Search code examples
stringhaskelldictionarywords

Split list of strings into list of lists of strings


I have a list of strings. I want to split each of the strings on space, e.g. using words, resulting in a list of lists of strings. Unfortunately I can't use map words myList because map expects [a] -> [b], whereas I want [a] -> [[b]]. How would I go about this?

The other option off the top of my head is a recursive function where I split off the head string from my original list, words it and then analyse the result there and then, but I was trying to do it with pre-existing functions and a one-liner.


Solution

  • The type signature of 'map' is

    map :: (a -> b) -> [a] -> [b]
    

    The type signature of 'words' is

    words :: String -> [String]
    

    Therefore, the type signature of 'map words' is

    map words :: [String] -> [[String]]
    

    Hey, that's exactly what you want! Let's give it a try.

    map words ["hello world","stack exchange"]
    

    outputs:

    [["hello","world"],["stack","exchange"]]