我如何将列表转换为Haskell中的元组? [英] How do I convert a list to a tuple in Haskell?

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

问题描述

  [1,2,3,4,5]我怎样才能最好地将列表转换为Haskell中的元组? ,6]  - > (1,2,3,4,5,6)


解决方案

<一般来说,你不能。每个元组的大小都是不同的类型,而任何长度的列表都是单一类型。因此,没有什么好的方法来编写一个函数,它接受一个列表并返回一个长度相同的元组 - 它不会有一个定义明确的返回类型。



例如,你可以有如下功能:

  tuplify2 :: [a]  - > (a,a)
tuplify2 [x,y] =(x,y)

tuplify3 :: [a] - > (A,A,A)
tuplify3 [X,Y,Z] =(X,Y,Z)

...但不是两者兼而有之。



您可以使用各种类型编写通用版本元编程,但你很少想要。

请注意,同样的问题也适用于其他事情,例如为各种元组编写类实例 - 带一个看的Data.Tuple的源代码来自标准库!


How can I best convert a list to a tuple in Haskell:

[1,2,3,4,5,6] -> (1,2,3,4,5,6)

解决方案

In a general way, you can't. Each size of tuple is a distinct type, whereas lists of any length are a single type. Thus, there's no good way to write a function that takes a list and returns a tuple of the same length--it wouldn't have a well-defined return type.

For instance, you could have functions like:

tuplify2 :: [a] -> (a,a)
tuplify2 [x,y] = (x,y)

tuplify3 :: [a] -> (a,a,a)
tuplify3 [x,y,z] = (x,y,z)

...but not one that does the job of both.

You can write a generic version using various kinds of meta-programming, but you'd rarely want to.

Note that the same problem applies to other things, such as writing class instances for various tuples--take a look at the source code for Data.Tuple from the standard libraries!

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

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