函子如何在haskell中工作? [英] How do functors work in haskell?

查看:17
本文介绍了函子如何在haskell中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Haskell,并且我已经掌握了所有基础知识.但现在我被困住了,试图让我的头脑围绕函子.

我读过函子将一个类别转换为另一个类别".这是什么意思?

我知道有很多问题要问,但谁能给我一个简单的英文函子解释或者一个简单用例?

解决方案

一个模糊的解释是 Functor 是某种容器和一个关联的函数 fmap允许你改变所包含的任何东西,给定一个转换所包含的函数.

例如,列表就是这种容器,这样 fmap (+1) [1,2,3,4] 产生 [2,3,4,5].

Maybe 也可以是一个函子,这样 fmap toUpper (Just 'a') 产生 Just 'A'.>

fmap 的一般类型非常清楚地显示了正在发生的事情:

fmap :: Functor f =>(a -> b) ->f a ->fb

专业版本可能会更清楚.这是列表版本:

fmap :: (a -> b) ->[a] ->[乙]

还有Maybe版本:

fmap :: (a -> b) ->也许一个 ->也许 b

您可以通过使用 :i Functor 查询 GHCI 来获取有关标准 Functor 实例的信息,并且许多模块定义了更多 Functor 实例(和其他类型类.)

不过,请不要太认真对待容器"这个词.Functor 是一个定义明确的概念,但您通常可以用这个模糊的类比来推理它.

理解正在发生的事情的最好办法就是阅读每个实例的定义,这应该会让您对正在发生的事情有一个直观的了解.从那里开始,真正使您对概念的理解正式化只是一小步.需要补充的是澄清我们的容器"究竟是什么,每个实例都非常满足一对简单的规律.

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 Functors (and other type classes.)

Please don't take the word "container" too seriously, though. Functors 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中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