Given a flattened list in Haskell:
['a', 'b','c','d']
how can I change it to:
[['a'], ['b'], ['c'], ['d']]
One way to describe what you want to do is to take each element in your list and wrap it, individually, with another list. Or, you'd like to perform the operation 'a' ---> ['a']
to each element of the list.
Whenever you're speaking about turning "each element of the list, individually, into something else" you're talking about a map
[0] and so we'll write this function a bit like
example :: [Char] -> [[Char]]
example cs = map _ cs
Where the _
is the function 'a' ---> ['a']
. This function can be written as an explicit anonymous function, though
example :: [Char] -> [[Char]]
example cs = map (\c -> [c]) cs
And this will achieve what we need!
But we can go a little further. First, in Haskell you're allowed to drop the last argument applied if it's the same as the last input argument. Or, more concretely, we can also write example
as
example :: [Char] -> [[Char]]
example = map (\c -> [c])
by simply deleting the cs
in both the argument list and as an argument to map
. Second, we can take note that example
's type is weaker than it could be. A better way of writing it is certainly
example :: [a] -> [[a]]
example = map (\c -> [c])
which reflects the fact that we didn't use anything specific to Char
on the inside.
[0] Or, more generally, an fmap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With