Haskell 中两个 Maybe Int 的 Maybe 差异

Maybe difference of two Maybe Int in Haskell

我想计算列表的两个 elemIndex 值的差值。

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

我尝试了不同的方法来使用绑定运算符>>=,但到目前为止没有成功。理想情况下,我想要一个表达式 returns 两个整数之间的差异 Just 如果两者都是 Just,或者 Nothing 如果至少其中一个是 Nothing.

示例:

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

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

mydistancefunction (Just 3) (Nothing)
-- Nothing

如评论中所述,liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c will lift a binary function distance :: Num a => a -> a -> a to work with Maybe values because Maybe is an applicative

myDistance :: Num a => Maybe a -> Maybe a -> Maybe a
myDistance = liftA2 distance
  where
    distance x y = abs $ x - y