【问题标题】:Maybe difference of two Maybe Int in HaskellHaskell中两个Maybe Int的可能差异
【发布时间】:2020-10-16 20:03:08
【问题描述】:

我想计算一个列表的两个 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

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

例子:

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

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

mydistancefunction (Just 3) (Nothing)
-- Nothing

【问题讨论】:

  • 你知道liftA2吗?
  • @RobinZigmond 我不是——但现在,多亏了你,我才成为。
  • 你不需要一个 monad 来做这件事,但如果你要手写一篇文章,它看起来像 ib >>= \b -> iy >>= \y -> Just $ b - y。重要的属性是它是嵌套的,即使括号在 Haskell 中是隐式的。
  • 那是ib >>= (\b -> iy >>= (\y -> (Just $ b - y))) 明确写出括号。但最简单的方法是编写do 代码do { b <- ib ; y <- iy ; return (b - y) }。它等同于liftA2 (-) ib iyliftM2,实际上。所以,最简单的就是写do 代码。

标签: haskell monads


【解决方案1】:

如 cmets 中所述,liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c 将提升二进制函数 distance :: Num a => a -> a -> a 以使用 Maybe 值,因为 Maybe is an applicative

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

【讨论】:

  • 除了固定数量的liftA2 & liftA3 用于简单的情况外,在f <$> x1 <*> … <*> xN 仿函数和应用运算符的模式中编写这种东西也很常见。使用问题中的示例,那就是:distance = abs <$> ((-) <$> ib <*> iy)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-03-06
相关资源
最近更新 更多