Using Maybe type in Haskell

后端 未结 6 2000
孤独总比滥情好
孤独总比滥情好 2020-12-01 13:46

I\'m trying to utilize the Maybe type in Haskell. I have a lookup for key, value tuples that returns a Maybe. How do I access the data that was wrapped by Maybe? For exam

6条回答
  •  庸人自扰
    2020-12-01 14:14

    You could use Data.Maybe.fromMaybe, which takes a Maybe a and a value to use if it is Nothing. You could use the unsafe Data.Maybe.fromJust, which will just crash if the value is Nothing. You likely want to keep things in Maybe. If you wanted to add an integer in a Maybe, you could do something like

    f x = (+x) <$> Just 4
    

    which is the same as

    f x = fmap (+x) (Just 4)
    

    f 3 will then be Just 7. (You can continue to chain additional computations in this manner.)

提交回复
热议问题