small lambda talk @booster2015
TRANSCRIPT
Small lambda talk
• Java 8 introduced lambda expressions
• focus on functional programming
• Also roots in object oriented programming: Smalltalk
Smalltalk – everything is simple
• Illustration, reserved words:
• self (=this), super, nil (=null), true, false
Java reserved words ….abstract default goto package synchronized
assert do if private this
boolean double implements protected throw
break else import public throws
byte enum instanceof return transient
case extends int short true
catch false interface static try
char final long strictfp void
class finally native super volatile
const float new switch while
continue for null
Messages - unary
• No arguments
• Invocation example:
• Implementation in class Number:
2 negated
negated
^0 - self
public Number negated() {
return 0 - this;
}
2.negated()
Equivalent “Java” Syntax
Messages - binary
• Exactly one argument
• Message selector (method name) made from special
characters: = , + , - , > etc.
• Invocation
• Implementation in class Object:
a = b
= anObject
^self == anObject
public boolean equals(Object obj){
return this == obj;
}
a.equals(b)
Equivalent “Java” Syntax
Messages - keyword
• One or more arguments
• Each argument is separated by a keyword
• Invocation:
• Implementation:
a at: 1 put: ‘one’
at: key put: value
self cache
at: key put: value
public Object put(Integer key, String value){
this.cache()
.put(key,value);
return this;
}
a.put(1, “one”);
Equivalent “Java” Syntax
OO Conditional Processing Example
• Task:
• Use recursion to return root of
tree
• Each node may access its
parent by sending the parent
message
OO branching- blocks
root
^self parent = nil
ifTrue: [self]
ifFalse: [self parent root]
ifTrue: trueBlock ifFalse:
falseBlock
^trueBlock value
ifTrue: trueBlock
ifFalse: falseBlock
^falseBlock value
Implementation in True: Implementation in False:
OO branching- characteristics
• Voilla! We have made if else with only objects and
messages
• Boolean instance is an object
• Code blocks are objects
• Implemented as one message, one expression, one return
value.
root
^self parent = nil
ifTrue: [self]
ifFalse: [self parent root]
More OO conditional logic
and: block
^block value
True implementation:
boolExpr1 and: [boolExpr2].
boolExpr1 or: [boolExpr2].
boolExpr not
and: block
^self
False implementation:
or: block
^self
or: block
^block value
not
^false
not
^true
boolExpr1 && boolExpr2;
boolExpr1 || boolExpr2;
!boolExpr;
Learning points
• Anything may be expressed using objects, messages
and lambdas:
• Branches, loops, exception handling ….
• Common language features may be implemented with
lambdas
• Source code acts as documentation
• Possible to debug
• Many ways to arrange program flow
• Polymorphy
• Behavioural design patterns
Workshop 13:3
0 Room #2