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

编程入门 行业动态 更新时间:2024-10-27 16:24:06
为什么我们使用元组,如果我们可以使用二维列表?(Why do we use tuples, if we can use a two dimensional list?)

特别为元组保留不同的数据类型配对有如下好处:

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

与仅使用二维列表相反:

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

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

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

最满意答案

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

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

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

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

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

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

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

更多推荐

本文发布于:2023-07-16 12:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   列表   tuples   dimensional   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!