我正在做 Set7.hs 来自 haskell.mooc.fi/ Exercises7
-- 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]
并且不能应用于参数。