Haskell 为类型类的子类定义方法
我试过这个:Haskell 为类型类的子类定义方法,haskell,typeclass,Haskell,Typeclass,我试过这个: class Functor f where fmap :: (a -> b) -> f a -> f b class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b fmap f x = pure f <*> x 如何为Applicative和Funct
class Functor f where
fmap :: (a -> b) -> f a -> f b
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
fmap f x = pure f <*> x
如何为
Applicative
和Functor
的其他子类定义fmap
?你理解错了:没有任何子类概念在起作用
当存在这样的类约束时:class(Functor f)=>Applicative f
,这意味着要将某个类型定义为Applicative
实例,它应该已经是Functor
的实例
考虑数据类型可能
:
您可以像这样定义它的Functor
实例:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
instance Applicative Maybe where
pure = Just
(Just f) <*> (Just x) = Just (f x)
_ <*> _ = Nothing
class Functor f where
fmap :: (a -> b) -> f a -> f b
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
它的应用
实例如下:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
instance Applicative Maybe where
pure = Just
(Just f) <*> (Just x) = Just (f x)
_ <*> _ = Nothing
class Functor f where
fmap :: (a -> b) -> f a -> f b
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
您不需要另外将
fmap
放入Applicative
typeclass中。类约束意味着所有具有Applicative
的类型都需要定义fmap
。Haskell尚未实现您所要求的。但是,有一个关于此功能的建议,名为,它允许您声明:
class Functor f => Applicative f where
return :: x -> f x
(<*>) :: f (s -> t) -> f s -> f t
instance Functor f where
fmap = (<*>) . pure
class函子f=>Applicative f其中
return::x->fx
()::f(s->t)->f s->f t
实例函子f,其中
fmap=()。纯净的
这就是继承的含义。@ThePiercingPrince我更新了解释。最好不要试图在OOP语言继承和Haskell之间找到相似之处。()
已经找到了,它是fmap