Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse of 'concat': transforming a flattened list into a nested list [duplicate]

Tags:

haskell

Given a flattened list in Haskell:

['a', 'b','c','d']

how can I change it to:

[['a'], ['b'], ['c'], ['d']]
like image 934
igorvpcleao Avatar asked Nov 30 '22 01:11

igorvpcleao


1 Answers

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

like image 51
J. Abrahamson Avatar answered Dec 05 '22 04:12

J. Abrahamson