Local functions

Rémi Forax forax at univ-mlv.fr
Wed Feb 10 07:53:55 PST 2010


Le 10/02/2010 16:36, Mark Mahieu a écrit :
> On 10 Feb 2010, at 15:05, Rémi Forax wrote:
>
>    
>> Le 10/02/2010 14:52, Mark Mahieu a écrit :
>>      
>>> On 10 Feb 2010, at 13:09, Rémi Forax wrote:
>>>
>>>        
>>>> There is a simple solution, if you want to write recursive function,
>>>> create a static method
>>>> and reference it as a lambda:
>>>>
>>>> class A {
>>>>    static int factorial(int x) {
>>>>      return (x<= 1) ? 1 : x*factorial.(x-1);
>>>>    }
>>>>
>>>>       public static void main(String[] args) {
>>>>           #int(int) lambda = A#factorial;
>>>>       }
>>>> }
>>>>
>>>>
>>>>          
>>> I don't think that approach is quite so simple if your recursive function needs to use locals in the method which 'creates' it (eg. it references 'args' in 'main', in your example).
>>>
>>> Regards,
>>>
>>> Mark
>>>
>>>        
>> In that case, the anonymous class syntax is your friend.
>>
>> Or if lambdas are translated to method handles, you can write:
>>
>> class A {
>>   static int foo(String[] args, int x) {
>>     return (x<= 1) ? args.length : x*foo.(x-1);
>>   }
>>
>>   public static void main(String[] args) {
>>     #int(int) lambda = A#foo.bindTo(args);
>>   }
>> }
>>
>> cheers,
>> Rémi
>>
>>
>>      
>
> You *can* do it without method references, method handles, or partial application too.  But you mentioned a simple solution, which to me suggests an ideal of being able to 'create' the lambda in approximately the same manner regardless of whether it's recursive or references local variables.
>
> Anyway, we could do with finding some additional recursive examples - factorial is getting worn out ;-)  One which I frequently write involves walking a tree and doing something with (eg. collecting) all nodes which match some criteria.  I'm slightly surprised it didn't crop up in the recent codebase stats I submitted though... I might look into why that is.
>
>
> Cheers,
>
> Mark
>    

Mark,
if you walk a tree, the method that walk is recursive, not the lambda 
taken as argument.

simple solution => if its a complex lambda, write it as a method or as 
an inner class
then construct a lambda on it.

class A {
  static int foo(String[] args, int x) {
    return (x<= 1) ? args.length : x*foo.(x-1);
  }

  public static void main(final String[] args) {
    #int(int) lambda = #(int x) (foo(args, x));
  }
}

Rémi





More information about the lambda-dev mailing list