Reputation: 535
I'm to use the replicate function that Haskell has (replicate 3 'x' = ['x','x','x']
) but I'm trying to add it to a list that already exists.
Prelude > let k = ['d','f','g']
Prelude > (replicate 3 'd':k)
but I keep getting the error,
Couldn't match type 'Char' with '[Char]'
Expected type: [[Char]]
Actual type: [Char]
Is there a way to do this?
Upvotes: 1
Views: 211
Reputation: 44634
k
and replicate 3 'd'
each have a type of [Char]
.
ghci> :t k
k :: [Char]
ghci> :t replicate 3 'd'
replicate 3 'd' :: [Char]
However, the type of (:)
is a -> [a] -> [a]
: it takes a single a
and adds it to the list of a
s.
ghci> :t (:)
(:) :: a -> [a] -> [a]
So Haskell's giving you a type error because you can't apply (:)
to two things of type [Char]
. In other words, you can't put a [Char]
inside a [Char]
.
What we really need is a function of type [a] -> [a] -> [a]
which concatenates the two lists. It happens that this function is called (++)
.
ghci> :t (++)
(++) :: [a] -> [a] -> [a]
ghci> replicate 3 'd' ++ k
"ddddfg"
Upvotes: 4