Pergunta

I'm learning functional programming using the SML language. While reading my study notes, I came across a question, that asks which kind of a function (tuppled or curried) performs faster.

I've looked at the video here, where the instructor says that this is a matter of language implementation and states (at 5:25) that SML/NJ performs faster with tuppled functions, but doesn't state why that is.

I think my instructor once said, that it's because the curried function creates more closures, but I think I didn't hear right.

Can someone, please, elaborate on this?

Foi útil?

Solução

There's some more intermediate evaluation for curried functions. Let's say we wanted a function so sum three numbers. We consider the following two definitions:

fun sum (x,y,z) = x + y + z

Alternatively,

fun sum x y z = x + y + z

Consider the following rough evaluation trace on the first version:

:> sum(1,2,3)
   1 + 2 + 3 (substitution using pattern matching on the contents of the tuple)
   (1 + 2) + 3
   3 + 3
   6

On the other hand, with the curried version SML will construct some anonymous functions on the fly as it is evaluating the expression. This is because curried functions take advantage of the fact that anonymous functions can be returned as the results of other functions in order to capture the behavior of applying multiple arguments to a single function. Constructing the functions takes some constant amount of time.

:> sum 1 2 3
   ((sum 1) 2) 3
   (((fn x => (fn y => (fn z => x + y + z))) 1) 2) 3
   ((fn y => (fn z => 1 + y + z)) 2) 3
   (fn z => 1 + 2 + z) 3
   1 + 2 + 3
   (1 + 2) + 3
   3 + 3
   6

So there are some extra steps involved. It certainly should not cause performance issues in your program, however.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top