時,我不明白爲什麼下面的代碼不會編譯:類型的錯誤編譯
append :: [a] -> [a] -> [a]
append xs ys = foldr (:) ys xs
traverse :: a -> [a] -> [[a]]
traverse x [] = [[x]]
traverse x (y:ys) = append [(x:y:ys)] (map (y:) (traverse x ys))
comb :: [a] -> [[a]]
comb [] = [[]]
comb (x:[]) = [[x]]
comb (x:y:[]) = [[x,y],[y,x]]
comb (x:xs) = map (traverse x) (comb xs)
它產生以下錯誤:
pr27.hs:13:20:
Couldn't match type `a' with `[a]'
`a' is a rigid type variable bound by
the type signature for comb :: [a] -> [[a]] at pr27.hs:10:1
Expected type: [a] -> [a]
Actual type: [a] -> [[a]]
In the return type of a call of `traverse'
In the first argument of `map', namely `(traverse x)'
Failed, modules loaded: none
但是當我加載只是traverse
並使用它在類似於上面的表達式中,我得到了期望的結果。這是怎麼回事?
Main> map (traverse 3) [[1,2],[2,1]]
[[[3,1,2],[1,3,2],[1,2,3]],[[3,2,1],[2,3,1],[2,1,3]]]
Tikhon已經解釋了這個問題,所以讓我試着給出解決方案。除非我錯誤地認爲,通過將'comb'的最後一個等式改爲'comb(x:xs)= concatMap(遍歷x)(comb xs)'或'comb(x:xs)= comb xs >> =遍歷x'。 – 2012-02-17 23:57:50