Haskell:如何映射元组? [英] Haskell: how to map a tuple?

查看:265
本文介绍了Haskell:如何映射元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中,我可以轻松映射一个列表:

  map(\ x  - > 2 * x)[ 1,2] 

给我 [2,4] 。是否有任何mapTuple函数会这样工作?

  mapTuple(\ x  - > 2 * x)( 1,2)

结果为(2,4) code>。

解决方案

在Hoogle 并不完全符合(a - > b) - > (a,a) - > (b,b),这是你需要的类型,但是你可以很容易做到:

  mapTuple ::(a  - > b) - > (a,a) - > (b,b)
mapTuple f(a1,a2)=(f a1,f a2)



注意,你将不得不为3元组,4元组等定义一个新函数 - 尽管这样的需求可能是一个标志,你并没有像他们想要的那样使用元组:一般来说,元组的值不同的类型,所以想要将单个函数应用于所有值不是很常见。


In Haskell, I can easily map a list:

map (\x -> 2*x) [1,2]

gives me [2,4]. Is there any "mapTuple" function which would work like that?

mapTuple (\x -> 2*x) (1,2)

with the result being (2,4).

解决方案

Searching at Hoogle gives no exact matches for (a -> b) -> (a, a) -> (b, b), which is the type you require, but it is pretty easy to do yourself:

mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple f (a1, a2) = (f a1, f a2)

Note, you will have to define a new function for 3-tuples, 4-tuples etc - although such a need might be a sign, that you are not using tuples like they were intended: In general, tuples hold values of different types, so wanting to apply a single function to all values is not very common.

这篇关于Haskell:如何映射元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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