Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java

Functional Programming First class functions, lambdas and closures

Radu Nicolescu Department of Computer Science University of Auckland

23 July 2018

1 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java

1 Programming paradigms

2 Pure FP

3 Recursion

4 # Delegates

5 Lambda expressions

6 Closures

7 More Lambdas

8 Quiz – Simple scenarios

9 Lambdas in Javascript

10 Lambdas in Java

2 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Programming paradigms

• Object-oriented: develop complex objects starting with simple objects (using inheritance, aggregation, delegation, ...)

• Functional: develop complex functions starting with simple functions (using function composition, Kleisli, ...)

• Object-oriented or functional?

• Object-oriented and functional! More dimensions, more tools!

• Most modern languages evolve towards a multi-paradigm style

• Object-first: C#, Java, C++, ...

• Functional-first: F#, Javascript (Lisp in Java syntax), ...

• Object-functional: Scala, ...

4 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Side-bar: functions and methods

• In classical OOP, functions only appear as methods:

• Static/class methods • Instance methods (cf. this pointer)

• Other languages, including FP, have standalone, even top-level, functions

• Problem: how to represent anonymous inline functions (such as lambdas) in OOP?

• Solution: embed these in the current object, if possible, or inside hidden automatically constructed objects – more at closures

5 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Basic ingredients of FP

• first-class and higher order functions (aka, functionals)

• informally, you can work with functions as with any other objects – and compose them! • you can have functions that take functions as parameters and return functions (functions which may be dynamically composed)

or partial application of functions

• memoization (or caching) of function results

• no side effects and immutable values (next slide)

6 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Pure FP

• Function results should only depend on parameter values

• No side effects: Functions should not change the global state or any persistent state (unlike object methods which change the object’s state)

• Immutable values: Ideally, functions should not change any value at all! – This is possible if we use recursion instead of classical loops...

• As one of the advantages, programs will be easier to prove correct, to optimize or to parallelize

8 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Pure FP

• For example, if f and g don’t change any global variable nor any of their parameters (i.e., a, b, c, d), the following two statements can run in parallel, on a dual-core machine:

1 x=f(a,b); — function f could be evaluated on core #1 2 3 y=g(c,d); — function g could be evaluated on core #2

• However, many practical languages, including C# (and F#), do accept side effects, although some of them will try to explicit or localize these (e.g., via so-called monads)

9 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in C#

• Class fields and properties : vast topic, but not much of our concern here...

• var or normal declarations are mutable 1 var x=10; x=x+1; 2 i n t x=10; x=x+1;

• const defines compile-time immutable values 1 const x = 1 0 ;

• readonly defines run-time immutable fields – maybe differently initialised in constructors, but then is frozen 1 readonly int x ;

10 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in C#

• Shallow vs deep immutability

