Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell equivalent of scala collect

I'm trying to read in a file containing key/value pairs of the form:

#A comment
a=foo
b=bar
c=baz
Some other stuff

With various other lines, as suggested. This wants to go into a map that I can then look up keys from.

My initial approach would be to read in the lines and split on the '=' character to get a [[String]]. In Scala, I would then use collect, which takes a partial function (in this case something like \x -> case x of a :: b :: _ -> (a,b) and applies it where it's defined, throwing away the values where the function is undefined. Does Haskell have any equivalent of this?

Failing that, how would one do this in Haskell, either along my lines or using a better approach?

like image 374
Impredicative Avatar asked Mar 26 '13 10:03

Impredicative


1 Answers

Typically this is done with the Maybe type and catMaybes:

catMaybes :: [Maybe a] -> [a]

So if your parsing function has type:

parse :: String -> Maybe (a,b)

then you can build the map by parsing the input string into lines, validating each line and returning just the defined values:

Map.fromList . catMaybes . map parse . lines $ s

where s is your input string.

like image 104
Don Stewart Avatar answered Nov 02 '22 19:11

Don Stewart