Monday, 15 February 2010

Funny Haskell Behaviour: min function on three numbers, including a negative -



Funny Haskell Behaviour: min function on three numbers, including a negative -

i've been playing around haskell functions in ghci.

i'm getting funny behavious , i'm wondering why it's happening.

i realized function min supposed used 2 values. however, when utilize 3 values, in case

1 2 -5

i'm getting

-4

as result.

why that?

because expression:

min 1 2 -5

parses if parenthesized this:

(min 1 2) -5

which same this:

1 -5

which same this:

1 - 5

which of course of study -4.

haskell function application highest precedence operation, not greedy. in fact, seemingly simple look min 1 2, function min first called single value, 1. homecoming value of function new, anonymous function, homecoming smaller of 1 , single argument. anonymous function called argument of 2, , of course of study returns 1.

to find minimum of 3 values, need chain 2 calls min (which actually, per logic described above, yields 4 separate function calls):

min (min 1 2) (-5)

the parentheses around -5 ensure - interpreted prefix negation instead of infix subtraction. in general, if have literal negative number in haskell, parentheses necessary. in cases can leave them off, then, using them makes things clearer reader of code.

more generally, allow haskell chaining applying fold list, can contain many numbers like:

foldl1 min [1, 2, -5]

the phone call foldl1 fun list means "take first 2 items of list , phone call fun on them. take result of phone call , next item of list, , phone call fun on 2 values. take result of phone call , next item of list..." , on, continuing until there's no more list, @ point value of lastly phone call fun returned original caller.

there several functions have predefined pre-folded equivalents, however, , min 1 of them; list version called minimum:

minimum [1, 2, -5]

that behaves foldl1 solution above; in particular, both throw error if handed empty list.

thanks johnl reminding me of existence of minimum.

haskell

No comments:

Post a Comment