我正在做来自haskell.mooc.fi/Exercises7的Set7.hs
-- Ex 5: reverse a NonEmpty list.
--
-- PS. The Data.List.NonEmpty type has been imported for you
-- below doesn't work
-- reverseNonEmpty :: NonEmpty a -> NonEmpty a
-- reverseNonEmpty (h:|tail) = head reversed :| (tail reversed)
-- where
-- reversed = reverse (h:tail)
-- below works
reverseNonEmpty :: NonEmpty a -> NonEmpty a
reverseNonEmpty (h :| tail) = head reversed :| revTail
where
reversed = reverse (h : tail)
-- revTail = (tail reversed) - this doesn't work, but WHY???
(_:revTail) = reversed
错误信息是:
Set7.hs:152:15: error:
• Couldn't match expected type ‘[a] -> t’ with actual type ‘[a]’
• The function ‘tail’ is applied to one argument,
but its type ‘[a]’ has none
In the expression: tail reversed
In an equation for ‘revTail’: revTail = tail reversed
• Relevant bindings include
revTail :: t (bound at Set7.hs:152:5)
reversed :: [a] (bound at Set7.hs:151:5)
tail :: [a] (bound at Set7.hs:149:23)
h :: a (bound at Set7.hs:149:18)
reverseNonEmpty :: NonEmpty a -> NonEmpty a
(bound at Set7.hs:149:1)
|
152 | revTail = tail reversed
我不明白错误消息,有什么问题吗tail reversed
?
为什么具有模式匹配功能的版本(_:revTail) = reversed
有效?
reverseNonEmpty (h :| tail) = ...
您自己绑定了名称
tail
,以引用NonEmpty
. 所以这会影响正常的tail
函数,并且无法在 的体内引用它reverseNonEmpty
。这就是为什么错误消息告诉您它
tail
具有类型[a]
并且不能应用于参数。为了避免这些问题,我强烈建议您在启用警告的情况下编译代码。
-Wall
您可以为此使用 GHC 标志。发出警告后,GHC 发现了问题:
GHC 在此警告范围内有两个事物,并且都被命名为
tail
。一种是库函数,另一种是通过模式匹配绑定的局部变量。正如其他人已经说过的。请不要使用与外部作用域中已存在的变量名称相同的变量名称。您分配
tail
到输入的尾部,因此这不起作用。然而,我认为目的是通过递归来编写相反的内容。我们可以递归:
我将实施这些
…
部分作为练习。