Maybe difference of two Maybe Int in Haskell

Viewed 203

I want to compute the difference of two elemIndex values for a list.

colours = ["blue", "red", "green", "yellow"]

ib = elemIndex "blue" colours
-- Just 0

iy = elemIndex "yellow" colours
-- Just 3

-- the following obviously does not work
distance = abs $ ib - iy

I've tried different ways to use the bind operator >>= but no success so far. Ideally, I'd want an expression that returns a Just of the difference between the two Ints if both are Just, or Nothing if at least one of them is Nothing.

Example:

mydistancefunction (Just 0) (Just 3)
-- Just 3

mydistancefunction (Just 1) (Just 2)
-- Just 1

mydistancefunction (Just 3) (Nothing)
-- Nothing
1 Answers
Related