对包含“Just"的 Maybe 的返回进行操作 [英] Operating on a return from a Maybe that contains "Just"
问题描述
我有一个返回类型为 Maybe ([(Int,Int)],(Int,Int))
我想从另一个函数调用它并对数据执行操作.
I would like to call this from another function and perform an operation on the data.
然而,返回值包含在 Just
中.第二种方法采用 ([(Int,Int)],(Int,Int))
,因此不会接受 Just ([(Int,Int)],(Int,Int))
.
However, the return value is contained within Just
. The second method takes ([(Int,Int)],(Int,Int))
and therefore will not accept Just ([(Int,Int)],(Int,Int))
.
有没有办法在应用第二种方法之前修剪Just
?
Is there a way I can trim the Just
before applying the second method?
我不完全理解在 Maybe
中使用 Just
- 但是,我被告知第一个 Method 的返回类型必须是 Maybe
.
I don't fully understand the use of Just
within Maybe
- however, I have been told that the return type for the first Method must be Maybe
.
推荐答案
您的问题有多种解决方案,均基于模式匹配.我假设你有两种算法(因为你没有命名它们,我会的):
There are several solutions to your problem, all based around pattern matching. I'm assuming you have two algorithms (since you didn't name them, I will):
algorithm1 :: a -> Maybe b
algorithm2 :: b -> c
input :: a
1) 模式匹配通常通过 case 语句(如下)或一个函数.
1) Pattern matching is typically done from either a case statement (below) or a function.
let val = algorithm1 input
in case val of
Nothing -> defaultValue
Just x -> algorithm2 x
所有其他提供的解决方案都使用模式匹配,我只是展示为您执行模式匹配的标准函数.
All other presented solutions use pattern matching, I'm just presenting standard functions that perform the pattern matching for you.
2) Prelude(和Data.Maybe)有一些内置函数来处理Maybe
.可能 功能很棒,建议大家使用.它在标准库中定义为:
2) The prelude (and Data.Maybe) have some built-in functions to deal with Maybe
s. The maybe function is a great one, I suggest you use it. It's defined in standard libraries as:
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.如果您没有默认值,这更有意义.定义:
3) Since Maybe is a functor you could use fmap. This makes more sense if you don't have a default value. The definition:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
所以你的代码看起来像:
So your code would look like:
fmap algorithm2 (algorithm1 input)
此输出将是一个 Maybe
值(如果 algorithm1 的结果是 Nothing
,则为 Nothing
).
This output will be a Maybe
value (Nothing
if the result of algorithm1 is Nothing
).
4) 最后,强烈建议不要使用 fromJust
.仅当您确定第一个算法将返回 Just x
(而不是 Nothing
)时才使用它.当心!如果你在 val = Nothing
时调用 fromJust val
那么你会得到一个异常,这在 Haskell 中是不受欢迎的.其定义:
4) Finally, and strongly discouraged, is fromJust
. Only use it if you are positive the first algorithm will return Just x
(and not Nothing
). Be careful! If you call fromJust val
when val = Nothing
then you get an exception, which is not appreciated in Haskell. Its definition:
fromJust :: Maybe b -> b
fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
fromJust (Just x) = x
让你的代码看起来像:
algorithm2 (fromJust (algorithm1 input))
这篇关于对包含“Just"的 Maybe 的返回进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!