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?
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.
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