I have a midterm coming up next week and I was just going over the sml notes provided in class. I came across a currying example and I was not sure exactly how it worked.
It is a simple function which computes the power of a number. Here is the function definition:
fun pow 0 n = 1 | pow k n = n*pow(k-1)n
I’m not sure how this function works when we pass it the following arguments:
val x = pow 2 2
This is the way I see it:
=2*pow(1)2
=2*(2*pow(0)2)2
=2*(2*(1)2)2)
The result we should be getting is four but I don’t see how we get this result from the steps I have carried out above.
Help Please. Thank-You.
Ah, Standard ML of New Jersey, how I miss thee…
Anyway, let me go through this step by step. Remember that currying, unlike the dinner in front of me (which incidentally is a curry dish), is basically a way of dealing with only one argument at a time to return a new function. With that in mind, apply the first 2 to the given function. Since only one pattern matches, you now have a new function — let’s call it “curry”:
Note that you now have an “inner” version of the pow function to address. Doing so, again, one pattern matches. Let’s call this inner curried function “rice”:
And one more, “shrimp” — but this time, the other pattern matches:
The recursion has terminated here, so you have:
Now, use the second 2 in your original
pow 2 2with the newcurryfunction:which of course is 4.
I highly doubt SML names the curried functions in this way, but I hope this does help to understand the concept. I take no responsibility if it also makes you hungry.