In Haskell, I can use the type a -> Maybe b
to model a function that either returns a value of type b
, or returns nothing (it fails).
If I have types a1, ..., a(n+1)
and functions f1, ..., fn
, with fi :: ai -> Maybe a(i+1)
for all i
, 1 <= i <= n
, I can chain the functions by using the >>=
operator of the Maybe
monad and write:
f1 x >>= f2 >>= f3 >>=... >>= fn
The >>=
operator ensures that each function is applied as long as its predecessor has returned a meaningful value. As soon as a function in the chain fails, the whole chain fails (returns Nothing
) and further functions in the chain are not evaluated.
I have a somewhat similar pattern in which I want to try several functions on the same input, and return as soon as one function succeeds. If all functions fail (return Nothing
), the whole computation should fail. More precisely, I have functions f1, ..., fn :: a -> Maybe b
and I define the function
tryFunctions :: [a -> Maybe b] -> a -> Maybe b
tryFunctions [] _ = Nothing
tryFunctions (f : fs) x = case f x of
Nothing -> tryFunctions fs x
r@(Just _) -> r
In a sense this is dual to the Maybe
monad in that a computation stops at the first success instead of at the first failure.
Of course, I can use the function I have written above but I was wondering if there is a better, well-established and idiomatic way of expressing this pattern in Haskell.
return f1 ?? f2 ?? f3 ?? DefaultValue;
Alternative
which is the symbol infix operator<|>
and is defined in terms of a Monoid