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

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

问题描述

  import Control.Applicative 

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

产生(1,4)。我期望它生成(2,4),但是该函数只应用于元组的第二个元素。



更新我基本上已经基本认识到了这一点。我会在一分钟后发布我自己的答案。

Functor 实例实际上来自 GHC.Base 模块,它由 Control.Applicative 导入。

试图编写我想要的实例,我可以看到它不起作用,给定了元组的定义;实例只需要一个类型参数,而2元组有两个。



一个有效的 Functor 实例将会在至少必须在元组上,(a,a)对每个元素都有相同的类型,但不能做任何鬼鬼祟祟的事情,比如定义实例:

  type T2 a =(a,a)

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



上面受限制的2元组同义词在逻辑上与类型相同:

  data T2 a = T2 aa 

哪些可以有一个Functor实例:

 实例Functor T2其中
fmap f(T2 xy)= T2(fx)(fy)

在评论中指出,这可以用于分支结构或并发。


import Control.Applicative

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

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..

解决方案

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

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.

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

which can have a Functor instance:

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

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

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

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