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

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

问题描述

在 Haskell 中如何最好地将列表转换为元组:

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.

注意,同样的问题适用于其他事情,比如为各种元组编写类实例——看看标准库中 Data.Tuple 的源代码

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天全站免登陆