【发布时间】: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 iy。liftM2,实际上。所以,最简单的就是写do代码。