Lesson 16 of 16

Maybe

Maybe

Maybe represents a value that might be absent. Instead of null, Haskell uses:

  • Just x — the value x is present
  • Nothing — no value
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv a b = Just (a `div` b)

Pattern Matching on Maybe

describe :: Maybe Int -> String
describe Nothing  = "no value"
describe (Just x) = "got " ++ show x

fromMaybe

fromMaybe (from Data.Maybe) provides a default for Nothing:

import Data.Maybe (fromMaybe)

fromMaybe 0 (Just 42)   -- 42
fromMaybe 0 Nothing     -- 0

Your Task

Define safeHead that returns Just the first element of a list, or Nothing for an empty list. Then:

  • Print fromMaybe (-1) (safeHead [10, 20, 30])
  • Print fromMaybe (-1) (safeHead [])
Haskell loading...
Loading...
Click "Run" to execute your code.