How to get the value of a Maybe in Haskell

前端 未结 5 667
南旧
南旧 2021-01-31 08:15

I\'m relatively new to Haskell and began to read \"Real World Haskell\".

I Just stumbled over the type Maybe and have a question about how to receive the actual value fr

5条回答
  •  感情败类
    2021-01-31 09:06

    From the standard Prelude,

    maybe :: b -> (a -> b) -> Maybe a -> b
    maybe n _ Nothing = n
    maybe _ f (Just x) = f x
    

    Given a default value, and a function, apply the function to the value in the Maybe or return the default value.

    Your eliminate could be written maybe 0 id, e.g. apply the identity function, or return 0.

    From the standard Data.Maybe,

    fromJust :: Maybe a -> a
    fromJust Nothing = error "Maybe.fromJust: Nothing"
    fromJust (Just x) = x
    

    This is a partial function (does not return a value for every input, as opposed to a total function, which does), but extracts the value when possible.

提交回复
热议问题