SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Discovering Functional Treasure
in
Idiomatic Groovy
Naresha K
Enteleki Solutions
!
naresha.k@gmail.com
@naresha_k
An imperative
language on JVM
A dynamic
with Functional Flavour
The origin
http://radio-weblogs.com/0112098/2003/08/29.html
initial idea was to make a little dynamic language which
compiles directly to Java classes and provides all the nice
(alleged) productivity benefits
- James Strachan
Prerequisites
Function
!
def sayHello(){!
! println 'Hello'!
}!
!
sayHello()!
Closure
def wish = {!
! println "Hello"!
}!
!
wish()
def wishFriend = {!
! println "Hello $it"!
} !
!
wishFriend 'Raj'
def wishFriend = { to ->!
! println "Hello $to"!
}!
!
wishFriend 'Raj'
Closure - No Arg
def wish = { ->!
! println "Hello"!
}!
!
wish()
Closure - Multiple args
def wishWithMessage = { to, message ->!
! println "Hello $to, $message"!
}!
!
wishWithMessage "Raj", "Good Evening"
Closures = Power functions
def wishWithMessage = { to, message ->!
! println "Hello $to, $message"!
}!
!
wishWithMessage "Raj", "Good Evening"
def <var> = <closure>
Functions as Values
Sample Data
import groovy.transform.ToString!
!
@ToString(includeNames=true)!
class Geek{!
String name!
int age!
List<String> languages!
}
def geeks = []!
geeks << new Geek(name: 'Raj', age: 24, !
! languages: ['Java', 'Groovy'])!
geeks << new Geek(name: 'Arun', age: 35, !
! languages: ['Java', 'Scala', 'Clojure'])!
geeks << new Geek(name: 'Kumar', age: 28, !
! languages: ['Groovy', 'Scala'])!
Geeks who can speak Groovy
def findGroovyGeeksImperative(geeks){!
! def groovyGeeks = []!
! for(geek in geeks){!
! if(geek.languages.contains('Groovy')){!
! groovyGeeks << geek!
! }!
! }!
! groovyGeeks!
}
Geeks who can speak Groovy
def findGroovyGeeksImperative(geeks){!
! def groovyGeeks = []!
! for(geek in geeks){!
! if(geek.languages.contains('Groovy')){!
! groovyGeeks << geek!
! }!
! }!
! groovyGeeks!
}
Generalised
def findGeeks(geeks, String language){!
! def knowsLang = []!
! for(geek in geeks){!
! if(geek.languages.contains(language)){!
! knowsLang << geek!
! }!
! }!
! knowsLang!
}!
Towards Idiomatic Groovy
def findGroovyGeeksFunctional(geeks){!
! geeks.findAll({it.languages.contains('Groovy')})!
}
def findGroovyGeeksFunctional(geeks){!
! geeks.findAll() {it.languages.contains('Groovy')}!
}
def findGroovyGeeksFunctional(geeks){!
! geeks.findAll {it.languages.contains('Groovy')}!
}
Reusable
def knowsGroovy = { geek -> !
! geek.languages.contains('Groovy')!
}!
!
def findGeeksFunctional(geeks, criterion){!
! geeks.findAll(criterion)!
}!
!
println findGeeksFunctional(geeks, knowsGroovy)
Higher Order Functions
Strategy Pattern
def knowsGroovy = { geek -> !
! geek.languages.contains('Groovy')!
}!
!
def knowsClojure = { geek ->!
! geek.languages.contains('Clojure')!
}!
!
def findGeeksFunctional(geeks, criterion){!
! geeks.findAll(criterion)!
}!
!
println findGeeksFunctional(geeks, knowsGroovy)!
println findGeeksFunctional(geeks, knowsClojure)
Command Pattern
def sayHello = {!
! println "Hello"!
}!
!
def sayHi = {!
! println "Hi"!
}!
!
[sayHello, sayHi].each{ command ->!
! command()!
}
Execute Around
def sayHello = {!
! println "Hello"!
}!
!
def sayHi = {!
! println "Hi"!
}!
!
[sayHello, sayHi].each{ command ->!
! println "Before Command"!
! command()!
! println "After Command"!
}
Code Smell!
def knowsGroovy = { geek -> !
! geek.languages.contains('Groovy')!
}!
!
def knowsClojure = { geek ->!
! geek.languages.contains('Clojure')!
}
After DRYing
def knowsLanguage = { geek, language ->!
! geek.languages.contains(language)!
}!
!
def findGeeks(geeks, criterion, String language){!
! geeks.findAll {criterion(it, language)}!
}!
!
println findGeeks(geeks, knowsLanguage, 'Groovy')
A Better Approach
def knowsLanguage = { geek, language ->!
! geek.languages.contains(language)!
}!
!
def knowsGroovy = knowsLanguage.rcurry('Groovy')!
def knowsClojure = knowsLanguage.rcurry('Clojure')!
!
def findGeeks(geeks, criterion){!
! geeks.findAll(criterion)!
}!
!
println findGeeks(geeks, knowsGroovy)!
println findGeeks(geeks, knowsClojure)
Curried Functions
Geeks
• Knows Groovy
• At least 25 years old
Composing em
def atleast25YearsOld = { geek ->!
! geek.age >= 25!
}!
!
def findGeeks(geeks, criterion){!
! geeks.findAll(criterion)!
}!
!
def findGroovyGeeks = (this.&findGeeks)!
! .rcurry(knowsGroovy)!
def findGeeksAtLeast25 = (this.&findGeeks)!
! .rcurry(atleast25YearsOld)
def findGroovyGeeksOlderThan24 = !
! findGeeksAtLeast25 << findGroovyGeeks!
!
println findGroovyGeeksOlderThan24(geeks)
Function Composition
Towards Immutable Data
def geeks = []!
geeks << new Geek(name: 'Raj', age: 24, !
! languages: ['Java', 'Groovy'])!
geeks << new Geek(name: 'Arun', age: 35, !
! languages: ['Java', 'Scala', 'Clojure'])!
geeks << new Geek(name: 'Kumar', age: 28, !
! languages: ['Groovy', 'Scala'])
geeks2 = geeks + new Geek(name: 'Mark', age: 40, !
! languages: ['Lisp', 'Haskell'])
geeksImmutable = geeks.asImmutable()
Towards Immutable Data …
def geeksOrderedByAge = geeks.sort { it.age }!
println geeksOrderedByAge!
println geeks
def geeksOrderedByAge = geeks.sort false, { it.age }!
println geeksOrderedByAge!
println geeks
Pure Functions
Demo
import groovy.transform.*!
!
@TailRecursive!
def factorial(number, fact = 1){!
! number == 0 ? fact : factorial(number - 1, fact * number)!
}!
!
println factorial(2500G)
Tail Call Optimization
Prior to Groovy 2.3
def fact!
fact = { number, result ->!
! number == 0 ? result : !
! ! fact.trampoline(number-1, result * number)!
}.trampoline()
Slow Functions
import groovy.transform.*!
!
@Memoized!
def timeConsumingOperation(int number){!
! println "Performing computation"!
! number * number!
}!
!
println timeConsumingOperation(2)!
println timeConsumingOperation(2)
Memoization
Map Filter Reduce
println geeks.findAll { it.languages.contains('Groovy')}!
! ! ! .collect {it.age}!
! ! ! .sum()!
!
println geeks.findAll { it.languages.contains('Groovy')}!
! ! ! .collect {it.age}!
! ! ! .with{ sum()/ size()}
Defer
Defer
import groovy.transform.*!
!
class Website{!
! String address!
! @Lazy !
! URL url = address.toURL()!
}!
!
!
def fuconf = new Website(address: 'http://functionalconf.com/')!
println fuconf.dump()!
!
def content = fuconf.url.text!
println content.grep("n").size()!
println fuconf.dump()!
Lazy Evaluation
Recursion vs Iteration
Recursion vs Iteration
def ages = geeks.collect { it.age }!
!
def sum!
sum = { head, tail ->!
! if(!tail){!
! ! head!
! }!
! else{!
! ! head + sum(tail.head(), tail.tail())!
! }!
}!
!
println(sum(0, ages))
Recursion vs Iteration
println ages.inject(0) { s, item ->!
! s + item!
}
The Ultimate Lesson
https://twitter.com/mfeathers/status/29581296216
Functional Treasures
Functions as values (First class citizens)
Higher order functions
Curried Functions
Function Composition
Pure Functions (Immutability)
Tail Call Optimization
Memoization
Lazy Evaluation
Welcome to
References
• https://github.com/naresha/functionalconf2014

