haskell - Why is pattern matching preferred in function definitions? -


i reading "learnyouahaskell" tutorial learnyouahaskell. there reads:

pattern matching can used on tuples. if wanted make function takes 2 vectors in 2d space (that in form of pairs) , adds them together? add 2 vectors, add x components separately , y components separately. here's how have done if didn't know pattern matching:

addvectors :: (num a) => (a, a) -> (a, a) -> (a, a)   addvectors b = (fst + fst b, snd + snd b)   

well, works, there's better way it. let's modify function uses pattern matching.

addvectors :: (num a) => (a, a) -> (a, a) -> (a, a)   addvectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)   

there go! better. note catch-all pattern. type of addvectors (in both cases) addvectors :: (num a) => (a, a) -> (a, a) - > (a, a), guaranteed 2 pairs parameters.

my question is: why pattern matching preferred preferred way, if both definitions result in same signature?

i think in case pattern matching expresses more directly mean.

in function application case, 1 needs know fst , snd do, , deduce a , b tuples elements added.

addvectors b = (fst + fst b, snd + snd b) 

the fact have snd , fst functions decompose tuples distracting here.

in pattern matching case clear input (a tuple elements call x1 , y1 , tuple... etc) , how deconstructed. , clear happening, how elements added.

addvectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) 

this mathematical definition:

(x1, y1) + (x2, y2) := (x1 + x2, y1 + y2)

straight point, no distractions :-)

you literally write in haskell:

(x₁, y₁) `addvector` (x₂, y₂) = (x₁ + x₂, y₁ + y₂) 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -