bas*_*iat 3 haskell functional-programming list tail pattern-matching
我正在做来自haskell.mooc.fi/Exercises7的Set7.hs
\n-- Ex 5: reverse a NonEmpty list.\n--\n-- PS. The Data.List.NonEmpty type has been imported for you\n\n-- below doesn\'t work\n-- reverseNonEmpty :: NonEmpty a -> NonEmpty a\n-- reverseNonEmpty (h:|tail) = head reversed :| (tail reversed)\n-- where \n-- reversed = reverse (h:tail)\n\n-- below works\nreverseNonEmpty :: NonEmpty a -> NonEmpty a\nreverseNonEmpty (h :| tail) = head reversed :| revTail\n where\n reversed = reverse (h : tail)\n -- revTail = (tail reversed) - this doesn\'t work, but WHY???\n (_:revTail) = reversed\nRun Code Online (Sandbox Code Playgroud)\n错误信息是:
\nSet7.hs:152:15: error:\n \xe2\x80\xa2 Couldn\'t match expected type \xe2\x80\x98[a] -> t\xe2\x80\x99 with actual type \xe2\x80\x98[a]\xe2\x80\x99\n \xe2\x80\xa2 The function \xe2\x80\x98tail\xe2\x80\x99 is applied to one argument,\n but its type \xe2\x80\x98[a]\xe2\x80\x99 has none\n In the expression: tail reversed\n In an equation for \xe2\x80\x98revTail\xe2\x80\x99: revTail = tail reversed\n \xe2\x80\xa2 Relevant bindings include\n revTail :: t (bound at Set7.hs:152:5)\n reversed :: [a] (bound at Set7.hs:151:5)\n tail :: [a] (bound at Set7.hs:149:23)\n h :: a (bound at Set7.hs:149:18)\n reverseNonEmpty :: NonEmpty a -> NonEmpty a\n (bound at Set7.hs:149:1)\n |\n152 | revTail = tail reversed\nRun Code Online (Sandbox Code Playgroud)\n我不明白错误消息,有什么问题吗tail reversed?
为什么具有模式匹配功能的版本(_:revTail) = reversed有效?
reverseNonEmpty (h :| tail) = ...
您自己绑定了名称tail,以引用NonEmpty. 所以这会影响正常的tail函数,并且无法在 的体内引用它reverseNonEmpty。
这就是为什么错误消息告诉您它tail具有类型[a]并且不能应用于参数。