Reputation: 73
How can I combine two different types of lists and traverse the result in Haskell?
For example:
input: [1,2,3] ['A','B','C'],
output: ["A1","A2","A3","B1","B2","B3","C1","C2","C3"].
I tried making an example using Int
and Char
, like:
combine :: Int -> Char -> String
combine a b = show b ++ show a
This doesn't work, however, because if I use this function for combine 3 'A'
, the output will be "'A'3"
, not "A3"
.
Upvotes: 2
Views: 710
Reputation: 26161
You may do as follows;
combiner :: [Char] -> [Int] -> [String]
combiner cs xs = (:) <$> cs <*> (show <$> xs)
*Main> combiner ['A','B','C'] [1,2,3]
["A1","A2","A3","B1","B2","B3","C1","C2","C3"]
Here (:) <$> cs
(where <$>
is infix fmap
) will construct an applicative list functor while show <$> xs
is like map show xs
yielding ["1","2","3"]
and by <*>
we just apply the applicative list to ["1","2","3"]
resulting ["A1","A2","A3","B1","B2","B3","C1","C2","C3"]
Upvotes: 2
Reputation: 476574
show :: Char -> String
will indeed put single quotes around the character:
*Main> show 'A'
"'A'"
But since a type String = [Char]
, we can use:
combine :: Int -> Char -> String
combine i c = c : show i
So here we construct a list of characters with c
as the head (the first character), and show i
(the representation of the integer) as tail.
Now we can use list comprehension to make a combination of two lists:
combine_list :: [Int] -> [Char] -> [String]
combine_list is cs = [combine i c | c <- cs, i <- is]
This then generates the output:
*Main> combine_list [1,2,3] ['A','B','C']
["A1","A2","A3","B1","B2","B3","C1","C2","C3"]
Upvotes: 3