SlideShare a Scribd company logo
Functional Programming
     101 in Groovy



            Evgeny Goldin
  DevCon Tel-Aviv, February 14, 2013
Evgeny Goldin


Java developer since 2000
FP enthusiast: Scheme, Perl, Groovy, Scala
GroovyMag, Gr8Conf
SCM at Trademob
github.com/evgeny-goldin/
@evgeny_goldin
Are you FP-er?
http://thecoolnessfactor.com/2013/01/winds-change/changes-ahead-exit-sign/
In this session

     Why FP?
 FP building blocks
   FP in Groovy
   FP candidates
In this session


Mindset switch
Why FP?
Because shit happens
.. or do we make it happen?
Average code is complex
                     Side-effects go wild
             Logical steps are interleaved
                 Changes are error-prone




http://www.guardian.co.uk/sustainable-business/research-confirms-health-impacts-tire
Average state is fragile and shared
 Exposed for updates in any way
Can easily mutate under your feet
       Changes are error-prone




  http://www.bbcgoodfood.com/content/knowhow/glossary/egg/
Parallelism is hard
              “The Multicore Revolution”
       Threads + shared mutable state :(
                Changes are error-prone




http://www.russel.org.uk/Presentations/euroPython2010_theMulticoreRevolution.pdf
       http://jalopnik.com/5965581/this-is-how-not-to-parallel-park-on-a-hill
Changes are error-prone
http://lenta.ru/sitemap.xml



https://bitbucket.org/evgenyg/devcon-2013/src/master/sitemap-imperative.groovy
https://bitbucket.org/evgenyg/devcon-2013/src/master/sitemap-functional.groovy
Modularity
Break the flow into distinct steps
  Do one thing and do it well
Flexibility
Shuffle your steps
Testability
Ensure correctness of your steps
Parallelism
Scale your steps!
FP building blocks
(only a subset this time)
Recursion
               List = head() + tail()
  State is hidden, built up on stack
              Recursion elimination
https://bitbucket.org/evgenyg/devcon-2013/src/master/recursion.groovy
Immutable State
Moving parts are minimized
   No defensive copying
   Caching, Parallelism
Immutable State
      New state = f ( old state )
Changes are isolated, constructor only
   g ( i + 1 ), g ( list + ‘element’ )
Immutable State
 Persistent data structures
      Updated in place
Yields a new immutable state
Git




http://git-scm.com/book/en/Git-Branching-What-a-Branch-Is
First-class functions
          Anonymous functions
         Higher-order functions
Command/Template/Visitor => “Free Willy”
No side-effects
 sin, cos, max, min, sum, sort
Opens doors for optimizations
     Caching, Parallelism
Mindset switch
        Imperative => Functional
          Variables => Values
            Classes => Functions
Explicit instructions => Declarative definitions
       How (Steps) => What (Result)
Mindset switch
Pointers, memory allocations, GC - check
           State management
               Iterations
      Filtering, conversion, folding
               Parallelism
FP in Groovy
Gradual
                                        conversion



http://www.buysgmath.com/p/200/eph-gradually-difficulty-mathematics-1/
final j = 5
@Immutable
Anonymous Functions
     a.k.a. Closures
Filter - findAll()
                                        Map - collect()
                                        Fold - inject()

     https://bitbucket.org/evgenyg/devcon-2013/src/master/functions.groovy


http://www.barlifeuk.com/index.php/2012/08/enter-the-janneau-armagnac-three-
                        musketeers-inspired-competition/
find()
     any()
    every()
    each()
eachWithIndex()
  takeWhile()
  dropWhile()
Collection
     Range
      Map
     Array
     String
       ...
Object.iterator()
Categories, Meta, Extensions
public	
  static	
  <T>	
  Collection<T>	
  findAll(Collection<T>	
  self,	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  Closure	
  filter)	
  

public	
  static	
  <T>	
  List<T>	
  collect(Collection<?>	
  self,
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  Closure<T>	
  transform)

public	
  static	
  T	
  inject(Collection<T>	
  self,	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  Closure<V>	
  closure)

public	
  static	
  <T>	
  T	
  	
  	
  	
  	
  	
  	
  head(List<T>	
  self)


public	
  static	
  <T>	
  List<T>	
  tail(List<T>	
  self)

...

                                 org.codehaus.groovy.runtime.DefaultGroovyMethods
Memoization
                       a.k.a. Caching
https://bitbucket.org/evgenyg/devcon-2013/src/master/memoization.groovy
Trampoline
Recursion => Loop (no stack overflow)
https://bitbucket.org/evgenyg/devcon-2013/src/master/trampoline.groovy
GPars!
                  Data Parallelism
https://bitbucket.org/evgenyg/devcon-2013/src/master/gpars.groovy
eachParallel()
collectParallel()
findAllParallel()
everyParallel()
 foldParallel()
 sumParallel()
  gmemoize()
FP Candidates
Loops => any / every




https://bitbucket.org/evgenyg/devcon-2013/src/master/loops.groovy
                http://en.hdyo.org/tee/questions
Split, filter, map, fold



 https://bitbucket.org/evgenyg/devcon-2013/src/master/map-reduce.groovy
https://bitbucket.org/evgenyg/devcon-2013/src/master/check-versions.groovy




       http://www.cityofwaterfalls.ca/hermitage_cascade.html
Open your eyes
pinboard.in/u:evgenyg/t:fp/

 Arturo Herrero - Functional Programming with Groovy

            Neal Ford - Functional Thinking

        Martin Odersky - FP Principles in Scala

             Erik Meijer - FP Fundamentals

MIT - Structure and Interpretation of Computer Programs

   University of Washington - Programming Languages

           Stanford - Programming Paradigms
Thank you!




 @evgeny_goldin
evgenyg@gmail.com

More Related Content

PDF
Asynchronous CompletableFuture Presentation by László-Róbert Albert @Crossover
PDF
Fighting async JavaScript (CSP)
PDF
Development Principles & Philosophy
PDF
Loading...git
PDF
Communicating Sequential Processes (CSP) in JavaScript
PPTX
PDF
3 d pie chart circular puzzle with hole in center pieces 7 stages style 4 pow...
Asynchronous CompletableFuture Presentation by László-Róbert Albert @Crossover
Fighting async JavaScript (CSP)
Development Principles & Philosophy
Loading...git
Communicating Sequential Processes (CSP) in JavaScript
3 d pie chart circular puzzle with hole in center pieces 7 stages style 4 pow...

Viewers also liked (19)

PPTX
Alimentazione americana e Mc donald' s Vittoria Tomas
PPTX
Alat ukur
PPTX
Power of Personal Branding for Brands - Pubcon 2015
PPTX
LinkedIn Endorsements
PDF
Sharing data from clinical and medical research
PDF
Engage 2013 - Why Upgrade to v10 Tag
PDF
Grafico diario del dax perfomance index para el 09 07-2012
PDF
Brochure about Stanford Corporate Governance Research Initiative
PDF
Tick Achieve - How To Get Stuff Done
PPTX
2.7 mbonfim
PPT
獅子山下女同志
PPT
Система Постройком
PDF
Artikel FI
PPTX
Ready Player One - Week 2 Check-in
DOCX
1. cronograma 2014
PPTX
Guidelines to evaluate blended learning programs
DOCX
PPT
Газоанализатор ООО НПП Импульс
PPTX
「旅のことば」について
Alimentazione americana e Mc donald' s Vittoria Tomas
Alat ukur
Power of Personal Branding for Brands - Pubcon 2015
LinkedIn Endorsements
Sharing data from clinical and medical research
Engage 2013 - Why Upgrade to v10 Tag
Grafico diario del dax perfomance index para el 09 07-2012
Brochure about Stanford Corporate Governance Research Initiative
Tick Achieve - How To Get Stuff Done
2.7 mbonfim
獅子山下女同志
Система Постройком
Artikel FI
Ready Player One - Week 2 Check-in
1. cronograma 2014
Guidelines to evaluate blended learning programs
Газоанализатор ООО НПП Импульс
「旅のことば」について
Ad

Similar to Functional Programming in Groovy (20)

PPT
What's New in Groovy 1.6?
ODP
The why and how of moving to PHP 5.4/5.5
PDF
Swt J Face 3/3
PPT
Groovy Maven Builds
PDF
Building resilient services in go
ODP
The why and how of moving to php 5.4/5.5
PDF
Native Java with GraalVM
KEY
Writing your Third Plugin
PDF
PHP Performance Trivia
PDF
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
PDF
Groovy - Grails as a modern scripting language for Web applications
PPT
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
PPTX
Groovy And Grails Introduction
ODP
The why and how of moving to PHP 5.5/5.6
KEY
Psgi Plack Sfpm
KEY
Psgi Plack Sfpm
PDF
jQuery Internals + Cool Stuff
KEY
groovy & grails - lecture 7
KEY
Intro to PSGI and Plack
PDF
Advanced Topics in Continuous Deployment
What's New in Groovy 1.6?
The why and how of moving to PHP 5.4/5.5
Swt J Face 3/3
Groovy Maven Builds
Building resilient services in go
The why and how of moving to php 5.4/5.5
Native Java with GraalVM
Writing your Third Plugin
PHP Performance Trivia
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Groovy - Grails as a modern scripting language for Web applications
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
Groovy And Grails Introduction
The why and how of moving to PHP 5.5/5.6
Psgi Plack Sfpm
Psgi Plack Sfpm
jQuery Internals + Cool Stuff
groovy & grails - lecture 7
Intro to PSGI and Plack
Advanced Topics in Continuous Deployment
Ad

More from Evgeny Goldin (8)

PDF
Alexa skills
PDF
Polyglot Gradle with Node.js and Play
PDF
Node.js meets jenkins
PDF
Release It!
PDF
Spock Extensions Anatomy
PDF
10 Cool Facts about Gradle
PPTX
Start Writing Groovy
PPTX
Maven Plugins
Alexa skills
Polyglot Gradle with Node.js and Play
Node.js meets jenkins
Release It!
Spock Extensions Anatomy
10 Cool Facts about Gradle
Start Writing Groovy
Maven Plugins

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
PPTX
Spectroscopy.pptx food analysis technology
PPTX
sap open course for s4hana steps from ECC to s4
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PPTX
A Presentation on Artificial Intelligence
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Empathic Computing: Creating Shared Understanding
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation_ Review paper, used for researhc scholars
The Rise and Fall of 3GPP – Time for a Sabbatical?
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
Spectroscopy.pptx food analysis technology
sap open course for s4hana steps from ECC to s4
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
A Presentation on Artificial Intelligence
Per capita expenditure prediction using model stacking based on satellite ima...
Programs and apps: productivity, graphics, security and other tools
A comparative analysis of optical character recognition models for extracting...
Reach Out and Touch Someone: Haptics and Empathic Computing
“AI and Expert System Decision Support & Business Intelligence Systems”
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Empathic Computing: Creating Shared Understanding

Functional Programming in Groovy