List 为什么添加错误案例会破坏我对last的实现?
这段代码运行得非常好:List 为什么添加错误案例会破坏我对last的实现?,list,haskell,List,Haskell,这段代码运行得非常好: last' :: [a] -> a last' (x:[]) = x last' (x:xs) = last xs 但如果我试图补充: last' [] = error "Empty list" 任何地方。我得到这个错误: "Couldn't match type 'a' with [Char] -> a0' 'a' is a rigid type variable bound by the type signature for last' :: [a]
last' :: [a] -> a
last' (x:[]) = x
last' (x:xs) = last xs
但如果我试图补充:
last' [] = error "Empty list"
任何地方。我得到这个错误:
"Couldn't match type 'a' with [Char] -> a0'
'a' is a rigid type variable bound by the type signature for last' :: [a] -> a
In the expression: error
in any equation for last': last [] = error "Empty list"
为什么会这样?当我为empy列表添加case时,我对head、tail和init的实现并没有发出尖叫
我是个白痴。我有打字错误。谢谢 添加
错误
不会破坏您的代码。这应该是正确的实施方式:
last' :: [a] -> a
last' (x:[]) = x
last' (x:xs) = last' xs -- xs not x
last' [] = error "Empty list"
还有那个错误吗?这一行
last'(x:xs)=last xs
调用RHS上的内置版本的last
。谢谢你在第三行发现我的打字错误。我还拼错了错误,很可能是把它弄坏了。太累了,应该睡觉再编码。为什么检查错误是最后一个要做的而不是第一个?@user241576在这种情况下,这并不重要。但把它放在第一位是个好习惯。