【发布时间】:2018-03-16 01:48:30
【问题描述】:
我是 Haskell 的初学者。我正在尝试创建一个具有两个参数的函数:一个字符和一个字符串。 这个函数应该遍历字符串并检查给定的字符是否在字符串中,然后返回一个整数列表,表示字符在字符串中的位置。
我的代码是:
tegnPose :: Char -> String -> [Int]
tegnPose c [] = []
tegnPose c (x:xs) = [if not (xs !! a == c)
then [a] ++ tegnPose c xs
else tegnPose c xs |a <- [0.. length xs - 1]]
这是一个带有列表理解的递归函数。
我得到的错误:
Uke4.hs:14:7: error:
* Couldn't match expected type `Int' with actual type `[Int]'
* In the expression: [a] ++ tegnPose c xs
In the expression:
if not (xs !! a == c) then [a] ++ tegnPose c xs else tegnPose c xs
In the expression:
[if not (xs !! a == c) then
[a] ++ tegnPose c xs
else
tegnPose c xs |
a <- [0 .. length xs - 1]]
|
14 | then [a] ++ tegnPose c xs
| ^^^^^^^^^^^^^^^^^^^^
Uke4.hs:15:7: error:
* Couldn't match expected type `Int' with actual type `[Int]'
* In the expression: tegnPose c xs
In the expression:
if not (xs !! a == c) then [a] ++ tegnPose c xs else tegnPose c xs
In the expression:
[if not (xs !! a == c) then
[a] ++ tegnPose c xs
else
tegnPose c xs |
a <- [0 .. length xs - 1]]
|
15 | else tegnPose c xs |a <- [0.. length xs - 1]]
我不明白不匹配是如何发生的,因为递归函数应该只是运行。
【问题讨论】:
-
列表推导默认返回一个列表。尝试在其中返回另一个列表会给您一个列表列表,这不是您想要的。我会重写它以完全避免理解。
标签: haskell types int mismatch