Is there a better way to have optional function arguments in Haskell?

Perhaps some nice notation would be easier on the eyes:

(//) :: Maybe a -> a -> a
Just x  // _ = x
Nothing // y = y
-- basically fromMaybe, just want to be transparent

multiProduct req1 opt1 opt2 opt3 = req1 * (opt1 // 10) * (opt2 // 20) * (opt3 // 30)

If you need to use the parameters more than once, I suggest going with @pat’s method.

EDIT 6 years later

With ViewPatterns you can put the defaults on the left.

{-# LANGUAGE ViewPatterns #-}

import Data.Maybe (fromMaybe)

def :: a -> Maybe a -> a
def = fromMaybe

multiProduct :: Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int
multiProduct req1 (def 10 -> opt1) (def 20 -> opt2) (def 30 -> opt3)
  = req1 * opt1 * opt2 * opt3

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)