我正在阅读来自learnyouahaskell的"learnyouahaskell"教程。其中有这样一段内容:
我的问题是:如果两种定义的结果相同,为什么模式匹配更受青睐?Pattern matching can also be used on tuples. What if we wanted to make a function that takes two vectors in a 2D space (that are in the form of pairs) and adds them together? To add together two vectors, we add their
x
components separately and then theiry
components separately. Here's how we would have done it if we didn't know about pattern matching:
addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a) addVectors a b = (fst a + fst b, snd a + snd b)
Well, that works, but there's a better way to do it. Let's modify the function so that it uses pattern matching.
addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a) addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
There we go! Much better. Note that this is already a catch-all pattern. The type of
addVectors
(in both cases) isaddVectors :: (Num a) => (a, a) -> (a, a) - > (a, a)
, so we are guaranteed to get two pairs as parameters.
fst
和snd
就能理解函数... - Random Devfst
和snd
,我可以看出那可能会有可读性的优势。 - Zelphir KaltstahladdVectors (x₁,y₁) (x₂,y₂) = (x₁+x₂, y₁+y₂)
,那么模式匹配版本看起来会更好。 - leftaroundabout