1
votes

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.

2
Wow, who voted to close this? "Off topic"? really? Perhaps we are only allowed to discuss imperative languages? - jalf
@jalf My curry pun was probably too unpalatable. Too much curry can be a bad thing. - Andrew

2 Answers

2
votes

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":

curry n = n * pow 1 n

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":

rice n = n * pow 0 n

And one more, "shrimp" -- but this time, the other pattern matches:

shrimp n = 1

The recursion has terminated here, so you have:

rice n = n * 1
curry n = n * (n * 1)

Now, use the second 2 in your original pow 2 2 with the new curry function:

curry 2 = 2 * (2 * 1)

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.

1
votes
2*pow(1)2 =2*(2*pow(0)2)2 

Here you expand pow 1 to 2 * pow 0 2 and leave the 2 after it be. This is wrong. pow 1 on its own would expand to (fn n => n * pow 0 2), only when applying it to the second argument as well it becomes 2 * pow 0 2. So the above should read:

2*pow(1)2 =2*(2*pow(0)2)

Now if we apply pow 0 2, we get 1 so the end result is:

2*pow(1)2 = 2*(2*pow(0)2) = 2*(2*1) = 4