我正在实施一个使用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)) -}
如何实现这一目标?
答案 0 :(得分:2)
除非您在签名中有约束==
,否则您将无法使用Eq a => Maybe a
。执行此类操作的最佳方法是使用case
语句:
case m of
Just x -> anotherFunction x
Nothing -> Nothing
Maybe
这种模式非常常见,它构成了Monad
的{{1}}个实例,为您提供了Maybe
和return 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
类型中的值(Maybe
,Just 3
,Just "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
,a
和b
使用了方便的名称,以使构图更清晰,但请注意类型不是约束,c
在一个签名中,与另一个签名中的a
无关,实际类型是在具体上下文中使用这两个函数时决定的。
由于您似乎对a
构造函数中的a
没有任何限制,我想您希望它可能与F a
不同。在这种情况下,函数A
不能包含myFunction
类型,因为您试图将A -> ...
作为参数传递。