在Haskell中获得Maybe的价值

时间:2015-10-12 13:33:48

标签: haskell maybe

我正在实施一个使用myFunction的函数anotherFunction

anotherFunction是一个无法修改的外部函数。它返回Maybe类型的值。

myFunction是一个递归函数,用于检查另一个myFunction返回的值是Just值还是Nothing。如果它是Nothing,则返回Nothing,否则它将使用myFunction返回的纯值作为anotherFunction的参数。

基本上是这样的:

--These cannot be modified

data A = B | F a

anotherFunction :: x -> Maybe x
--Something here

myFunction :: A -> Maybe x 

--These can be modified
myFunction (F a) = {- if (myFunction a == Nothing) 
                        then Nothing 
                        else anotherFunction (pure value of (myFunction a)) -}

如何实现这一目标?

3 个答案:

答案 0 :(得分:2)

除非您在签名中有约束==,否则您将无法使用Eq a => Maybe a。执行此类操作的最佳方法是使用case语句:

case m of
    Just x -> anotherFunction x
    Nothing -> Nothing

Maybe这种模式非常常见,它构成了Monad的{​​{1}}个实例,为您提供了Maybereturn x = Just x的功能。

答案 1 :(得分:2)

您可以使用MyFunction匹配case返回的值:

case (myFunction a) of
  Nothing -> Nothing
  Just x -> anotherFunction x

然而,更简洁的方法是使用>>=

(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
myFunction (f a) = (myFunction a) >>= anotherFunction

或者您可以使用do表示法:

myFunction (f a) = do
  x <- myFunction a
  anotherFunction x

答案 2 :(得分:1)

假设您<ul class="product-list"> <!-- Insert Products here --> </ul> f都生成包含在g类型中的值(MaybeJust 3Just "three")。你可以把这两个组成:

Nothing

我为类型import Control.Monad f :: a -> Maybe b -- suppose these two are signatures of the given two functions g :: b -> Maybe c h :: a -> Maybe c -- this is the way you pass values from one h = f >=> g -- to the other and bail out when you see Nothing ab使用了方便的名称,以使构图更清晰,但请注意类型不是约束,c在一个签名中,与另一个签名中的a无关,实际类型是在具体上下文中使用这两个函数时决定的。

由于您似乎对a构造函数中的a没有任何限制,我想您希望它可能与F a不同。在这种情况下,函数A不能包含myFunction类型,因为您试图将A -> ...作为参数传递。