• Shallow immutable complex objects such as arrays 1 c l a s s C { 2 public static readonly int []A 3 = new i n t [] { 10 , 20 , 30 , } ; 4 } 5 6 void Main ( ) { 7 var B = new i n t [] { 100, 200, 300, } ; 8 // C .A = B; // NOT allowed 9 C .A [ 1 ] = 200; // allowed! 10 C .A. Dump ( ) ; 11 }

• Conclusions: flexible but porous

11 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in F#

• Class fields and properties : vast topic, but not much of our concern here...

• let declarations are immutable – not “variables” but values 1 l e t x = 10

• x = x + 1 is legal (!) but does NOT mean what one would think: it is a boolean equality test that returns false ! • Mutable variables must be explicitly declared so 1 l e t mutable x = 10 2 x <− x + 1

• Increased awareness: the assignment to a mutable variable uses a distinct op sign <−

12 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in F#

• Still shallow immutable arrays (but not other objects) 1 l e t A = [ | 1 0 ; 2 0 ; 3 0 ; | ] // A itself is immutable 2 A . [ 1 ] <− 200 // allowed! 3 A. Dump ( )

• Why this exception for arrays? Because of the HUGE body of scientific algorithms, which have been developed and optimised for FORTRAN mutable arrays

• F# encourages a more pure style, and promotes increased awareness of mutability – but still allows one the choice to use other styles

13 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in JS

• var declarations are mutable with global scope or function “global” scope 1 var x = 10

• let declarations are mutable with block local scope 1 i f ( b ) { 2 l e t x = 10 3 x = x + 1 4 }

• const declarations are immutable with block local scope 1 i f ( b ) { 2 const x = 10 3 // x = x + 1 // not allowed 4 }

• More in part (M) 14 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Imperative factorial

• F# 1 l e t f a c t n : i n t = 2 l e t mutable m = n 3 l e t mutable f = 1 4 while (m >= 1) do 5 f <− f ∗ m 6 m <− m − 1 7 f 8 9 p r i n t f n ”Imperative: %A” (fact 5)

16 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Naive recursive factorial

• F# 1 l e t rec f a c t ’ n = 2 i f n <= 0 then 1 3 e l s e ( f a c t ’ ( n−1)) ∗ n 4 5 p r i n t f n ”Naive Recursive: %A” (fact ’ 5)

• Performance issues, stack overflow

17 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Tail recursive factorial

• F# 1 l e t f a c t ’ ’ n = 2 l e t rec f a c t tailrec n acc = 3 i f ( n <= 0) then acc 4 e l s e f a c t t a i l r e c ( n−1) ( n∗ acc ) 5 f a c t t a i l r e c n 1 6 7 p r i n t f n ”Tail Recursive: %A” (fact ’’ 5)

• F# : TCO = Tail Call Optimisation • NO performance issues, NO stack overflow

18 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Tail recursive factorial – reverse engineered

• C# : recursion ⇒ while loop! 1 s t a t i c i n t f a c t t a i l r e c ( i n t n , i n t acc ) { 2 while ( n > 0) { 3 acc = n ∗ acc ; 4 n = n − 1 ; 5 } 6 return acc ; 7 } 8 public static int f a c t ( i n t n ) { 9 return f a c t tailrec(n, 1); 10 }

• NO performance issues, NO stack overflow

19 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java C# Delegates in a nutshell

• Consider this scenario 1 c l a s s C { 2 p u b l i c i n t F( i n t x ) { return x +1; } 3 p u b l i c i n t G( i n t y ) { return y+y ; } 4 public static int H( i n t z ) { return z ∗ z ; } 5 }

• What do these three methods have in common?

• Their signature: int→int

• Usage (assuming using static System.Console) 1 WriteLine ($”{ c1 . F (3)}{ c2 .G(3)}{C .H(3)} ”); 2 // 4 6 9

21 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java C# Delegates in a nutshell

• Same scenario 1 c l a s s C { 2 p u b l i c i n t F( i n t x ) { return x +1; } 3 p u b l i c i n t G( i n t y ) { return y+y ; } 4 public static int H( i n t z ) { return z ∗ z ; } 5 }

• More flexible usage using typed function pointers! 1 Func f = c1 . F ; 2 Func g = c2 .G; 3 Func h = C .H; 4 WriteLine ($”{ f (3)}{g (3)}{h (3)} ”); 5 // 4 6 9

• The same pointer, e.g. f, could point in turn to all these methods! 22 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java C# Delegates

• A delegate is a .NET type-safe pointer to a function, i.e. to a class or instance method • To call an instance method: obj.F (...)

• To call a static method: Class .H (...)

• Technically, a delegate is an object with two properties

• Method: a pointer to the instance or class method (F,H) • Target – for instance methods: pointer to actual object (obj) • instance method calls depend on the actual target object

• Target – for static methods: null (usually) • static methods can be fully resolved by the compiler (so the actual class is not needed at runtime)

23 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Predefined delegate types in C# – Function types in F#

1 Func (n ∈ {0, 1, 2,..., 16}) // C# 2 3 f : T1∗T2 ∗ ... ∗Tm − > unit // F#

• functions taking T1,T2 ,..., Tn and returning TResult, i.e. • f : T 1 × T 2 × ... Tn → TResult – maths notation.

1 Action (m ∈ {0, 1, 2,..., 16}) // C# 2 3 f : T1∗T2 ∗ ... ∗Tm − > unit // F#

• “functions” taking T1,T2 ,..., Tm and returning void, i.e. • f : T 1 × T 2 × ... Tm → void – maths-like notation. • unit is the F# “void” type, with one single value ()

24 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Delegates – visualisation

To visualise the target of a delegate to a method, consider the following scenario (Linqpad) • a class C – nested in the outer Linqpad class, UserQuery

1 c l a s s C { 2 p u b l i c i n t X { get ; ; } 3 p u b l i c i n t F( i n t v ) { return v + X; } 4 public static int G( i n t v ) { return v + 100; } 5 }

• two instances of C, o1 and o2 1 var o1 = new C { X = 10 , } ; 2 var o2 = new C { X = 20 , } ; 3 4 WriteLine($”{o1 . F ( 1 ) } , {o2 . F ( 1 ) } , {C .G(1)} ”); 5 // 11 , 21 , 101

25 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Delegates – visualisation

• three pointers to functions (delegates)

1 Func f 1 = o1 . F ; 2 Func f 2 = o2 . F ; 3 Func g = C .G; 4 WriteLine($”{ f 1 ( 1 ) } , { f 2 ( 1 ) } , { g (1)} ” ) ; //11 ,21 ,101

• visualise their target objects

1 f1.Target.Dump(”f1”); 2 3 f2.Target.Dump(”f2”); 4 5 g.Target.Dump(”g”);

26 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java λ-expressions

• Ideas originate from an early theoretical model: λ-calculus (introduced by Alonzo Church, 1930s).

• λ-expression example (lambda in red):

1 l e t f :=( λs.suv)

• Let f is “syntactic sugar”, our external denotation to an anonymous (unnamed) λ-expression of one parameter,s.

• Sample invocation: (f x) = ((λs.suv) x) = xuv .

• Pure λ-expressions have only names for the parameters – although these could also be eliminated and replaced by numbers which indicate the position (De Brujin).

28 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java λ-expressions

• Pure λ-calculus has NO variables, NO loops/recursion (but these can simulated by way of Y combinators). • Still, λ-calculus is an universal model of computation equivalent to Turing machines! • Historical note: why “lambdas”? “Raging” debate... • Church’s manuscript used hats to designate parameters 1 (s ˆ. t )

• Typographer’s solution 1 (ˆ s . t )

• Adjustment (according to the original cursive script) 1 (λs . t )

29 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Lambdas as anonymous inline functions

• C# examples:

1 Func f = (string s) => s.Length ; 2 3 Func f = s=> s.Length ;

• f is a delegate (pointer) to an anonymous (unnamed) function of one string parameter,s, return its length

• sample invocation: f(”abc”) • F# examples:

1 l e t f = fun (s: string) − > s.Length ; 2 3 l e t f ’ : s t r i n g −> i n t = fun s − > s.Length

30 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Lambdas — Other examples

• C#, F# 1 Func g = () => 2 ; // C# 2 l e t g = fun () − > 2;//F# unit −> i n t

• g is a function without parameters, returning int constant 2 • unit is the F# “void” type, with one single value () • sample invocation: g() • C#, F# 1 Func h = (x, y) => x + y ; // C# 2 l e t h = fun (x, y) − > x + y;//F#( i n t ∗ i n t ) −> i n t

• h is a function of an int pair, x, y, returning their sum • sample invocation: h(10, 20)

31 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Lambdas have two faces!

Janus, from Wikipedia

1 Anonymous inline functions

2 Expression trees

32 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Lambdas as Expression trees!

• The other face of lambdas (≈ compilation arrested at intermediate tree structures) • Consider the following scenario, where the same lambda can be assigned to different left-handside type!

1 Func g = x => x + 2 ; 2 3 Expression > t = x => x + 2 ;

• g is a pointer to a .NET function int → int • t is a tree structure, called Expression, representing such a function • This tree structure is similar to the intermediate tree structure used by the compiler, when compiling g

33 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Lambdas as Expression Trees!

• t can be easily visualised via Linqpad’s Dump() operator

1 t.Dump(...);

Lambda Func

parameters body

Parameter Expression x int Add int

left right

Parameter Constant x int 2 int

34 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Sidebar: Typical translation/compilation steps (simplified)

• Source code expression: (x + y) ∗ z • Abstract syntax tree (AST) *

+ z

x y

• Target code • Reverse Polish (postorder): xy+z∗ or stack machine: 1 PUSH x ; PUSH y ; ADD; PUSH z ; MULT; POP

• Bytecode or machine code 1 LOAD x ; ADD y ; MULT z ;

• Almost any other target: SQL, ODATA/REST, ... 35 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Lambdas as Expression Trees!

• Consider

1 Expression > t = x => x + 2 ;

• t can be dynamically compiled (at runtime) into a .NET function int → int and subsequently executed

1 g = t.Compile(); 2 var b = g ( 1 0 0 ) ;

• According to the context, providers can compile t to many different other formats, e.g. SQL queries, ODATA queries, ... (more later)

• Hot trend, generalised by the compiler as service

36 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java A lambda with a free variable

1 Func f = y => y + z ;

• f is a function of one parameter, y, returning the value y + z

• where z is a free variable (external value, expected from the lexical context)

• the closure of f ≡ f plus z

Closure The closure of a function is the function itself plus context references for all its free variables.

38 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java The closure object

1 Func f = ( i n t y ) => y +z;

In C#, closures are implemented as hidden, compiler-generated closure objects, where

• anonymous functions, e.g. (int y) => y + z , are methods • free variables, e.g.z, are transformed into fields

1 c l a s s Q { // Q and f are hidden compiler-generated names 2 p u b l i c i n t z; 3 p u b l i c i n t f ( i n t y ) { return y +z; } 4 }

Other implementations exist, but this one is “natural” in OO languages (C#, Java) and clarifies “tricky” scenarios

39 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java The closure object

• Closures in FP often serve a similar purpose as objects in OO. Essentially, the following two objects are equivalent: • The hidden closure object created by the following FP snippet:

1 var x = 1 0 ; 2 var y = 2 0 ; 3 Func f = ( ) => x + y ; 4 Func g = ( ) => x ∗ x ;

• An instance of the following OO class:

1 c l a s s C { 2 p u b l i c i n t x = 1 0 ; 3 p u b l i c i n t y = 2 0 ; 4 p u b l i c i n t f ( ) { return x + y ; } 5 p u b l i c i n t g ( ) { return x ∗ x ; } 6 }

40 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Targets and Closures – visualisation

To visualise the target of a delegate to a lambda, consider the following scenario (Linqpad)

1 Func f = v => v + 1 ; 2 i n t x = 1 0 ; 3 Func g = v => v + x ; // closure! 4 WriteLine($”{ f ( 1 0 ) } , {g (10)} ” ) ; // 11 , 20 5 6 f.Target.Dump(”f”); 7 g.Target.Dump(”g”);

<>c DisplayClass5 is the in- ternal name of the automati- cally generated closure class

41 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Dynamic access to closure details – C#

• Consider the following function Quiz. Quiz returns a closure, which includes the field w 1 Func Quiz ( i n t z ) { 2 i n t w = z + 1 ; 3 return y => w + y ; 4 }

• Consider a scenario where we dynamically update the field w of a closure generated by Quiz 1 Func k2 = Quiz(200); // .w= 201 2 i n t i 2 = k2 ( 1 0 ) ; // 211 3 4 dynamic t = k2.Target; // duck typing as in JS! 5 t .w += 1 ; 6 i n t i 3 = k2 ( 1 0 ) ; // 212

42 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Dynamic access to closure details – C#

43 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java A lambda taking another lambda

1 Func, int , int > h = (f , x) => f (x) ;

• h is a function of two parameters: a function Func f and an int x,

• which returns the result of f on x, i.e. f (x)

• sample invocation: h(n => n+n, 10)

• sample invocation: h(n => n∗n, 10)

45 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java A lambda returning another lambda

1 Func> h = x => (y => x + y) ;

• h is a function of one int parameter, x • which returns an anonymous Func function, of one int parameter, y • sample invocation: var r = h(10)(20) • h is similar, but not identical, to the function h of two variables from the preceding slide • another invocation: 1 Func k = h(10) ; var r = k ( 3 0 ) ; 2 which is equivalent to 3 Func k = (y => 10 + y) ; var r = k ( 3 0 ) ;

46 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Expression lambdas and statement lambdas

Two of lambdas (so far we’ve seen only the first type):

• expression lambdas param => expr or (params) => expr

• statement lambdas param => {stmt} or (params) => {stmt}

• Any expression lambda can be converted to a statement lambda, e.g. param => expr → param => {return expr; }

• Currently, only expression lambdas can be viewed as syntax trees (assigned to Expressions)

47 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java More examples

The C# compiler uses type inference rules to determine types which are not explicit. What are the delegate types (i.e. Func<>’s or Action<>’s) of the following lambda expressions?

1 x => x + 1 2 3 ( i n t x ) => x + 1 4 5 x => { return x +1; } 6 7 ( i n t x ) => { return x +1; } 8 9 ( x , y ) => x ∗ y 10 11 ( ) => { Console.WriteLine (); }

48 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz

What are the results?

1 Func f = ( x => x + 2 ) ; 2 i n t a = f ( 1 0 ) ;

1 Func g = ( ( x , y ) => x ∗ y ) ; 2 i n t b = g(10, 20);

50 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz

What are the results?

1 Func, int , int > 2 f1=((k,x)=> 2∗k ( x ) ) ; 3 i n t a1 = f1(f,10); 4 i n t b1 = f 1 ( t => t +1, 10)

1 Func>> 2 g1 = ( x => ( y => ( z => x + y + z ) ) ) ; 3 i n t b1 = g1(10)(20)(30);

51 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz – simple closure

What are the results? 1 i n t z = 100; 2 Func h = ( y => z+ y); 3 i n t c = h ( 1 0 ) ; 4z = 200; 5 i n t d = h ( 1 0 ) ;

Take care of the free variable z, which is included in the closure

Note that the closure contains the variable z itself (or a pointer to it), not a copy of its value

52 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz –“tricky” closure

1 Func Quiz ( i n t z) { 2 . . . // statements here are executed just when Quiz is called 3 . . . // this includes the creation of the hidden closure object 4 return ( y => z+ y); // function returned by Quiz 5 }

Take care of parameter z, which is is a free variable, included in the returned closure. Here, each call of Quiz creates and returns its own closure object, which uses its own copy of z. Note also that, like many other similar languages, C# uses call-by-value.

53 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz –“tricky” closure

1 Func Quiz ( i n t z) { 2 . . . // statements here are executed when Quiz itself is called 3 . . . // this includes the creation of the hidden closure object 4 return ( y => z+ y); // function returned by Quiz 5 }

1 Func k1 = Quiz(100); // k1’sz = 100 2 Func k2 = Quiz(200); // k2’sz = 200 3 i n t i 1 = k1 ( 1 0 ) ; 4 i n t i 2 = k2 ( 1 0 ) ; 5 i n t i 3 = k1 ( 2 0 ) ; 6 i n t i 4 = k2 ( 2 0 ) ;

Each delegate, k1 and k2, has its own closure, with its own copy of z, which will “magically survive”, after the end of Quiz.

54 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz –“trickier” closure – C#

1 // Func> 2 Func Quiz ( i n t q ) { 3 return ( ) => { 4 q = q + 1 ; 5 return q ; 6 } ; 7 }

1 Func k1 = Quiz (100); 2 Func k2 = Quiz (200); 3 4 Console.WriteLine (”{0}{1}{2}”, k1(), k1(), k1()); 5 Console.WriteLine (”{0}{1}{2}”, k2(), k2(), k2()); 6 Console.WriteLine (”{0}{1}{2}”, k1(), k1(), k1());

What are the printed results? 55 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz –“trickier” closure – F#

1 // i n t −> ( unit −> i n t ) 2 l e t Quiz q = 3 l e t mutable p = q // q is not mutable 4 fun () −> 5 p <− p + 1 6 p

1 l e t k1 = Quiz (100) // unit −> i n t 2 l e t k2 = Quiz (200) // unit −> i n t 3 4 Console.WriteLine (”{0}{1}{2}”, k1(), k1(), k1()) 5 Console.WriteLine (”{0}{1}{2}”, k2(), k2(), k2()) 6 Console.WriteLine (”{0}{1}{2}”, k1(), k1(), k1())

What are the printed results?

56 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Quiz –“trickier” closure – JS

1 function Quiz ( q ) { 2 return ( ) => { 3 q = q + 1 4 return q 5 } 6 }

1 l e t k1 = Quiz (100) 2 l e t k2 = Quiz (200) 3 4 console.log (k1(), k1(), k1()) 5 console.log (k2(), k2(), k2()) 6 console.log (k1(), k1(), k1())

What are the printed results?

58 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Simple Java lambda – before v8

Source LambdaJava.java 1 i n t e r f a c e BinaryOp { 2 i n t op ( i n t x , i n t y ) ; 3 } 4 c l a s s LambdaJava { 5 public static void main(String[] args) { 6 BinaryOp add1= new BinaryOp ( ) { 7 p u b l i c i n t op ( i n t x , i n t y ) { return x + y ; } 8 } ; 9 i n t res1 = add1.op(10, 20); 10 System . out .println(res1); 11 } 12 }

60 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Simple Java lambdas – v8

1 @FunctionalInterface // optional annotation – attribute 2 i n t e r f a c e BinaryOp { 3 i n t op ( i n t x , i n t y ) ; 4 } 5 6 c l a s s LambdaJava8 { 7 public static void main(String[] args) { 8 BinaryOp add2=(x, y) −> x + y ; 9 i n t res2 = add2.op(10, 20); 10 System . out .println(res2); 11 12 j a v a . u t i l . function . Function 13 i n c = x −> x + 1 ; // 14 i n t res = inc.apply(10); 15 System . out .println(res); 16 } 17 }

61 / 61