2 ms·
As I just wrote elsewhere, the typical ways you get from Maybe x to x in Haskell don't have room to get tripped. There is a function, fromMaybe, which takes a
by dllthomas 12y ago
As I just wrote elsewhere, the typical ways you get from Maybe x to x in Haskell don't have room to get tripped.
There is a function, fromMaybe, which takes a Maybe x and gives you an x... but it also takes a default!
Often even more useful is the maybe function:
maybe :: output -> (input -> output) -> Maybe input -> output
This takes a default output to use if you're given Nothing, a function to apply to the input and generate an output if you're given Just an input, and Maybe the input, and gives you the resulting output. As I said this is often more useful than "and use this default", because quite often the value you want to generate when it's Nothing is outside the image of the input under the function in question. For instance:
maybe "no number" show maybe_integer
There's no number I can pass to show to get "no number", maybe lets me very conveniently avoid trying to force one.