  lua-l archive

• Subject: Re: Functional programming
• From: Roberto Ierusalimschy <roberto@...>
• Date: Wed, 21 Jan 2009 09:55:17 -0200

```>
> Hi, I just tried
>
> print((function (f,x) return f(f,x) end)(function (f,x) if x>1 then return f(f,x-1)*x else return 1 end end,5))
>
> 120
>
>
> And was impressed.  This is a rather direct rendition of the functional
> teaser "how do I use a recursive function call without permanent
> binding" which is solved in Scheme by saying
>
> ((lambda(f x) (f f x))(lambda (f x) (if (> x 1) (* (f f (- x 1)) x) 1)) 5)
>
> 120

You may also try this more "dogmatic" solution (using a
fixed-point operator) :-)

print(
(function (le)
return (function (f)
return f(f)
end)(function (f)
return le(function (x)
return f(f)(x)
end)
end)
end)(function (f)
return function (n)
if n == 0 then return 1
else return n*f(n-1) end
end
end)(5))

(The first function is much more convoluted, but it allows the second
to be quite close to the recursive factorial.)

-- Roberto

```