1

I'm learning some haskell since this weekend, I found this language interesting, but also some syntaxs make me confused.

Like, zip is a function that take 2 list as parameters and then return a list of pairs. if I invoke zip [1,2,3] [3,2,1] in ghci I got [(1,3),(2,2),(3,1)]. But if I say (zip [1,2,3]) [3,2,1] it returns the same result.

When I looked into the definition of the zip function using :i zip, I got zip :: [a] -> [b] -> [(a, b)] -- Defined in ‘GHC.List’, from this it seems that zip is a function apply the first parmeter, return a function and then apply to the second parameter.

Another example is elem, elem 1 [1,2,3], (elem 1) [1,2,3] and (1 `elem`) [1,2,3] return the same result.

So my question is if a function receive multiple parameters, how this function evaluate, process each parameter in order or just process all parameters in one time.

Joey
  • 1,233
  • 3
  • 11
  • 18
  • You can read `someFunc :: a -> b -> c` as `someFunc :: a -> (b -> c)`, which might help you to answer the question yourself. – Zeta Oct 26 '14 at 10:15
  • 2
    see also: http://stackoverflow.com/questions/1352855/in-functional-programming-what-is-currying – kieran Oct 26 '14 at 10:19

1 Answers1

5

(->) is right associative¹, and that means that something like this:

zip :: [a] -> [b] -> [(a, b)]

is understood by GHC as:

zip :: [a] -> ([b] -> [(a, b)])

The latter helps you to see that when you call zip with one argument, you get a function back:

λ> :t zip [1, 2, 3]
zip [1, 2, 3] :: Num a => [b] -> [(a, b)]

This is called currying, or partial application.


Notes

  1. Right associative means that the operator groups to the right. A common example is the power operator ^. In a power tower, this is evident: λ> 2^2^2^2 65536 λ> 2^(2^(2^2)) 65536

    If the power operator were left-associative, we would have: λ> ((2^2)^2)^2 256

rubik
  • 8,814
  • 9
  • 58
  • 88
  • Thank you so much, I thought I found something big, but it turns out to be a common idea in haskell.I'll continue dive into it. – Joey Oct 26 '14 at 12:42
  • 1
    I'm glad it was helpful. Yes, currying is common and super-useful! You might consider accepting the answer if it answered you questions. – rubik Oct 26 '14 at 17:43
  • sorry man, I just realized I should accept a satisfied answer. – Joey Oct 30 '14 at 16:48