Haskell,类型匹配问题

rub*_*bik 1 haskell type-mismatch

我无法理解为什么功能:

repli :: [a] -> Int -> [a]
repli xs n = concatMap (replicate n) xs
Run Code Online (Sandbox Code Playgroud)

不能改写为:

repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n = (take n $ repeat x) : repli xs n
Run Code Online (Sandbox Code Playgroud)

要么

repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n = (replicate n x) : repli xs n
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我不明白为什么,因为做所有的类型计算,结果证明是好的.repeat x是的[a],take n是的[a].所以不应该抱怨.

shr*_*t18 6

签名(:)a -> [a] -> [a].因此,您不能在运营商的两侧都有列表.这是你的错误的原因.

你可以改为使用(++),它有签名[a] -> [a] -> [a].

  • 在第一个功能(工作的)中甚至有**concat**Map! (2认同)