SlideShare una empresa de Scribd logo
1 de 42
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaJorge Vásquez
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.CIIT Atd.
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversionPdr Patnaik
 
Quick Select (Decrease and Conquer)
Quick Select (Decrease and Conquer) Quick Select (Decrease and Conquer)
Quick Select (Decrease and Conquer) Gem WeBlog
 
PYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSPYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSAniruddha Paul
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...
Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...
Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...Василь Тереховський
 
Adversarial search
Adversarial searchAdversarial search
Adversarial searchNilu Desai
 
String Matching with Finite Automata,Aho corasick,
String Matching with Finite Automata,Aho corasick,String Matching with Finite Automata,Aho corasick,
String Matching with Finite Automata,Aho corasick,8neutron8
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C ProgramsKandarp Tiwari
 

La actualidad más candente (20)

Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Podstawy php
Podstawy phpPodstawy php
Podstawy php
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversion
 
Quick Select (Decrease and Conquer)
Quick Select (Decrease and Conquer) Quick Select (Decrease and Conquer)
Quick Select (Decrease and Conquer)
 
PYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSPYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMS
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
14 Skip Lists
14 Skip Lists14 Skip Lists
14 Skip Lists
 
Stack
StackStack
Stack
 
Golang Template
Golang TemplateGolang Template
Golang Template
 
Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...
Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...
Урок 11. Створення, редагування та форматування графічних об′єктів у текстово...
 
Lisp
LispLisp
Lisp
 
Adversarial search
Adversarial searchAdversarial search
Adversarial search
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
String Matching with Finite Automata,Aho corasick,
String Matching with Finite Automata,Aho corasick,String Matching with Finite Automata,Aho corasick,
String Matching with Finite Automata,Aho corasick,
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C Programs
 
Quick sort algorithm using slide presentation , Learn selection sort example ...
Quick sort algorithm using slide presentation , Learn selection sort example ...Quick sort algorithm using slide presentation , Learn selection sort example ...
Quick sort algorithm using slide presentation , Learn selection sort example ...
 
たのしい関数型
たのしい関数型たのしい関数型
たのしい関数型
 

Similar a 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
 

Similar a 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
 

Más de 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
 

Más de 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
 

Último

H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
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
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
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!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
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)
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.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