在 Haskell 中,类 Functor
声明为:
class Functor f where
fmap :: (a -> b) -> f a -> f b
可以输入变量
a
和 b
是函数类型,还是必须是非函数类型?如果它们可以是函数类型,那不就是类
Functor
吗?与 Applicative
类有效地相同, 在制作 fmap
方面能够应用于具有任意数量参数的函数吗?根据 Hutton 在 Haskell 中的编程所说:Functors abstract the idea of
fmap
mapping a function over each element of a structure. Applicatives generalize this idea to allowfmap
mapping functions with any number of arguments to be mapped, rather than being restricted to functions with a single argument.
在应用中:
fmap0 :: a -> f a fmap0 = pure fmap1 :: (a -> b) -> f a -> f b fmap1 g x = pure g <*> x fmap2 :: (a -> b -> c) -> f a -> f b -> f c fmap2 g x y = pure g <*> x <*> y fmap3 :: (a -> b -> c -> d) -> f a -> f b -> f c -> f d fmap3 g x y z = pure g <*> x <*> y <*> z
类(class)
Applicative
声明为:class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b
谢谢。
最佳答案
Can type variables
a
andb
be function types
- 好,当然。
isn't it that class
Functor
become effectively the same as classApplicative
不,绝对不是。如果将函数类型插入
a
或 b
的fmap
签名,你会得到类似的东西fmap :: ((x -> y) -> b) -> f (x -> y) -> f b
或者
fmap :: (a -> p -> q) -> f a -> f (p -> q)
但至关重要的是,
fmap
总是只取一个 f _
Wrapped-value 并准确地吐出一个这样的值。 Applicative
同时允许你接受任意数量的包装值,只要你给它一个函数来处理包含的值。
关于haskell - 在类 Functor 的声明中,类型变量可以是函数类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57085023/