Haskell:如何映射元组? [英] Haskell: how to map a tuple?
问题描述
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屋!