In Haskell String is an alias for [Char]:
type String = [Char]
If you just want a function that converts a single char to a string you could e.g. do
charToString :: Char -> String
charToString c = [c]
If you prefer pointfree style you could also write
charToString :: Char -> String
charToString = (:[])
Answer from Thies Heidecke on Stack OverflowIn Haskell String is an alias for [Char]:
type String = [Char]
If you just want a function that converts a single char to a string you could e.g. do
charToString :: Char -> String
charToString c = [c]
If you prefer pointfree style you could also write
charToString :: Char -> String
charToString = (:[])
A String is just a [Char]
But that's just a nice way of saying
'H':'E':'L':'L':'O':[]
So to make it a [String] we could do:
['H':'E':'L':'L':'O':[]]
How to combine the letters in two strings in haskell - Stack Overflow
haskell - How do I add a char to every item in a list? - Stack Overflow
How to simplify string concatenation in Haskell? - Stack Overflow
How to combine two strings i Haskell and return a new string - Stack Overflow
++ works only for lists, but x and y are only Char. After all, they're elements from a String (= [Char]), whereas the LYAH example had lists of lists of Char: [String] = [[Char]]:
-- [a] -> [a] -> [a]
-- vv vv
[y ++ ' ' ++ y | x <- "abd", y <- "bcd"]
-- ^ ^ ^
-- Char Char
-- vs
-- [String] [String]
-- vvvvvvvvvv vvvvv
[adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
-- ^^^^^^^ ^^^^
-- String String
Instead, use (:) to cons the characters on each other and onto the empty list:
[x : ' ' : y : [] | x <- "abd", y <- "bcd"]
x ++ ' ' ++ y
The actual problem here is, you are trying to concatenate three characters, with a function defined only for list of items.
++ will actually concatenate two lists, not two individual items and give a list.
So, you can fix your program either by converting all the characters to strings, like this
> [[x] ++ " " ++ [y] | x <- "ab", y <- "cd"] ["a c","a d","b c","b d"]Note the
" ", not' '. Because" "means a string with just a space character, but' 'means just the space character.Or, convert
yto a String, useconsoperator with the' ', and concatenate it toxconverted to a string, like this> [[x] ++ (' ' : [y]) | x <- "ab", y <- "cd"] ["a c","a d","b c","b d"]Or, even simpler and intutive, as suggested by chi, create a list of characters, like this
> [[x, ' ', y] | x <- "ab", y <- "cd"] ["a c","a d","b c","b d"]
Note: Wrapping a character with [] makes it a list of characters with just one character in it. It basically becomes a String.