Post on 03-Jun-2020
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Functional ProgrammingFirst class functions, lambdas and closures
Radu NicolescuDepartment of Computer Science
University of Auckland
23 July 2018
1 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
1 Programming paradigms
2 Pure FP
3 Recursion
4 C# 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 Quiz JS Java
Programming paradigms
• Object-oriented: develop complex objects starting with simpleobjects (using inheritance, aggregation, delegation, ...)
• Functional: develop complex functions starting with simplefunctions (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 Quiz JS 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, eventop-level, functions
• Problem: how to represent anonymous inline functions (suchas lambdas) in OOP?
• Solution: embed these in the current object, if possible, orinside hidden automatically constructed objects – more atclosures
5 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Basic ingredients of FP
• first-class and higher order functions (aka, functionals)
• informally, you can work with functions as with any otherobjects – and compose them!
• you can have functions that take functions as parameters andreturn functions (functions which may be dynamicallycomposed)
• currying 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 Quiz JS Java
Pure FP
• Function results should only depend on parameter values
• No side effects: Functions should not change the global stateor any persistent state (unlike object methods which changethe object’s state)
• Immutable values: Ideally, functions should not change anyvalue at all! – This is possible if we use recursion instead ofclassical loops...
• As one of the advantages, programs will be easier to provecorrect, to optimize or to parallelize
8 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Pure FP
• For example, if f and g don’t change any global variable norany of their parameters (i.e., a, b, c , d), the following twostatements can run in parallel, on a dual-core machine:
1 x = f ( a , b ) ; — function f could be evaluated on core #123 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 toexplicit or localize these (e.g., via so-called monads)
9 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Variables and mutability in C#
• Class fields and properties : vast topic, but not much of ourconcern here...
• var or normal declarations are mutable
1 var x = 1 0 ; x = x + 1 ;2 i n t x = 1 0 ; x = x + 1 ;
• const defines compile-time immutable values
1 const x = 1 0 ;
• readonly defines run-time immutable fields – maybe differentlyinitialised in constructors, but then is frozen
1 readonly i n t x ;
10 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS 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 pub l i c s t a t i c readonly i n t [ ] A3 = new in t [ ] { 10 , 20 , 30 , } ;4 }56 void Main ( ) {7 var B = new in t [ ] { 100 , 200 , 300 , } ;8 // C . A = B ; // NOT allowed9 C . A [ 1 ] = 2 0 0 ; // allowed!
10 C . A . Dump ( ) ;11 }
• Conclusions: flexible but porous
11 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Variables and mutability in F#
• Class fields and properties : vast topic, but not much of ourconcern 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 wouldthink: it is a boolean equality test that returns false !
• Mutable variables must be explicitly declared so
1 l e t mutable x = 102 x <− x + 1
• Increased awareness: the assignment to a mutable variableuses a distinct op sign <−
12 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS 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 immutable2 A . [ 1 ] <− 200 // allowed!3 A . Dump ( )
• Why this exception for arrays? Because of the HUGE body ofscientific algorithms, which have been developed andoptimised for FORTRAN mutable arrays
• F# encourages a more pure style, and promotes increasedawareness of mutability – but still allows one the choice to useother styles
13 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS 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 = 103 x = x + 14 }
• const declarations are immutable with block local scope
1 i f ( b ) {2 const x = 103 // x = x + 1 // not allowed4 }
• More in part (M) 14 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Imperative factorial
• F#
1 l e t f a c t n : i n t =2 l e t mutable m = n3 l e t mutable f = 14 whi le (m >= 1) do5 f <− f ∗ m6 m <− m − 17 f89 p r i n t f n ” I m p e r a t i v e : %A” ( f a c t 5)
16 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Naive recursive factorial
• F#
1 l e t rec f a c t ’ n =2 i f n <= 0 then 13 e l s e ( f a c t ’ ( n−1)) ∗ n45 p r i n t f n ” Naive R e c u r s i v e : %A” ( f a c t ’ 5)
• Performance issues, stack overflow
17 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Tail recursive factorial
• F#
1 l e t f a c t ’ ’ n =2 l e t rec f a c t t a i l r e c n acc =3 i f ( n <= 0) then acc4 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 167 p r i n t f n ” T a i l R e c u r s i v e : %A” ( f a c t ’ ’ 5)
• F# : TCO = Tail Call Optimisation
• NO performance issues, NO stack overflow
18 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS 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 whi le ( n > 0) {3 acc = n ∗ acc ;4 n = n − 1 ;5 }6 return acc ;7 }8 pub l i c s t a t i c i n t f a c t ( i n t n ) {9 return f a c t t a i l r e c ( n , 1 ) ;
10 }
• NO performance issues, NO stack overflow
19 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
C# Delegates in a nutshell
• Consider this scenario
1 c l a s s C {2 pub l i c i n t F ( i n t x ) { return x +1; }3 pub l i c i n t G ( i n t y ) { return y+y ; }4 pub l i c s t a t i c i n t 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 W r i t e L i n e ($”{ c1 . F ( 3 )} { c2 . G( 3 )} {C .H( 3 )} ” ) ;2 // 4 6 9
21 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
C# Delegates in a nutshell
• Same scenario
1 c l a s s C {2 pub l i c i n t F ( i n t x ) { return x +1; }3 pub l i c i n t G ( i n t y ) { return y+y ; }4 pub l i c s t a t i c i n t H ( i n t z ) { return z∗ z ; }5 }
• More flexible usage using typed function pointers!
1 Func <int , int> f = c1 . F ;2 Func <int , int> g = c2 . G ;3 Func <int , int> h = C .H;4 W r i t e L i n e ($”{ f ( 3 )} {g ( 3 )} {h ( 3 )} ” ) ;5 // 4 6 9
• The same pointer, e.g. f, could point in turn to all thesemethods!
22 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
C# Delegates
• A delegate is a .NET type-safe pointer to a function, i.e. to aclass 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 theactual class is not needed at runtime)
23 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Predefined delegate types in C# – Function types in F#
1 Func<T1 , T2 , . . . , Tn , TResult> (n ∈ {0, 1, 2, . . . , 16}) // C#23 f : T1∗T2 ∗ . . . ∗Tm − > un i t // F#
• functions taking T1,T2 ,..., Tn and returning TResult, i.e.
• f : T1× T2× . . .Tn→ TResult – maths notation.
1 Act ion<T1 , T2 , . . . , Tm> (m ∈ {0, 1, 2, . . . , 16}) // C#23 f : T1∗T2 ∗ . . . ∗Tm − > un i t // F#
• “functions” taking T1,T2 ,..., Tm and returning void , i.e.
• f : T1× T2× . . .Tm→ void – maths-like notation.
• unit is the F# “void” type, with one single value ()
24 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Delegates – visualisation
To visualise the target of a delegate to a method, consider thefollowing scenario (Linqpad)
• a class C – nested in the outer Linqpad class, UserQuery
1 c l a s s C {2 pub l i c i n t X { get ; set ; }3 pub l i c i n t F ( i n t v ) { return v + X ; }4 pub l i c s t a t i c i n t G( i n t v ) { return v + 1 0 0 ; }5 }
• two instances of C, o1 and o2
1 var o1 = new C { X = 10 , } ;2 var o2 = new C { X = 20 , } ;34 W r i t e L i n e ($”{o1 . F ( 1 )} , {o2 . F ( 1 )} , {C . G( 1 )} ” ) ;5 // 11 , 21 , 101
25 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Delegates – visualisation
• three pointers to functions (delegates)
1 Func<int , int> f 1 = o1 . F ;2 Func<int , int> f 2 = o2 . F ;3 Func<int , int> g = C . G ;4 W r i t e L i n e ($”{ f 1 ( 1 )} ,{ f 2 ( 1 )} ,{ g ( 1 )} ” ) ; //11 ,21 ,101
• visualise their target objects
1 f 1 . Target . Dump( ” f 1 ” ) ;23 f 2 . Target . Dump( ” f 2 ” ) ;45 g . Target . Dump( ”g” ) ;
26 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS 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 ananonymous (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 bynumbers which indicate the position (De Brujin).
28 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
λ-expressions
• Pure λ-calculus has NO variables, NO loops/recursion (butthese can simulated by way of Y combinators).
• Still, λ-calculus is an universal model of computationequivalent 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 Quiz JS Java
Lambdas as anonymous inline functions
• C# examples:
1 Func<s t r ing , int> f = (string s) => s.Length ;
2
3 Func<s t r ing , int> 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 ng −> i n t = fun s − > s.Length
30 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Lambdas — Other examples
• C#, F#
1 Func<int> g = () => 2 ; // C#2 l e t g = fun () − > 2 ; // F# un i t −> 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<int , int , int> 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 Quiz JS Java
Lambdas have two faces!
Janus, from Wikipedia
1 Anonymous inline functions
2 Expression trees
32 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Lambdas as Expression trees!
• The other face of lambdas (≈ compilation arrested atintermediate tree structures)
• Consider the following scenario, where the same lambda canbe assigned to different left-handside type!
1 Func<int , int> g = x => x + 2 ;
2
3 E x p r e s s i o n<Func<int , int>> t = x => x + 2 ;
• g is a pointer to a .NET function int → int
• t is a tree structure, called Expression, representing such afunction
• This tree structure is similar to the intermediate tree structureused by the compiler, when compiling g
33 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Lambdas as Expression Trees!
• t can be easily visualised via Linqpad’s Dump() operator
1 t . Dump ( . . . ) ;
Lambda
Func<int,int>
Parameter
x int
Expression
Add int
Parameter
x int
Constant
2 int
parameters body
left right
34 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Sidebar: Typical translation/compilation steps (simplified)
• Source code expression: (x + y) ∗ z
• Abstract syntax tree (AST)
*
+ z
yx
• 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 Quiz JS Java
Lambdas as Expression Trees!
• Consider
1 E x p r e s s i o n<Func<int , int>> t = x => x + 2 ;
• t can be dynamically compiled (at runtime) into a .NETfunction int → int and subsequently executed
1 g = t . Compi le ( ) ;2 var b = g ( 1 0 0 ) ;
• According to the context, providers can compile t to manydifferent 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 Quiz JS Java
A lambda with a free variable
1 Func<int , int> 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 thelexical context)
• the closure of f ≡ f plus z
Closure
The closure of a function is the function itself plus contextreferences for all its free variables.
38 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
The closure object
1 Func<int , int> f = ( i n t y ) => y + z ;
In C#, closures are implemented as hidden, compiler-generatedclosure 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 names2 pub l i c i n t z ;3 pub l i c i n t f ( i n t y ) { return y + z ; }4 }
Other implementations exist, but this one is “natural” in OOlanguages (C#, Java) and clarifies “tricky” scenarios
39 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS 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<int> f = ( ) => x + y ;4 Func<int> g = ( ) => x ∗ x ;
• An instance of the following OO class:
1 c l a s s C {2 pub l i c i n t x = 1 0 ;3 pub l i c i n t y = 2 0 ;4 pub l i c i n t f ( ) { return x + y ; }5 pub l i c i n t g ( ) { return x ∗ x ; }6 }
40 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Targets and Closures – visualisation
To visualise the target of a delegate to a lambda, consider thefollowing scenario (Linqpad)
1 Func<int , int> f = v => v + 1 ;2 i n t x = 1 0 ;3 Func<int , int> g = v => v + x ; // closure!4 W r i t e L i n e ($”{ f ( 1 0 )} , {g ( 1 0 )} ” ) ; // 11 , 2056 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 Quiz JS Java
Dynamic access to closure details – C#
• Consider the following function Quiz. Quiz returns a closure,which includes the field w
1 Func<int , int> 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 wof a closure generated by Quiz
1 Func<int , int> k2 = Quiz ( 2 0 0 ) ; // . w = 2012 i n t i 2 = k2 ( 1 0 ) ; // 21134 dynamic t = k2 . Target ; // duck t y p i n g 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 Quiz JS Java
Dynamic access to closure details – C#
43 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
A lambda taking another lambda
1 Func<Func<int , int >, int , int> h = (f , x) => f (x) ;
• h is a function of two parameters:a function Func<int, int> 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 Quiz JS Java
A lambda returning another lambda
1 Func<int , Func<int , int>> h = x => (y => x + y) ;
• h is a function of one int parameter, x
• which returns an anonymous Func<int, int> function, of oneint parameter, y
• sample invocation: var r = h(10)(20)
• h is similar, but not identical, to the function h of twovariables from the preceding slide
• another invocation:
1 Func<int , int> k = h(10) ; var r = k ( 3 0 ) ;
2 which is equivalent to
3 Func<int , int> k = (y => 10 + y) ; var r = k ( 3 0 ) ;
46 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Expression lambdas and statement lambdas
Two kind of lambdas (so far we’ve seen only the first type):
• expression lambdas
param => expr or (params) => expr
• statement lambdasparam => {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 syntaxtrees (assigned to Expressions)
47 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
More examples
The C# compiler uses type inference rules to determine typeswhich are not explicit.
What are the delegate types (i.e. Func<>’s or Action<>’s) of thefollowing lambda expressions?
1 x => x + 123 ( i n t x ) => x + 145 x => { return x +1; }67 ( i n t x ) => { return x +1; }89 ( x , y ) => x ∗ y
1011 ( ) => { C o n s o l e . W r i t e L i n e ( ) ; }
48 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz
What are the results?
1 Func<int , int> f = ( x => x + 2 ) ;2 i n t a = f ( 1 0 ) ;
1 Func<int , int , int> g = ( ( x , y ) => x ∗ y ) ;2 i n t b = g ( 1 0 , 2 0 ) ;
50 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz
What are the results?
1 Func<Func<int , int >, int , int>2 f 1 = ( ( k , x ) => 2∗k ( x ) ) ;3 i n t a1 = f 1 ( f , 1 0 ) ;4 i n t b1 = f 1 ( t => t +1, 10)
1 Func<int , Func<int , Func<int , int>>>2 g1 = ( x => ( y => ( z => x + y + z ) ) ) ;3 i n t b1 = g1 ( 1 0 ) ( 2 0 ) ( 3 0 ) ;
51 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz – simple closure
What are the results?
1 i n t z = 1 0 0 ;2 Func<int , int> h = ( y => z + y ) ;3 i n t c = h ( 1 0 ) ;4 z = 2 0 0 ;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 toit), not a copy of its value
52 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz –“tricky” closure
1 Func<int , int> Quiz ( i n t z) {2 . . . // statements here are executed just when Quiz is called3 . . . // this includes the creation of the hidden closure object4 return ( y => z + y ) ; // function returned by Quiz5 }
Take care of parameter z , which is is a free variable, included inthe 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# usescall-by-value.
53 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz –“tricky” closure
1 Func<int , int> Quiz ( i n t z) {2 . . . // statements here are executed when Quiz itself is called3 . . . // this includes the creation of the hidden closure object4 return ( y => z + y ) ; // function returned by Quiz5 }
1 Func<int , int> k1 = Quiz ( 1 0 0 ) ; // k1’s z = 1002 Func<int , int> k2 = Quiz ( 2 0 0 ) ; // k2’s z = 2003 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 copyof z , which will “magically survive”, after the end of Quiz.
54 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz –“trickier” closure – C#
1 // Func<int , Func<int>>2 Func<int> Quiz ( i n t q ) {3 return ( ) => {4 q = q + 1 ;5 return q ;6 } ;7 }
1 Func<int> k1 = Quiz ( 1 0 0 ) ;2 Func<int> k2 = Quiz ( 2 0 0 ) ;34 C o n s o l e . W r i t e L i n e ( ”{0} {1} {2}” , k1 ( ) , k1 ( ) , k1 ( ) ) ;5 C o n s o l e . W r i t e L i n e ( ”{0} {1} {2}” , k2 ( ) , k2 ( ) , k2 ( ) ) ;6 C o n s o l e . W r i t e L i n e ( ”{0} {1} {2}” , k1 ( ) , k1 ( ) , k1 ( ) ) ;
What are the printed results?55 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz –“trickier” closure – F#
1 // i n t −> ( un i t −> i n t )2 l e t Quiz q =3 l e t mutable p = q // q is not mutable4 fun ( ) −>5 p <− p + 16 p
1 l e t k1 = Quiz ( 1 0 0 ) // un i t −> i n t2 l e t k2 = Quiz ( 2 0 0 ) // un i t −> i n t34 C o n s o l e . W r i t e L i n e ( ”{0} {1} {2}” , k1 ( ) , k1 ( ) , k1 ( ) )5 C o n s o l e . W r i t e L i n e ( ”{0} {1} {2}” , k2 ( ) , k2 ( ) , k2 ( ) )6 C o n s o l e . W r i t e L i n e ( ”{0} {1} {2}” , k1 ( ) , k1 ( ) , k1 ( ) )
What are the printed results?
56 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Quiz –“trickier” closure – JS
1 funct ion Quiz ( q ) {2 return ( ) => {3 q = q + 14 return q5 }6 }
1 l e t k1 = Quiz ( 1 0 0 )2 l e t k2 = Quiz ( 2 0 0 )34 c o n s o l e . l o g ( k1 ( ) , k1 ( ) , k1 ( ) )5 c o n s o l e . l o g ( k2 ( ) , k2 ( ) , k2 ( ) )6 c o n s o l e . l o g ( k1 ( ) , k1 ( ) , k1 ( ) )
What are the printed results?
58 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Simple Java lambda – before v8
Source LambdaJava.java
1 i n t e r f a ce BinaryOp {2 i n t op ( i n t x , i n t y ) ;3 }4 c l a s s LambdaJava {5 pub l i c s t a t i c void main ( S t r i n g [ ] a r g s ) {6 BinaryOp add1 = new BinaryOp ( ) {7 pub l i c i n t op ( i n t x , i n t y ) { return x + y ;}8 } ;9 i n t r e s 1 = add1 . op ( 1 0 , 2 0 ) ;
10 System . out . p r i n t l n ( r e s 1 ) ;11 }12 }
60 / 61
Paradigms Pure Rec Delegates Lambdas Closures More Quiz JS Java
Simple Java lambdas – v8
1 @ F u n c t i o n a l I n t e r f a c e // optional annotation – attribute2 i n t e r f a ce BinaryOp {3 i n t op ( i n t x , i n t y ) ;4 }56 c l a s s LambdaJava8 {7 pub l i c s t a t i c void main ( S t r i n g [ ] a r g s ) {8 BinaryOp add2 = ( x , y ) −> x + y ;9 i n t r e s 2 = add2 . op ( 1 0 , 2 0 ) ;
10 System . out . p r i n t l n ( r e s 2 ) ;1112 j a v a . u t i l . funct ion . Funct ion<I n t e g e r , I n t e g e r>13 i n c = x −> x + 1 ; // <Integer , Integer>14 i n t r e s = i n c . a p p l y ( 1 0 ) ;15 System . out . p r i n t l n ( r e s ) ;16 }17 }
61 / 61