[英]Why does this function take an [[a]]?
我正在編寫Haskell代碼,練習尾部遞歸來反轉列表,並提出了以下解決方案:
reverseh' [] list = list
reverseh' (x:xs) list = reverseh' (xs) (x ++ list)
reverse' x = reverseh' x []
它僅適用於列表列表,但我希望它具有類型簽名[a] -> [a]
。
您能在這里解釋我做錯了嗎?
如果您沒有獲得期望的類型,則最好添加一個顯式類型簽名以告訴編譯器您想要的類型是什么,這里:
reverseh' :: [a] -> [a] -> [a]
然后,您會收到一個編譯錯誤:
Couldn't match expected type `[a]' with actual type `a'
`a' is a rigid type variable bound by
the type signature for reverseh' :: [a] -> [a] -> [a]
at reverseh.hs:1:14
Relevant bindings include
list :: [a] (bound at reverseh.hs:3:18)
xs :: [a] (bound at reverseh.hs:3:14)
x :: a (bound at reverseh.hs:3:12)
reverseh' :: [a] -> [a] -> [a] (bound at reverseh.hs:2:1)
In the first argument of `(++)', namely `x'
In the second argument of reverseh', namely `(x ++ list)'
這告訴您,在(x ++ list)
, x
必須為[a]
類型以便進行類型檢查,但是考慮到類型簽名, x
實際上是a
類型。 因此,您想用++
a -> [a] -> [a]
類型的函數替換++
,因此您可以使用(x : list)
。
由於第二行中的(x ++ list)
表達式,typechecker認為x :: [a]
。 我想你想寫(x : list)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.