如果我们可以使用二维列表,我们为什么要使用元组? [英] Why do we use tuples, if we can use a two dimensional list?

查看:22
本文介绍了如果我们可以使用二维列表,我们为什么要使用元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为这样的元组专门保留不同的数据类型配对是否有好处:

Is there a benefit to specifically reserving varied data-type pairings for tuples like such:

[(23, "Jordan"), (8, "Bryant")]

与仅使用二维列表相反:

As opposed to just using a two-dimensional list:

[[23, "Jordan"], [8, "Bryant"]]

我知道第二段代码在 Haskell 中不起作用

I know the second piece of code will not work in Haskell

推荐答案

如果我们可以使用二维列表,为什么还要使用元组?

Why do we use tuples, if we can use a two dimensional list?

因为列表和元组在概念上是不同的东西,而类型系统为我们提供了一种有用的方式来说明和识别代码中的差异.对于许多可能的示例之一,可以定义...

Because lists and tuples are conceptually different things, and the type system gives us an useful way to state and recognise the difference in code. For one of many possible examples, one might define...

type ListyPair a = [a]

...然后...

listyFst :: ListyPair a -> a
listyFst [x, _] = x

listySnd :: ListyPair a -> a
listySnd [_, y] = y

...这样:

GHCi> listyFst [3,4]
3
GHCi> listySnd [3,4]
4

但是如果列表的对"只有一个元素,或者没有元素,会发生什么?我们将不得不抛出一个运行时错误 (yuck),或者使 listyFstlistySnd 产生 Maybe a 以便我们可以干净利落地处理故障.如果对"有两个以上的元素怎么办?我们应该默默地丢弃它们,还是在这种情况下让函数也失败更好?

But what happens if the listy "pair" has just one element, or none? We would have to throw a runtime error (yuck), or make listyFst and listySnd result in a Maybe a so that we can handle failure cleanly. What if the "pair" has more than two elements? Should we just discard them silently, or would it be better to make the functions fail in this case as well?

从强类型系统用户的角度来看,当我们用 ListyPair 替换实际的配对时,我们丢弃了有用的信息.知道实际上只有两个元素可以避免上述所有复杂情况.

From the perspective of a strong type system user, when we replace an actual pair with ListyPair we are throwing away useful information. Knowing that there are really just two elements allows us to avoid all of the complications above.

realFst :: (a, b) -> a
realFst (x, _) = x

realSnd :: (a, b) -> b
realSnd (_, y) = y 

这篇关于如果我们可以使用二维列表,我们为什么要使用元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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