【发布时间】:2021-08-05 02:46:16
【问题描述】:
我正在尝试实现列表的反转:
myLast :: [a] -> a
myLast [] = error "No end for empty lists!"
myLast [x] = x
myLast (_:xs) = myLast xs
myReverse :: [a] -> [a]
myReverse (x:xs) = myLast xs + myReverse xs
但我收到此错误:
/workspaces/hask_exercises/exercises/src/Lib.hs:42:32: error:
* Occurs check: cannot construct the infinite type: a ~ [a]
* In the second argument of `(+)', namely `myReverse xs'
In the expression: myLast xs + myReverse xs
In an equation for `myReverse':
myReverse (x : xs) = myLast xs + myReverse xs
* Relevant bindings include
xs :: [a] (bound at src/Lib.hs:42:14)
x :: a (bound at src/Lib.hs:42:12)
myReverse :: [a] -> [a] (bound at src/Lib.hs:41:1)
|
42 | myReverse (x:xs) = myLast xs + myReverse xs
| ^^^^^^^^^^^^
cannot construct the infinite type: a ~ [a] 是什么意思?我经常收到此错误,并想了解它的含义。
【问题讨论】:
-
你认为
+会做什么? -
++用于连接列表。 -
@JosephSible-ReinstateMonica
myLast xs是一个数字,myReverse xs是一个列表,所以它应该将数字添加到列表中 -
+用于将数字相加。:将一个元素粘贴到一个列表中,++连接两个列表。
标签: list haskell types infinite