我无法理解为什么功能:
repli :: [a] -> Int -> [a]
repli xs n = concatMap (replicate n) xs
不能改写为:
repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n = (take n $ repeat x) : repli xs n
或
repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n = (replicate n x) : repli xs n
Ghci抱怨道:
Couldn't match expected type ‘a’ with actual type ‘[a]’
‘a’ is a rigid type variable bound by
the type signature for repli :: [a] -> Int -> [a]
at 99questions.hs:41:10
Relevant bindings include
xs :: [a] (bound at 99questions.hs:43:10)
x :: a (bound at 99questions.hs:43:8)
repli :: [a] -> Int -> [a] (bound at 99questions.hs:42:1)
In the first argument of ‘(:)’, namely ‘(replicate n x)’
In the expression: (replicate n x) : repli xs n
我不明白为什么,因为做了所有类型的计算,结果证明没问题。 repeat x
为[a]
,因此take n
为[a]
。所以它不应该抱怨。
答案 0 :(得分:6)
(:)
的签名是a -> [a] -> [a]
。因此,您不能在运营商的两侧都有列表。这是导致错误的原因。
您可以改为使用(++)
,其中包含签名[a] -> [a] -> [a]
。