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

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

问题描述

  [(23,Jordan)是否有利于特别为元组保留不同的数据类型配对: ),(8,Bryant)] 

与仅使用二维列表:

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

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

解决方案


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


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

  type ListyPair a = [a] 

...然后...

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

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

...这样: p>

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

但是如果列表中的pair有只有一个元素,或没有?我们必须抛出一个运行时错误(yuck),或者让 listyFst listySnd 产生一个也许是一个,这样我们可以干净地处理失败。如果对有两个以上的元素会怎么样?我们应该静静地抛弃它们,还是在这种情况下让函数失败会更好?

从强类型系统用户的角度来看,当我们用 ListyPair 替换一个实际的对,我们扔掉有用的信息。知道实际上只有两个元素可以避免以上所有问题。

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

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


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"]]

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]

... and then...

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

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

... so that:

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

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?

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