为什么 2 元组 Functor 实例只将函数应用于第二个元素? [英] Why does the 2-tuple Functor instance only apply the function to the second element?

查看:29
本文介绍了为什么 2 元组 Functor 实例只将函数应用于第二个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import Control.Applicative

main = print $ fmap (*2) (1,2)

产生(1,4).我希望它产生 (2,4) 但该函数仅应用于元组的第二个元素.

produces (1,4). I would expect it it to produce (2,4) but instead the function is applied only to the second element of the tuple.

更新我几乎马上就明白了这一点.我会在一分钟内发布我自己的答案..

Update I've basically figured this out almost straight away. I'll post my own answer in a minute..

推荐答案

Functor 实例实际上来自 GHC.Base 模块.

The Functor instance is actually from the GHC.Base module which is imported by Control.Applicative.

尝试编写我想要的实例,我可以看到它不会工作,给定元组的定义;实例只需要一个类型参数,而 2 元组有两个.

Trying to write the instance I want, I can see that it won't work, given the definition of tuples; the instance requires just one type parameter, while the 2-tuple has two.

一个有效的 Functor 实例至少必须在每个元素具有相同类型的元组 (a,a) 上,但你不能做任何偷偷摸摸的事情,比如定义实例:

A valid Functor instance would at least have to be on tuples, (a,a) that have the same type for each element, but you cannot do anything sneaky, like define the instance on:

 type T2 a = (a,a)

因为实例类型不允许是同义词.

because instance types aren't permitted to be synonyms.

上述受限的二元组同义词在逻辑上与类型相同:

The above restricted 2-tuple synonym is logically the same as the type:

data T2 a = T2 a a

哪个可以有一个 Functor 实例:

which can have a Functor instance:

instance Functor T2 where
    fmap f (T2 x y) = T2 (f x) (f y)

正如 Gabriel 在评论中所说,这对于分支结构或并发很有用.

As Gabriel remarked in the comments, this can be useful for branching structures or concurrency.

这篇关于为什么 2 元组 Functor 实例只将函数应用于第二个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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