问题描述
我试图学习Haskell,并且我通过了所有的基础知识。但是现在我陷入困境,试图让我的脑袋绕过仿函数。我读过一个仿函数将一个类别转换为另一个类别。这意味着什么?
我知道需要问很多问题,但是任何人都可以给我一个纯英文的函数说明或者简单用例?
模糊解释是 Functor
是某种容器和一个相关的函数 fmap
,允许你改变包含的内容,给定一个函数来转换包含的内容。
例如,列表就是这种类型的容器,例如 fmap(+1)[1,2,3,4]
得到 [2,3,4,5]
。
也许
也可以作为一个函子,例如 fmap toUpper(Just'a')
产生只是'A'
。
$ b
fmap
的一般类型非常巧妙地显示了正在发生的事情:
fmap :: Functor f => (a - > b) - > f a - > f b
特殊版本可能会更清晰。以下是列表版本:
fmap ::(a - > b) - > [a] - > [b]
和Maybe版本:
fmap ::(a - > b) - >也许是 - >也许b
您可以获得标准 Functor $ c $通过使用
:i Functor
查询GHCI,许多模块定义了更多的 Functor
s(以及其他类型的类。)
尽管如此,请不要太认真地对待容器一词。 Functor
s是一个明确定义的概念,但您通常可以用这个模糊的比喻来推论它。
您的理解发生的最好的方法就是简单地阅读每个实例的定义,这应该让你直观地了解正在发生的事情。从那里开始真正正式理解你的概念只需要一小步。需要补充的是澄清我们的容器的真正含义,并且每个实例都满足一对简单的法律。
I'm trying to learn Haskell and I'm through all the basics. But now I'm stuck, trying to get my head around functors.
I've read that "A functor transforms one category into another category". What does this mean?
I know it's a lot to ask, but could anyone give me a plain english explanation of functors or maybe a simple use case?
A fuzzy explanation would be that a Functor
is some sort of container and an associated function fmap
that allows you to alter whatever is contained, given a function that transforms the contained.
For instance, lists are this kind of container, such that fmap (+1) [1,2,3,4]
yields [2,3,4,5]
.
Maybe
can also be made a functor, such that fmap toUpper (Just 'a')
yields Just 'A'
.
The general type of fmap
shows quite neatly what is going on:
fmap :: Functor f => (a -> b) -> f a -> f b
And the specialized versions may make it clearer. Here's the list version:
fmap :: (a -> b) -> [a] -> [b]
And the Maybe version:
fmap :: (a -> b) -> Maybe a -> Maybe b
You can gain information on the standard Functor
instances by querying GHCI with :i Functor
and many modules define more instances of Functor
s (and other type classes.)
Please don't take the word "container" too seriously, though. Functor
s are a well-defined concept, but you can often reason about it with this fuzzy analogy.
Your best bet in understanding what is going on is simply reading the definition of each of the instances, which should give you an intuition on what is going on. From there it's only a small step to really formalize your understanding of the concept. What needs to be added is a clarification of what our "container" really is, and that each instance much satisfy a pair of simple laws.
这篇关于函子在haskell中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!