Failing with Maybe
In the previous chapter, we used the Maybe
type constructor to model computations that can fail. We have illustrated this on two little databases, one of functions and another of parameters for those functions:
funs :: [(String, Float -> Float)] funs = [("sine",sin),("cosine",cos),("increment",(+1))] params :: [(String,Float)] params = [("pi",pi),("zero",0),("x",5)]
With lookup :: Eq a => a -> [(a, b)] -> Maybe b
, we would fetch these by name:
fun :: String -> Maybe (Float -> Float) fun f = lookup f funs param :: String -> Maybe Float param p = lookup p params
Using the applicative operator (<*>)
, we can perform the two lookups side-by-side and, if both are successful, perform the function application:
prog :: Maybe Float prog = fun "inc" <*> param "one"
The side-by-side aspect of (<*>)
is not always appropriate. Sometimes...