Lambda recursive ...

Remi Forax forax at univ-mlv.fr
Sat Oct 20 14:39:05 PDT 2012


On 10/20/2012 09:53 PM, Olexandr Demura wrote:
> Or choose to be even more functional (-: replace recursion with
> fixed-point combinator.
>
> interface PreIntToInt {
>    int apply(PreIntToInt next, int i);
>    default IntToInt fix() { return (i) -> { return this.apply(this, i); }
> }
> PreIntToInt preFactorial = (self, i) -> { return i == 0 ? 1 : i *
> self.apply(i - 1); };
> IntToInt factorial = preFactorial.fix();
>
> Have a nice weekend.

or using the mutable array trick as in lisp,

IntToInt[] applier = { null };
IntToInt factorial = i -> (i == 0)? 1: i* applier[0].apply(i - 1);
applier[0] = factorial;

Rémi

>
> 2012/10/20 Remi Forax <forax at univ-mlv.fr>:
>> On 10/20/2012 06:29 PM, Maurice Naftalin wrote:
>>> The FAQ page with this factorial example
>>> (http://lambdafaq.org/can-lambda-expressions-be-used-to-define-recursive-functions/)
>>> actually did make that point. It makes it more emphatically now.
>> You can also define the recursive function and use the method referene
>> syntax:
>> class A {
>>     static int fibo(int n) {
>>       return (n < 2)? 1: fibo(n -1) + fibo(n - 2);
>>     }
>>     ...
>>     Mapper<Integer, Integer> mapper = A#fibo;
>> }
>>
>> Rémi
>>> Maurice
>>>
>>> On 19/10/2012 14:18, Aleksey Shipilev wrote:
>>>> On 10/19/2012 05:09 PM, Boaz Nahum wrote:
>>>>
>>>>> interface FactInt { int invoke(int i); }
>>>>>
>>>>>     FactInt factorial = i ->
>>>>>                    { return i == 0 ? 1 : i * factorial.invoke(i - 1); };
>>>>>
>>>>> But the compile (b61) says:
>>>>> error: variable factorial might not have been initialized
>>>>>
>>>>> How can I write recursive expression like this ?
>>>>>
>>>> Lambda can not capture the uninitialized local variable; the trick is to
>>>> use fields, in which case lambda will capture "this" or the reference to
>>>> static field [1].
>>>>
>>>> -Aleksey.
>>>>
>>>> [1]
>>>> https://github.com/shipilev/jdk8-lambda-samples/blob/master/src/test/java/net/openjdk/lambda/FibonacciTest.java



More information about the lambda-dev mailing list