Search code examples
functional-programmingnaming-conventionsnomenclature

What is this functional "pattern" called?


I was fooling around with some functional programming when I came across the need for this function, however I don't know what this sort of thing is called in standard nomenclature. Anyone recognizes it?

function WhatAmIDoing(args...)
   return function()
       return args
   end
end

Edit: generalized the function, it takes a variable amount of arguments ( or perhaps an implicit list) and returns a function that when invoked returns all the args, something like a curry or pickle, but it doesn't seem to be either.


Solution

  • WhatAmIDoing is a higher-order function because it is a function that returns another function.

    The thing that it returns is a thunk — a closure created for delayed computation of the actual value. Usually thunks are created to lazily evaluate an expression (and possibly memoize it), but in other cases, a function is simply needed in place of a bare value, as in the case of "constantly 5", which in some languages returns a function that always returns 5.

    The latter might apply in the example given, because assuming the language evaluates in applicative-order (i.e. evaluates arguments before calling a function), the function serves no other purpose than to turn the values into a function that returns them.

    WhatAmIDoing is really an implementation of the "constantly" function I was describing. But in general, you don't have to return just args in the inner function. You could return "ackermann(args)", which could take a long time, as in...

    function WhatAmIDoing2(args...)
       return function()
           return ackermann(args)
       end
    end
    

    But WhatAmIDoing2 would return immediately because evaluation of the ackermann function would be suspended in a closure. (Yes, even in a call-by-value language.)