Reputation: 581
I'm new to Haskell and I'm trying to add a string to a list of strings using the :
operator, but somehow it's not working properly... This code is working:
sl:(printH header):sl:(map printR t)
but when I try to add the string sl
on the end as well, like this:
sl:(printH header):sl:(map printR t):sl
it throws out an error, which doesn't make any sense to me (sincwe the other joins did go well):
Couldn't match type '[Char]' with 'Char'
Expected type: [String] -> Char
Actual type: [String] -> String
In the first argument of 'map', namely 'printR'
...
Does anyone know why this happens?
Upvotes: 1
Views: 2634
Reputation: 9778
Prelude> :type (:)
(:) :: a -> [a] -> [a]
This tells you that the (:)
function takes a single item on the left and a list on the right. Given:
a :: t
b :: t
c :: [t],
a:b:c
parses as a:(b:c)
, which works, because the expression b:c
is of type [t]
. Meanwhile, b:c:a
parses as b:(c:a)
, which doesn't work, because c:a
is ill-typed: a
should be of type [t]
, but is actually of type t
, and c
should be of type t
, but is actually of type [t]
. In your example, t
is Char
.
If you want to add a single item to the end of a list, you can use concatenate (++)
:
xs ++ [i]
Upvotes: 5
Reputation: 5808
Operator :
is used to prepend an element to a list. In your expression
sl:(printH header):sl:(map printR t)
the first three expressions (sl
, printH header
and sl
) are list elements (strings, apparently), whereas the fourth one (map printR t
) is the list to prepend those to.
If you want to append an element to the list, you cannot use operator :
. You will have to use something like:
sl:(printH header):sl:(map printR t) ++ [sl]
Upvotes: 3