Weitere ähnliche Inhalte

Was ist angesagt?

Testing API platform with Behat BDD tests
Testing API platform with Behat BDD testsTesting API platform with Behat BDD tests
Testing API platform with Behat BDD testsStefan Adolf
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patternsPascal Larocque
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQLMuhilvarnan V
 
5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment 5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment pcnmtutorials
 
Domain Driven Design and Hexagonal Architecture with Rails
Domain Driven Design and Hexagonal Architecture with RailsDomain Driven Design and Hexagonal Architecture with Rails
Domain Driven Design and Hexagonal Architecture with RailsDeclan Whelan
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Crafted Design - Sandro Mancuso
Crafted Design - Sandro MancusoCrafted Design - Sandro Mancuso
Crafted Design - Sandro MancusoJAXLondon2014
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Gheyath M. Othman
 
Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j Neo4j
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
REST vs. GraphQL: Critical Look
REST vs. GraphQL: Critical LookREST vs. GraphQL: Critical Look
REST vs. GraphQL: Critical LookNordic APIs
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with XtextHolger Schill
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 

Was ist angesagt? (20)

Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
Testing API platform with Behat BDD tests
Testing API platform with Behat BDD testsTesting API platform with Behat BDD tests
Testing API platform with Behat BDD tests
 
Jquery
JqueryJquery
Jquery
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQL
 
