Could someone please explain the concept of currying to me. I am primarily learning it because we are learning ML in my 'modern programming language' class for a functional language introduction.
In particular you can use this example:
-fun g a = fn b => a+b;
val g = fn: int -> int -> int
-g 2 3;
val it = 5 : int
I'm confused how these parameters are passed or how to even think about it in the first place.
Thank you for any help.
In this case, you make the currying explicit, so it should be easier to understand.
If we read the function definition, it says (paraphrased): "Create a function g
, which when given an a
returns fn b => a+b
."
That is, if we call g 2
, we get back the function fn b => 2+b
. As such, when we call g 2 3
, we actually call (g 2) 3
; that is we first get the function stated above back, and then use this function on the value 3
, yielding 5
.
Currying is simply the concept of making a function in several "stages", each taking an input and producing a new function. SML has syntactic sugar for this, making g
equivalent to the following:
fun g a b = a + b;