特别为元组保留不同的数据类型配对有如下好处:
[(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) = yWhy 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] 4But 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更多推荐
发布评论