5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment 5. Destructuring | ES6 | Assignment
5. Destructuring | ES6 | Assignment
 
Domain Driven Design and Hexagonal Architecture with Rails
Domain Driven Design and Hexagonal Architecture with RailsDomain Driven Design and Hexagonal Architecture with Rails
Domain Driven Design and Hexagonal Architecture with Rails
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Crafted Design - Sandro Mancuso
Crafted Design - Sandro MancusoCrafted Design - Sandro Mancuso
Crafted Design - Sandro Mancuso
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Serving ML easily with FastAPI - meme version
Serving ML easily with FastAPI - meme versionServing ML easily with FastAPI - meme version
Serving ML easily with FastAPI - meme version
 
REST vs. GraphQL: Critical Look
REST vs. GraphQL: Critical LookREST vs. GraphQL: Critical Look
REST vs. GraphQL: Critical Look
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 

Ähnlich wie Discovering functional treasure in idiomatic Groovy

Go(lang) for the Rubyist
Go(lang) for the RubyistGo(lang) for the Rubyist
Go(lang) for the RubyistMark
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!Gautam Rege
 
NUS iOS Swift Talk
NUS iOS Swift TalkNUS iOS Swift Talk
NUS iOS Swift TalkGabriel Lim
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介Wen-Tien Chang
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design PatternsRobert Casanova
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyGautam Rege
 
Crunching data with go: Tips, tricks, use-cases
Crunching data with go: Tips, tricks, use-casesCrunching data with go: Tips, tricks, use-cases
Crunching data with go: Tips, tricks, use-casesSergii Khomenko
 
