gpt4 book ai didi

haskell - Haskell 中两个 Maybe Int 的 Maybe 区别

转载 作者:行者123 更新时间:2023-12-04 15:15:28 29 4
gpt4 key购买 nike

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

我尝试了不同的方法来使用绑定(bind)运算符 >>= 但到目前为止没有成功。理想情况下,我想要一个表达式,它返回两个 Int 之间差异的 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将提升二进制函数 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

关于haskell - Haskell 中两个 Maybe Int 的 Maybe 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64395705/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com