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