from Ruby to Objective-C
from Ruby to Objective-Cfrom Ruby to Objective-C
from Ruby to Objective-CEddie Kao
 

Ähnlich wie Discovering functional treasure in idiomatic Groovy (20)

Go(lang) for the Rubyist
Go(lang) for the RubyistGo(lang) for the Rubyist
Go(lang) for the Rubyist
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!
 
Groovy!
Groovy!Groovy!
Groovy!
 
NUS iOS Swift Talk
NUS iOS Swift TalkNUS iOS Swift Talk
NUS iOS Swift Talk
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of ruby
 
Es.next
Es.nextEs.next
Es.next
 
Rails by example
Rails by exampleRails by example
Rails by example
 
Crunching data with go: Tips, tricks, use-cases
Crunching data with go: Tips, tricks, use-casesCrunching data with go: Tips, tricks, use-cases
Crunching data with go: Tips, tricks, use-cases
 
Ruby ile tanışma!
Ruby ile tanışma!Ruby ile tanışma!
Ruby ile tanışma!
 
from Ruby to Objective-C
from Ruby to Objective-Cfrom Ruby to Objective-C
from Ruby to Objective-C
 

Mehr von Naresha K

The Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockThe Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockNaresha K
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveNaresha K
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersNaresha K
 
Implementing Resilience with Micronaut
Implementing Resilience with MicronautImplementing Resilience with Micronaut
Implementing Resilience with MicronautNaresha K
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersNaresha K
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy WayNaresha K
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesNaresha K
 
What's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingWhat's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingNaresha K
 
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Naresha K
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Naresha K
 
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...Naresha K
 
Implementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautImplementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautNaresha K
 
Groovy - Why and Where?
Groovy  - Why and Where?Groovy  - Why and Where?
Groovy - Why and Where?Naresha K
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaNaresha K
 
Groovy Refactoring Patterns
Groovy Refactoring PatternsGroovy Refactoring Patterns
Groovy Refactoring PatternsNaresha K
 
Implementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautImplementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautNaresha K
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with GroovyNaresha K
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveNaresha K
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesNaresha K
 
Beyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaBeyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaNaresha K
 

Mehr von Naresha K (20)

The Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockThe Groovy Way of Testing with Spock
The Groovy Way of Testing with Spock
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain Effective
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Implementing Resilience with Micronaut
Implementing Resilience with MicronautImplementing Resilience with Micronaut
Implementing Resilience with Micronaut
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy Way
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good Practices
 
What's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingWhat's in Groovy for Functional Programming
What's in Groovy for Functional Programming
 
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
 
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
 
Implementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautImplementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with Micronaut
 
Groovy - Why and Where?
Groovy  - Why and Where?Groovy  - Why and Where?
Groovy - Why and Where?
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS Lambda
 
Groovy Refactoring Patterns
Groovy Refactoring PatternsGroovy Refactoring Patterns
Groovy Refactoring Patterns
 
Implementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautImplementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with Micronaut
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good Practices
 
Beyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaBeyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in Java
 

