Using Maybe type in Haskell

后端 未结 6 1976
孤独总比滥情好
孤独总比滥情好 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:13

    Alternatively you can pattern match:

    case maybeValue of
      Just value -> ...
      Nothing    -> ...
    
    0 讨论(0)
  • 2020-12-01 14:13

    Many people are against the use of fromJust, however it can be convenient if you are aware of what will happen when the lookup fails (error!!)

    Firstly you will need this:

    import Data.Maybe
    

    And then your lookup from a list of tuples will look like this

    Data.Maybe.fromJust $ lookup key listOfTuples
    

    For example, successful lookup:

    Data.Maybe.fromJust $ lookup "a" [("a",1),("b",2),("c",3)]
    1
    

    And horrible failure looks like this:

    Data.Maybe.fromJust $ lookup "z" [("a",1),("b",2),("c",3)]
    *** Exception: Maybe.fromJust: Nothing
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-12-01 14:27

    Sorry, I should have googled better.

    using the fromMaybe function is exactly what I need. fromMaybe will return the value in Maybe if it is not nothing, otherwise it will return a default value supplied to fromMaybe.

    http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Maybe.html

    0 讨论(0)
  • 2020-12-01 14:30

    Just as a side note: Since Maybe is a Monad, you can build computations using do-notation ...

    sumOfThree :: Maybe Int
    sumOfThree = do
      a <- someMaybeNumber
      b <- someMaybeNumber
      c <- someMaybeNumber
      let k = 42 -- Just for fun
      return (a + b + c + k)
    
    0 讨论(0)
  • 2020-12-01 14:31

    Examples for "maybe":

    > maybe 0 (+ 42) Nothing
    0
    > maybe 0 (+ 42) (Just 12)
    54
    
    0 讨论(0)
提交回复
热议问题