[英]Changing function to Maybe function in Haskell
Is it possible to write a function which takes a function like (Something -> Something)
, and returns it, but with a type (Maybe Something -> Maybe Something)
? 是否可以编写一个函数,该函数接受类似(Something -> Something)
的函数并返回它,但是返回类型(Maybe Something -> Maybe Something)
呢?
eg: 例如:
f :: Point -> Point
f x = [some code goes here]
makeItMaybe :: (Point -> Point) -> (Maybe Point -> Maybe Point)
makeItMaybe x = ???
I know it has something to do with Monads and Applicatives, but can't really figure out how. 我知道这与Monads和Applicatives有关,但无法真正弄清楚如何做。 I played around a bit with <*>
and <$>
, but didn't get anywhere. 我在<*>
和<$>
玩了一下,但是什么都没得到。
Any help or pointers in the right direction would be appreciated. 任何在正确方向上的帮助或指导将不胜感激。 Thanks! 谢谢!
I think you are looking for fmap
, which has type Functor f => (a -> b) -> fa -> fb
. 我认为您正在寻找fmap
,其类型为Functor f => (a -> b) -> fa -> fb
fmap
Functor f => (a -> b) -> fa -> fb
。 If you replace f
by Maybe
(since Maybe
is a functor) and put the parenthesis un the right place you get (a -> b) -> (Maybe a -> Maybe b)
. 如果用Maybe
替换f
(因为Maybe
是函子),然后将括号放在正确的位置,则您会得到(a -> b) -> (Maybe a -> Maybe b)
。 You were in the right direction with (<$>)
, which is just an alias for fmap
. 使用(<$>)
朝着正确的方向发展,这只是fmap
的别名。
So we have makeItMaybe fx = fmap fx
or, more simply, makeItMaybe = fmap
. 因此,我们有makeItMaybe fx = fmap fx
或更简单的是makeItMaybe = fmap
。
The function you want is fmap
: 您想要的功能是fmap
:
makeItMaybe = fmap
fmap
is defined by the Functor
typeclass: fmap
由Functor
类型类定义:
fmap :: Functor f => (a -> b) -> f a -> f b
Maybe
has a functor instance so fmap
specialised to Maybe
has type Maybe
有函子的实例,以便fmap
专门到Maybe
已经键入
(a -> b) -> Maybe a -> Maybe b
This functions satisfies the signature, but I don't know if it is what you want: 此函数满足签名,但是我不知道它是否是您想要的:
makeItMaybe :: (a -> a) -> (Maybe a -> Maybe a)
makeItMaybe f (Just x) = Just (f x)
makeItMaybe f Nothing = Nothing
As @baxbaxwalanuksiwe and @Lee pointed out, it is fmap
instance of Maybe
from the Functor
typeclass. 正如@baxbaxwalanuksiwe和@Lee指出的那样,它是Functor
类型类中Maybe
fmap
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.