Haskell Maybe Combinators
Haskell Maybe combinators are small functions that work with a value that may be missing. They supply fallbacks, change present values, and drop missing ones.
FromMaybe supplies a fallback
A present value stays 5. A missing value becomes the fallback 0.
import Data.Maybe (fromMaybe)
main :: IO ()
main = do
print (fromMaybe 0 (Just 5), fromMaybe 0 Nothing)Maybe folds a value or a fallback
Doubling a present 21 gives 42. A missing value gives the fallback 0.
main :: IO ()
main = do
print (maybe 0 (*2) (Just 21), maybe 0 (*2) Nothing)MapMaybe keeps only good results
Negative and zero inputs give Nothing. Positive inputs give ten times their value.
import Data.Maybe (mapMaybe)
main :: IO ()
main = do
print (mapMaybe (\x -> if x > 0 then Just (x * 10) else Nothing) [-1,2,0,3])Example
import Data.Maybe (catMaybes)
main :: IO ()
main = do
let readings = [Just 10, Nothing, Just 20, Just 5]
let good = catMaybes readings
print (length good, sum good)Key points
- Maybe: a Maybe value is Just a value or Nothing for a missing value.
- FromMaybe: fromMaybe supplies a fallback when the value is Nothing.
- Maybe fold: maybe takes a fallback, a function, and a Maybe value and returns one plain result.
- MapMaybe: mapMaybe keeps only the Just results after applying a function that returns Maybe.
- CatMaybes: catMaybes drops every Nothing and keeps every Just value.
In this example, the program holds four readings with one missing value. It drops the missing value and keeps the three good ones. It prints how many good readings remain and their total.
Note
these combinators never crash on Nothing, so no case split is needed.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does fromMaybe 0 Nothing return?