Kürzlich hochgeladen

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Kürzlich hochgeladen (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

Discovering functional treasure in idiomatic Groovy

  • 1. Discovering Functional Treasure in Idiomatic Groovy Naresha K Enteleki Solutions ! naresha.k@gmail.com @naresha_k
  • 2.
  • 3. An imperative language on JVM A dynamic with Functional Flavour
  • 4. The origin http://radio-weblogs.com/0112098/2003/08/29.html initial idea was to make a little dynamic language which compiles directly to Java classes and provides all the nice (alleged) productivity benefits - James Strachan
  • 6. Function ! def sayHello(){! ! println 'Hello'! }! ! sayHello()!
  • 7.
  • 8. Closure def wish = {! ! println "Hello"! }! ! wish() def wishFriend = {! ! println "Hello $it"! } ! ! wishFriend 'Raj' def wishFriend = { to ->! ! println "Hello $to"! }! ! wishFriend 'Raj'
  • 9. Closure - No Arg def wish = { ->! ! println "Hello"! }! ! wish()
  • 10. Closure - Multiple args def wishWithMessage = { to, message ->! ! println "Hello $to, $message"! }! ! wishWithMessage "Raj", "Good Evening"
  • 11. Closures = Power functions def wishWithMessage = { to, message ->! ! println "Hello $to, $message"! }! ! wishWithMessage "Raj", "Good Evening" def <var> = <closure> Functions as Values
  • 12. Sample Data import groovy.transform.ToString! ! @ToString(includeNames=true)! class Geek{! String name! int age! List<String> languages! } def geeks = []! geeks << new Geek(name: 'Raj', age: 24, ! ! languages: ['Java', 'Groovy'])! geeks << new Geek(name: 'Arun', age: 35, ! ! languages: ['Java', 'Scala', 'Clojure'])! geeks << new Geek(name: 'Kumar', age: 28, ! ! languages: ['Groovy', 'Scala'])!
  • 13. Geeks who can speak Groovy def findGroovyGeeksImperative(geeks){! ! def groovyGeeks = []! ! for(geek in geeks){! ! if(geek.languages.contains('Groovy')){! ! groovyGeeks << geek! ! }! ! }! ! groovyGeeks! }
  • 14. Geeks who can speak Groovy def findGroovyGeeksImperative(geeks){! ! def groovyGeeks = []! ! for(geek in geeks){! ! if(geek.languages.contains('Groovy')){! ! groovyGeeks << geek! ! }! ! }! ! groovyGeeks! }
  • 15. Generalised def findGeeks(geeks, String language){! ! def knowsLang = []! ! for(geek in geeks){! ! if(geek.languages.contains(language)){! ! knowsLang << geek! ! }! ! }! ! knowsLang! }!
  • 16. Towards Idiomatic Groovy def findGroovyGeeksFunctional(geeks){! ! geeks.findAll({it.languages.contains('Groovy')})! } def findGroovyGeeksFunctional(geeks){! ! geeks.findAll() {it.languages.contains('Groovy')}! } def findGroovyGeeksFunctional(geeks){! ! geeks.findAll {it.languages.contains('Groovy')}! }
  • 17. Reusable def knowsGroovy = { geek -> ! ! geek.languages.contains('Groovy')! }! ! def findGeeksFunctional(geeks, criterion){! ! geeks.findAll(criterion)! }! ! println findGeeksFunctional(geeks, knowsGroovy) Higher Order Functions
  • 18. Strategy Pattern def knowsGroovy = { geek -> ! ! geek.languages.contains('Groovy')! }! ! def knowsClojure = { geek ->! ! geek.languages.contains('Clojure')! }! ! def findGeeksFunctional(geeks, criterion){! ! geeks.findAll(criterion)! }! ! println findGeeksFunctional(geeks, knowsGroovy)! println findGeeksFunctional(geeks, knowsClojure)
  • 19. Command Pattern def sayHello = {! ! println "Hello"! }! ! def sayHi = {! ! println "Hi"! }! ! [sayHello, sayHi].each{ command ->! ! command()! }
  • 20. Execute Around def sayHello = {! ! println "Hello"! }! ! def sayHi = {! ! println "Hi"! }! ! [sayHello, sayHi].each{ command ->! ! println "Before Command"! ! command()! ! println "After Command"! }
  • 21. Code Smell! def knowsGroovy = { geek -> ! ! geek.languages.contains('Groovy')! }! ! def knowsClojure = { geek ->! ! geek.languages.contains('Clojure')! }
  • 22. After DRYing def knowsLanguage = { geek, language ->! ! geek.languages.contains(language)! }! ! def findGeeks(geeks, criterion, String language){! ! geeks.findAll {criterion(it, language)}! }! ! println findGeeks(geeks, knowsLanguage, 'Groovy')
  • 23. A Better Approach def knowsLanguage = { geek, language ->! ! geek.languages.contains(language)! }! ! def knowsGroovy = knowsLanguage.rcurry('Groovy')! def knowsClojure = knowsLanguage.rcurry('Clojure')! ! def findGeeks(geeks, criterion){! ! geeks.findAll(criterion)! }! ! println findGeeks(geeks, knowsGroovy)! println findGeeks(geeks, knowsClojure) Curried Functions
  • 24. Geeks • Knows Groovy • At least 25 years old
  • 25. Composing em def atleast25YearsOld = { geek ->! ! geek.age >= 25! }! ! def findGeeks(geeks, criterion){! ! geeks.findAll(criterion)! }! ! def findGroovyGeeks = (this.&findGeeks)! ! .rcurry(knowsGroovy)! def findGeeksAtLeast25 = (this.&findGeeks)! ! .rcurry(atleast25YearsOld) def findGroovyGeeksOlderThan24 = ! ! findGeeksAtLeast25 << findGroovyGeeks! ! println findGroovyGeeksOlderThan24(geeks) Function Composition
  • 26. Towards Immutable Data def geeks = []! geeks << new Geek(name: 'Raj', age: 24, ! ! languages: ['Java', 'Groovy'])! geeks << new Geek(name: 'Arun', age: 35, ! ! languages: ['Java', 'Scala', 'Clojure'])! geeks << new Geek(name: 'Kumar', age: 28, ! ! languages: ['Groovy', 'Scala']) geeks2 = geeks + new Geek(name: 'Mark', age: 40, ! ! languages: ['Lisp', 'Haskell']) geeksImmutable = geeks.asImmutable()
  • 27. Towards Immutable Data … def geeksOrderedByAge = geeks.sort { it.age }! println geeksOrderedByAge! println geeks def geeksOrderedByAge = geeks.sort false, { it.age }! println geeksOrderedByAge! println geeks Pure Functions
  • 28. Demo
  • 29. import groovy.transform.*! ! @TailRecursive! def factorial(number, fact = 1){! ! number == 0 ? fact : factorial(number - 1, fact * number)! }! ! println factorial(2500G) Tail Call Optimization
  • 30. Prior to Groovy 2.3 def fact! fact = { number, result ->! ! number == 0 ? result : ! ! ! fact.trampoline(number-1, result * number)! }.trampoline()
  • 32. import groovy.transform.*! ! @Memoized! def timeConsumingOperation(int number){! ! println "Performing computation"! ! number * number! }! ! println timeConsumingOperation(2)! println timeConsumingOperation(2) Memoization
  • 33. Map Filter Reduce println geeks.findAll { it.languages.contains('Groovy')}! ! ! ! .collect {it.age}! ! ! ! .sum()! ! println geeks.findAll { it.languages.contains('Groovy')}! ! ! ! .collect {it.age}! ! ! ! .with{ sum()/ size()}
  • 34. Defer
  • 35. Defer import groovy.transform.*! ! class Website{! ! String address! ! @Lazy ! ! URL url = address.toURL()! }! ! ! def fuconf = new Website(address: 'http://functionalconf.com/')! println fuconf.dump()! ! def content = fuconf.url.text! println content.grep("n").size()! println fuconf.dump()! Lazy Evaluation
  • 37. Recursion vs Iteration def ages = geeks.collect { it.age }! ! def sum! sum = { head, tail ->! ! if(!tail){! ! ! head! ! }! ! else{! ! ! head + sum(tail.head(), tail.tail())! ! }! }! ! println(sum(0, ages))
  • 38. Recursion vs Iteration println ages.inject(0) { s, item ->! ! s + item! }
  • 40. Functional Treasures Functions as values (First class citizens) Higher order functions Curried Functions Function Composition Pure Functions (Immutability) Tail Call Optimization Memoization Lazy Evaluation