gpt4 book ai didi

haskell - 对包含 "Just"的 Maybe 返回进行操作

转载 作者:行者123 更新时间:2023-12-03 15:06:42 24 4
gpt4 key购买 nike

我有一个返回类型为 Maybe ([(Int,Int)],(Int,Int)) 的函数

我想从另一个函数调用它并对数据执行操作。

但是,返回值包含在 Just 中。 .第二种方法取([(Int,Int)],(Int,Int))因此不接受Just ([(Int,Int)],(Int,Int)) .

有什么方法可以修剪 Just在应用第二种方法之前?

我不完全理解 Just 的使用在 Maybe 内- 但是,有人告诉我第一个方法的返回类型必须是 Maybe .

最佳答案

您的问题有多种解决方案,均基于模式匹配。我假设你有两种算法(因为你没有命名它们,我会的):

algorithm1 :: a -> Maybe b
algorithm2 :: b -> c
input :: a

1) Pattern matching通常由 case 语句(如下)或函数完成。
let val = algorithm1 input
in case val of
Nothing -> defaultValue
Just x -> algorithm2 x

所有其他介绍的解决方案都使用模式匹配,我只是介绍为您执行模式匹配的标准函数。

2)前奏(和Data.Maybe)有一些内置函数来处理 Maybe s。 maybe功能很好,建议大家用。它在标准库中定义为:
maybe :: c -> (b -> c) -> Maybe b -> c
maybe n _ Nothing = n
maybe _ f (Just x) = f x

您的代码如下所示:
maybe defaultValue algorithm2 (algorithm1 input)

3) 因为 Maybe 是 functor你可以使用 fmap .如果您没有默认值,这更有意义。定义:
instance  Functor Maybe  where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)

所以你的代码看起来像:
fmap algorithm2 (algorithm1 input)

此输出将是 Maybe值( Nothing 如果 algorithm1 的结果是 Nothing )。

4) 最后,强烈建议使用 fromJust .仅当您确定第一个算法将返回 Just x 时才使用它(而不是 Nothing )。当心!如果您调用 fromJust valval = Nothing然后你会得到一个异常(exception),这在 Haskell 中是不受欢迎的。它的定义:
fromJust          :: Maybe b -> b
fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
fromJust (Just x) = x

让您的代码看起来像:
algorithm2 (fromJust (algorithm1 input))

关于haskell - 对包含 "Just"的 Maybe 返回进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375483/

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