Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[1] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...