SlideShare a Scribd company logo
1 of 65
LEARNING
 FUNCTIONAL
PROGRAMMING
   WITHOUT
 GROWING A
  NECKBEARD
   by Kelsey Innis / @kelseyinnis
HI!
                    I'm Kelsey.
I work at StackMob writing code that lets our users
 create & manage their applications, APIs, and data
  through the browser. I use Scala and the Lift web
               framework to do that.
WHY ARE YOU HERE?
http://www.youtube.com/embed/Lb8BCl6NKn0
To learn to write code with drive that don't take no
                        jive.
THE PAM GRIER CRITERIA FOR
     CODE BADASSERY
   Code, like Pam Grier, should be:
          Powerful,
          Beautiful, and
          Tough to mess with.
POWERFUL
Do big things
Do them easily
Do them quickly
TOUGH TO MESS WITH
Secure from outside manipulation
Hard to unintentionally make mistakes
Easy to maintain
BEAUTIFUL
Elegant, concise, and--yes--readable
Able to be easily reused
Fun to write
SCALA!
don't need parentheses for method calls
semicolons are optional
return value is the last line of the method
static typing with type inference
BUT WHAT DOES IT LOOK LIKE?
val   x: String = "a"
val   y = 2
val   z = 15.3
val   myThing = new Thing
val   theList = List("this", "sure", "is", "a", "list")
val   whatIsIt = theList(4)
BUT WHAT DOES IT LOOK LIKE?
def haggle(theirPrice: Int, myOffer: Int): String = {
        val theResponse: String =
                if (theirPrice <= myOffer + 5) {
                         "You've got a deal!"
                } else {
                         "I definitely wouldn't pay more than " +
                         (myOffer + (theirPrice - myOffer)/2) +
                         " for it."
                }
        theResponse
}

val askingPrice = 100
val iWantToPay = 50
val letsMakeADeal = haggle(askingPrice, iWantToPay)
FUNCTIONAL
PROGRAMMING
WHAT IS FUNCTIONAL
  PROGRAMMING?
  Well, what is a program?
ASK A KID
 (OR SIMPLE ENGLISH WIKIPEDIA)




                 A computer
               program is a list




WRONG
                of instructions
                   that tell a
              computer what to
                      do.
Imperative programming:
a sequence of commands that the computer carries
                 out in sequence

          Object-oriented programming:
these instructions, and the data they manipulate, are
                organized into objects
If a program's not a series of commands, then
                  what is it?
“Functional programming is a style of
 programming that emphasizes the
evaluation of expressions rather than
    the execution of commands.”
   —comp.lang.functional FAQ
WHAT THINGS ARE
val theQueen = "Elizabeth II"



                          but also...
def theGovernor(state: State) = {
        val candidates = state.getCandidates
        candidates(getTopVoteGetter)
}
WHAT IS A FUNCTION?



          A function is a relation
          between values where
          each of its input values
          gives back exactly one
           output value, playa.
SOME FUNCTIONS
Math.sqrt(x)
Collections.max(list)
Arrays.copyOf(original, newLength)
String.valueOf(anInt)
A function is pure if “the impact of a function on the
rest of the program [can] be described only in terms of
   its return type, and...the impact of the rest of the
program on the function be described only in terms of
            its arguments”. (Victor Nicollet)
This is our building block.




          Sooooo....
FUNCTIONS ARE DETERMINISTIC.
You will always get the same result if you run them
                with the same data.
             correctness is more clear
             unit tests are a breeze
             debugging is more directed

                    tough to mess with
FUNCTIONS ARE ENCAPSULATED.
“With a referentially transparent function, the interface-
     level activity is all one needs to know about its
            behavior.”. (Michael O. Church)
                        readability
                        reuse
                        maintainability

                           beautiful


                       tough to mess with
FUNCTIONS ARE COMMUTATIVE.
val firstThing = doOneThing()
val secondThing = doAnotherThing()

val thirdThing = doTheLastThing(firstThing, secondThing)



                        parallelization
                        concurrency
                        lazy evaluation

                                powerful
DATA IS IMMUTABLE.
Once an object is created, it cannot be changed.
If you need to change an object, make your own
                     copy.
                    a quick detour back to Java...

String s1 = "san dimas high school football rules"
String s2 = s1.toUpperCase

println("string 1: " + s1);
println("string 2: " + s2);



                       concurrency
                       rollback of data
                       simplicity

          powerful                               tough to mess with
Functions are deterministic
Functions are encapsulated
Functions are commutative
Data is immutable
                              Let's build.
...how?
FUNCTIONS AS FIRST CLASS CITIZENS
FIRST CLASS CITIZENS
val longSkinnyThing: String = "this is a string"
val listOfThem: List[String] = List("yarn","twine","thread")
val freshNewLongSkinnyThing: String = spinFromFiber("wool")
tieInAKnot(longSkinnyThing)




 class Rope(type:String) {
    override def toString(): String = "You've put me on a diet!";
}

val longSkinnyThing: Rope = new Rope("nautical")
val listOfThem: List[String] =
    List(longSkinnyThing, new Rope("climbing"),
    new Rope("clothesline"), new Rope("jump"))
val freshNewLongSkinnyThing: Rope = spinFromFiber("hemp")
tieInAKnot(longSkinnyThing)
val addSpam: (String) => String =
        { (x:String) => x + " and Spam" }
addSpam("Egg and Bacon")
        //result: "Egg and Bacon and Spam"
val menuOptions = List(addSpam, withoutSpam)
menuOptions(1)("Egg and Bacon and Spam")
        //result: "You can't have that"




   addSpam's type is (String) => String
(list of parameters' types) => return
                 type
RETURNING FUNCTIONS FROM
             FUNCTIONS
def tagText(tag: String, text: String) = "<" + tag +">" + text +
""
val noReally = tagText("em", "pay attention!!!!")
        //result: <em>pay attention!!!!</em>

def tagText2(tag: String) = { (text:String) =>"<" + tag +">" + te
xt + "" }
val tagWithAndSpam = tagText2("andSpam")
val breakfast = tagWithAndSpam("Spam Bacon and Sausage")
        //result: <andSpam>Spam Bacon and Sausage</andSpam>




                               beautiful


                                powerful
CURRYING




  YUM!
HIGHER-ORDER FUNCTIONS
FOR LOOP
                               Java

public void talkAboutFruit {
         Fruit[] fruits = {
                 new Fruit("apple"),
                 new Fruit("cherry"),
                 new Fruit("strawberry")
         };
         for (int i = 0; i < fruits.length; i++) {
                 System.out.println("Hey the other day I ate a " +
  fruits[i];
         }
}

                               Scala

 def talkAboutFruit = {
        val fruits = List(new Fruit("apple"),
                          new Fruit("cherry"),
                          new Fruit("strawberry"))
        for (i <- 0 until fruits.length) {
                System.out.println("Hey the other day I ate a " +
 fruits(i);
        }
}
LET'S GET ABSTRACT
    a function that takes a list and a function
          (list of parameters' types) => return type

  foreach(fruitList:List(fruits),
theFunction: (Fruit) => Unit): Unit
  def foreach(fruitList:List(fruits), theFunction: (Fruit) => Unit
) = {
         for (i <- 0 until fruitList.length) {
                 theFunction(fruits(i))
         }
}

 def talkAboutFruit = {
        val fruits = List(new Fruit("apple"),
                          new Fruit("cherry"),
                          new Fruit("strawberry"))
        val tellEm =
                { (f:Fruit) => System.out.println(
                        "Hey the other day I ate a " + f) }
        foreach(fruits, tellEm)
        }
}
MORE ABSTRACTERER!
foreach(theList:List(A), theFunction:
         (A) => Unit): Unit
abstract class Collection[A] {
        ...
        def foreach(theFunction: (A) => Unit): Unit
        ...
}

 def talkAboutFruit = {
        val fruits = List(new Fruit("apple"),
                          new Fruit("cherry"),
                          new Fruit("strawberry"))
        val tellEm =
                { (f:Fruit) => System.out.println(
                        "Hey the other day I ate a " + f) }
        fruits.foreach(tellEm)
        }
}
THIS:
abstract class Collection[A] {
        ...
        def foreach(theFunction: (A) => Unit): Unit = {
                for (i <- 0 until this.length) {
                        theFunction(this(i))
                }
        }
        ...
}


        IS NOT HOW SCALA
      IMPLEMENTED FOREACH
                          tough to mess with


                                powerful
SOMETHING A LITTLE JUICIER
def makePies: List[Pie] = {
        val fruits = List(new Fruit("apple"),
                          new Fruit("cherry"),
                          new Fruit("strawberry"))
        var pies = List()
        for (i <- 0 until fruits.length) {
                new Pie(fruits(i)) :: pies
        }
        pies
}


           on a collection of A, you can
        map(theFunction: (A) => B):
                 Collection[B]
def makePies: List[Pie] = {
        val fruits = List(new Fruit("apple"),
                          new Fruit("cherry"),
                          new Fruit("strawberry"))
        val makePie = { (f: Fruit) => new Pie(f) }
        fruits.map(makePie)
}
ANONYMOUS FUNCTIONS
val kindOfFruit: String = "blueberry"
val blueberryFruit = new Fruit(kindOfFruit)
val alsoBlueberry = new Fruit("blueberry")

val makePie = { (f: Fruit) => new Pie(f) }
fruits.map(makePie)
//equivalent to
fruits.map( { (f: Fruit) => new Pie(f) } )

def makePies: List[Pie] = {
        val fruits = List(new Fruit("apple"),
                          new Fruit("cherry"),
                          new Fruit("strawberry"))
        fruits.map( { (f: Fruit) => new Pie(f) } )
}

def makePies(fruits: List[Fruit]) : List[Pie]
         = fruits.map( { (f: Fruit) => new Pie(f) } )




                               beautiful
COLLECTION HANDLING
                            FILTER
val theList = List(new Fruit("apple"), new Fruit("pear"), new Fru
it("cherry"), new Fruit("strawberry"), new Fruit("honeydew"))

scala> theList.filter( { (f: Fruit) => f.isDelicious } )
res0: List[Fruit] = List(apple, cherry, strawberry)

                             FOLD
scala> theList.fold("The fruits on this list are: ")( { (stringSo
Far: String, f: Fruit) => stringSoFar + " " + f.name } )
res1: String = "The fruits on this list are: apple pear cherry st
rawberry honeydew"

                           REDUCE
scala> theList.fold(0)( { (count: Int, f: Fruit) => count + " " +
 f.totalPieces } )
res2: Int = 42300

theList.reduce( { (f: Fruit) => f.totalPieces } )
res3: Int = 42300
NESTED FOR-LOOPS
  def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]):
List(Serving[Pie, IceCream]) {
         val servings = List[Serving[Pie,IceCream]]()
         for (p <- 0 until pies.length) {
                  for (i <- 0 until iceCreams.length) {
                          val serving = new Serving(p, i)
                          serving :: servings
                  }
         }
         servings
}

  def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]):
List(Serving[Pie, IceCream]) {
         pies.map( { (p: Pie) =>
                 iceCreams.map( { (i: IceCream) =>
                         new Serving(p, i)
                 } )
         } )
}
IS THIS AN IMPROVEMENT?
def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]): L
ist(Serving[Pie, IceCream]) {
        val servingsLists =
                pies.map( { (p: Pie) =>
                        iceCreams.map( { (i: IceCream) =>
                                new Serving(p, i)
                        } )
                } )
        servingsLists.flatten
}
FUNCTION COMPOSITION




  def bakeAPie(f: Fruit, c: Crust): Pie
  def eatAPie(p: Pie): HappyKelsey

  def bakeAndEatAPie(f: Fruit, c: Crust): HappyKelsey = eatAPie com
  pose bakeAPie
          //could also be written bakeAPie andThen eatAPie


flatten compose map is flatMap, and it's MAGIC
FOR-YIELD
  def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]):
List(Serving[Pie, IceCream]) {
         for {
                 p <- pies
                 i <- iceCreams
         } yield {
                 new Serving(p,i)
         }
}




                               beautiful!
FUN WITH FOR-YIELD
  def goodPairings(pies: List[Pie], iceCreams: List[IceCream]): Li
st(Serving[Pie, IceCream]) {
         for {
                 p <- pies
                 i <- iceCreams
                 val serving = new Serving(p,i)
                 if (serving.isGood)
         } yield {
                 serving
         }
}

  def pleaseEverybody(audience: List[Person], pies: List[Pie], ice
Creams: List[IceCream]): List(ThankYou) {
         for {
                 person <- audience
                 p <- pies
                 i <- iceCreams
                 val serving = new Serving(p,i)
                 if (serving.isGood)
         } yield {
                 person.feed(serving)
         }
}
partial application
higher order functions
function composition
for-yield
AND NOW FOR SOMETHING
(NOT REALLY) COMPLETELY DIFFERENT
NULL.
YUCK
 public Serving<Pie, IceCream> serveBestALaMode(Pie key, Map<Pie,
 IceCream> pairings) {
     if(pairings != null) {
         IceCream iceCream = pairings.get(key);
         if(iceCream != null) {
             return new Serving(key, iceCream)
         } else {
                  return null;
         }
     }
 }


SCALA PROGRAMMING DOESN'T USE NULL.
              YIPPEE!
OPTION
Option[T] is either a Some with a value of type T
     inside, or None representing nothing.
 val someOption: Option[String] = Some("this is a value")
 val noneOption: Option[String] = None

 val theSomeValue = someOption.get //returns "this is a value"
 val someIsDefined = someOption.isDefined //returns true

 val theNoneValue = noneOption.get //throws NoSuchElementException
 val someIsDefined = someOption.isDefined //returns false
def serveBestALaMode(key: Pie, pairings: Map[Pie, IceCream]): Op
tion[Serving[Pie,IceCream]] = {
         iceCream: Option[IceCream] = pairings.get(key);
         if (iceCream.isDefined) {
                  Some(new Serving(key, iceCream.get))
         } else {
                  None
         }
}
OPTION IS KIND OF LIKE A
          COLLECTION
                             .MAP
someOption.map( {(str:String) => str + " SAN DIMAS HIGH SCHOOL FO
OTBALL RULES"} )
        //returns Some("this is a value SAN DIMAS HIGH SCHOOL FOO
TBALL RULES")
noneOption.map( {(str:String) => str + " SAN DIMAS HIGH SCHOOL FO
OTBALL RULES"} )
        //returns None

                          .FLATMAP
val favoritePie: Option[Pie] = Some(rhubarb)
favoritePie.map({ (pie: Pie) => pairings.get(pie) })
        //returns Some(Some(butterPecan))--whoops!
favoritePie.flatMap( { (pie: Pie) => pairings.get(pie) } )
        //returns Some(butterPecan)

                            .FILTER
val todaysSpecial: Option[Pie]
val myOrder = todaysSpecial.filter( { (pie: Pie) => (pie != butte
rPecan) }
FOR-YIELD OVER OPTION
 for {
         pie <- todaysSpecial
         bestIceCream <- pairings.get(pie)
         iceCream <- availableFlavors.get(bestIceCream) } yield {
         myDessert
}




                                beautiful


                                 powerful


                           tough to mess with
OPTION IS A MONAD
   WHAT IS A MONAD?
"Let’s look at what it is that makes Thing a monad.
The first thing is that I can wrap up a value inside of a
new Thing...We have a function of type A => Thing; a
  function which takes some value and wraps it up
                    inside a new Thing.
  We also have this fancy bind function, which digs
   inside our Thing and allows a function which we
supply to use that value to create a new Thing. Scala
             calls this function “flatMap“....
 What’s interesting here is the fact that bind is how
 you combine two things together in sequence. We
 start with one thing and use its value to compute a
                        new thing."
                    —Daniel Spiewak
FLATMAP IS MAGIC
 flatMap hides our boilerplate. For Lists, it abstracts
away a for-loop, letting us create a new List from an
   existing list. For Options, it abstracts away a null
check, letting us create a new nullable value from an
                       existing one.


                      tough to mess with
OTHER MONADS
accumulating errors
a cursor position in a database or file
states in a state machine
an environment that changes

                 powerful
EXTRA CREDIT WHOA




A SEMICOLON IS A MONAD
partial application
higher order functions
function composition
for-yield
monads
THE PSYCHOLOGY OF
FUNCTIONAL PROGRAMMING
READABILITY
“Is Clojure code hard to understand? Imagine if every
   time you read Java source code and encountered
   syntax elements like if statements, for loops, and
   anonymous classes, you had to pause and puzzle
  over what they mean. There are certain things that
    must be obvious to a person who wants to be a
  productive Java developer. Likewise there are parts
   of Clojure syntax that must be obvious for one to
    efficiently read and understand code. Examples
 include being comfortable with the use of let, apply,
 map, filter, reduce and anonymous functions...”—R.
                     Mark Volkmann
DSLS
class HelloWorldSpec extends Specification {

      "The 'Hello world' string" should {
        "contain 11 characters" in {
          "Hello world" must have size(11)
        }
        "start with 'Hello'" in {
          "Hello world" must startWith("Hello")
        }
        "end with 'world'" in {
          "Hello world" must endWith("world")
        }
      }
  }

                             from specs2
PURITY




“The truth is that good programmers mix the styles quite
   a bit. We program imperatively when needed, and
   functionally when possible.” - Michael O. Church
THANK YOU

More Related Content

What's hot

Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scalaAmuhinda Hungai
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them AllJohn De Goes
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in ScalaShai Yallin
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Omar Abdelhafith
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type ClassesJohn De Goes
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testingScott Wlaschin
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programmingnewmedio
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix TaskHermann Hueck
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekyoavrubin
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 

What's hot (20)

Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic Programmer
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 

Viewers also liked

Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with XtendSven Efftinge
 
Kerry Karl | Debunking Myths: GLUTEN
Kerry Karl | Debunking Myths: GLUTENKerry Karl | Debunking Myths: GLUTEN
Kerry Karl | Debunking Myths: GLUTENKerry Karl
 
Ratpack - SpringOne2GX 2015
Ratpack - SpringOne2GX 2015Ratpack - SpringOne2GX 2015
Ratpack - SpringOne2GX 2015Daniel Woods
 
5 Reasons Why Your Headlines Are On Life Support
5 Reasons Why Your Headlines Are On Life Support5 Reasons Why Your Headlines Are On Life Support
5 Reasons Why Your Headlines Are On Life SupportWishpond
 
Auktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva online
Auktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva onlineAuktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva online
Auktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva onlineMartin Husovec
 
Historia insp manuel antonio leal chacon
Historia insp   manuel antonio leal chaconHistoria insp   manuel antonio leal chacon
Historia insp manuel antonio leal chaconantonio leal
 
Nuevas tecnologías de
Nuevas tecnologías deNuevas tecnologías de
Nuevas tecnologías demariaelicena
 
基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間
基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間
基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間交點
 
Impacto de las tics en la educaciòn
Impacto de las tics en la educaciònImpacto de las tics en la educaciòn
Impacto de las tics en la educaciònDarìo Miranda S.A
 
Grafico diario del dax perfomance index para el 11 02-2013
Grafico diario del dax perfomance index para el 11 02-2013Grafico diario del dax perfomance index para el 11 02-2013
Grafico diario del dax perfomance index para el 11 02-2013Experiencia Trading
 
Collaboration friday
Collaboration fridayCollaboration friday
Collaboration fridaykacrey
 
Planificacion de eliana caballero
Planificacion de eliana caballeroPlanificacion de eliana caballero
Planificacion de eliana caballeroElianaCaballero
 

Viewers also liked (20)

Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
1 4 vamos a jugar
1 4 vamos a jugar1 4 vamos a jugar
1 4 vamos a jugar
 
Kerry Karl | Debunking Myths: GLUTEN
Kerry Karl | Debunking Myths: GLUTENKerry Karl | Debunking Myths: GLUTEN
Kerry Karl | Debunking Myths: GLUTEN
 
Ratpack - SpringOne2GX 2015
Ratpack - SpringOne2GX 2015Ratpack - SpringOne2GX 2015
Ratpack - SpringOne2GX 2015
 
5 Reasons Why Your Headlines Are On Life Support
5 Reasons Why Your Headlines Are On Life Support5 Reasons Why Your Headlines Are On Life Support
5 Reasons Why Your Headlines Are On Life Support
 
Auktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva online
Auktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva onlineAuktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva online
Auktuálne otázky zodpovednosti za porušovanie práv duševného vlastníctva online
 
Historia insp manuel antonio leal chacon
Historia insp   manuel antonio leal chaconHistoria insp   manuel antonio leal chacon
Historia insp manuel antonio leal chacon
 
Nuevas tecnologías de
Nuevas tecnologías deNuevas tecnologías de
Nuevas tecnologías de
 
基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間
基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間
基隆交點Vol.5 - 王珈琳 - 陪伴,一段服務的時間
 
Impacto de las tics en la educaciòn
Impacto de las tics en la educaciònImpacto de las tics en la educaciòn
Impacto de las tics en la educaciòn
 
8th biosimilars congregation 2016
8th biosimilars congregation 20168th biosimilars congregation 2016
8th biosimilars congregation 2016
 
Future of Grails
Future of GrailsFuture of Grails
Future of Grails
 
Grafico diario del dax perfomance index para el 11 02-2013
Grafico diario del dax perfomance index para el 11 02-2013Grafico diario del dax perfomance index para el 11 02-2013
Grafico diario del dax perfomance index para el 11 02-2013
 
Collaboration friday
Collaboration fridayCollaboration friday
Collaboration friday
 
부용
부용부용
부용
 
leonardo monsalve
leonardo monsalveleonardo monsalve
leonardo monsalve
 
Brexit Webinar Series 3
Brexit Webinar Series 3Brexit Webinar Series 3
Brexit Webinar Series 3
 
Planificacion de eliana caballero
Planificacion de eliana caballeroPlanificacion de eliana caballero
Planificacion de eliana caballero
 
rhythm workshop
rhythm workshoprhythm workshop
rhythm workshop
 

Similar to Learning Functional Programming Without Growing a Neckbeard

pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOJorge Vásquez
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final TaglessJohn De Goes
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)William Narmontas
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional ProgrammingSovTech
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaInnar Made
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8James Brown
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
 

Similar to Learning Functional Programming Without Growing a Neckbeard (20)

pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Scala
ScalaScala
Scala
 
Kotlin
KotlinKotlin
Kotlin
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Functional programming
Functional programming Functional programming
Functional programming
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 

Recently uploaded

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 

Recently uploaded (20)

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 

Learning Functional Programming Without Growing a Neckbeard

  • 1. LEARNING FUNCTIONAL PROGRAMMING WITHOUT GROWING A NECKBEARD by Kelsey Innis / @kelseyinnis
  • 2. HI! I'm Kelsey. I work at StackMob writing code that lets our users create & manage their applications, APIs, and data through the browser. I use Scala and the Lift web framework to do that.
  • 3. WHY ARE YOU HERE? http://www.youtube.com/embed/Lb8BCl6NKn0 To learn to write code with drive that don't take no jive.
  • 4. THE PAM GRIER CRITERIA FOR CODE BADASSERY Code, like Pam Grier, should be: Powerful, Beautiful, and Tough to mess with.
  • 5. POWERFUL Do big things Do them easily Do them quickly
  • 6. TOUGH TO MESS WITH Secure from outside manipulation Hard to unintentionally make mistakes Easy to maintain
  • 7. BEAUTIFUL Elegant, concise, and--yes--readable Able to be easily reused Fun to write
  • 8. SCALA! don't need parentheses for method calls semicolons are optional return value is the last line of the method static typing with type inference
  • 9. BUT WHAT DOES IT LOOK LIKE? val x: String = "a" val y = 2 val z = 15.3 val myThing = new Thing val theList = List("this", "sure", "is", "a", "list") val whatIsIt = theList(4)
  • 10. BUT WHAT DOES IT LOOK LIKE? def haggle(theirPrice: Int, myOffer: Int): String = { val theResponse: String = if (theirPrice <= myOffer + 5) { "You've got a deal!" } else { "I definitely wouldn't pay more than " + (myOffer + (theirPrice - myOffer)/2) + " for it." } theResponse } val askingPrice = 100 val iWantToPay = 50 val letsMakeADeal = haggle(askingPrice, iWantToPay)
  • 12. WHAT IS FUNCTIONAL PROGRAMMING? Well, what is a program?
  • 13. ASK A KID (OR SIMPLE ENGLISH WIKIPEDIA) A computer program is a list WRONG of instructions that tell a computer what to do.
  • 14. Imperative programming: a sequence of commands that the computer carries out in sequence Object-oriented programming: these instructions, and the data they manipulate, are organized into objects
  • 15. If a program's not a series of commands, then what is it?
  • 16.
  • 17. “Functional programming is a style of programming that emphasizes the evaluation of expressions rather than the execution of commands.” —comp.lang.functional FAQ
  • 18. WHAT THINGS ARE val theQueen = "Elizabeth II" but also... def theGovernor(state: State) = { val candidates = state.getCandidates candidates(getTopVoteGetter) }
  • 19. WHAT IS A FUNCTION? A function is a relation between values where each of its input values gives back exactly one output value, playa.
  • 21. A function is pure if “the impact of a function on the rest of the program [can] be described only in terms of its return type, and...the impact of the rest of the program on the function be described only in terms of its arguments”. (Victor Nicollet)
  • 22. This is our building block. Sooooo....
  • 23. FUNCTIONS ARE DETERMINISTIC. You will always get the same result if you run them with the same data. correctness is more clear unit tests are a breeze debugging is more directed tough to mess with
  • 24. FUNCTIONS ARE ENCAPSULATED. “With a referentially transparent function, the interface- level activity is all one needs to know about its behavior.”. (Michael O. Church) readability reuse maintainability beautiful tough to mess with
  • 25. FUNCTIONS ARE COMMUTATIVE. val firstThing = doOneThing() val secondThing = doAnotherThing() val thirdThing = doTheLastThing(firstThing, secondThing) parallelization concurrency lazy evaluation powerful
  • 26. DATA IS IMMUTABLE. Once an object is created, it cannot be changed. If you need to change an object, make your own copy. a quick detour back to Java... String s1 = "san dimas high school football rules" String s2 = s1.toUpperCase println("string 1: " + s1); println("string 2: " + s2); concurrency rollback of data simplicity powerful tough to mess with
  • 27. Functions are deterministic Functions are encapsulated Functions are commutative Data is immutable Let's build.
  • 29. FUNCTIONS AS FIRST CLASS CITIZENS
  • 30. FIRST CLASS CITIZENS val longSkinnyThing: String = "this is a string" val listOfThem: List[String] = List("yarn","twine","thread") val freshNewLongSkinnyThing: String = spinFromFiber("wool") tieInAKnot(longSkinnyThing) class Rope(type:String) { override def toString(): String = "You've put me on a diet!"; } val longSkinnyThing: Rope = new Rope("nautical") val listOfThem: List[String] = List(longSkinnyThing, new Rope("climbing"), new Rope("clothesline"), new Rope("jump")) val freshNewLongSkinnyThing: Rope = spinFromFiber("hemp") tieInAKnot(longSkinnyThing)
  • 31. val addSpam: (String) => String = { (x:String) => x + " and Spam" } addSpam("Egg and Bacon") //result: "Egg and Bacon and Spam" val menuOptions = List(addSpam, withoutSpam) menuOptions(1)("Egg and Bacon and Spam") //result: "You can't have that" addSpam's type is (String) => String (list of parameters' types) => return type
  • 32. RETURNING FUNCTIONS FROM FUNCTIONS def tagText(tag: String, text: String) = "<" + tag +">" + text + "" val noReally = tagText("em", "pay attention!!!!") //result: <em>pay attention!!!!</em> def tagText2(tag: String) = { (text:String) =>"<" + tag +">" + te xt + "" } val tagWithAndSpam = tagText2("andSpam") val breakfast = tagWithAndSpam("Spam Bacon and Sausage") //result: <andSpam>Spam Bacon and Sausage</andSpam> beautiful powerful
  • 35. FOR LOOP Java public void talkAboutFruit { Fruit[] fruits = { new Fruit("apple"), new Fruit("cherry"), new Fruit("strawberry") }; for (int i = 0; i < fruits.length; i++) { System.out.println("Hey the other day I ate a " + fruits[i]; } } Scala def talkAboutFruit = { val fruits = List(new Fruit("apple"), new Fruit("cherry"), new Fruit("strawberry")) for (i <- 0 until fruits.length) { System.out.println("Hey the other day I ate a " + fruits(i); } }
  • 36. LET'S GET ABSTRACT a function that takes a list and a function (list of parameters' types) => return type foreach(fruitList:List(fruits), theFunction: (Fruit) => Unit): Unit def foreach(fruitList:List(fruits), theFunction: (Fruit) => Unit ) = { for (i <- 0 until fruitList.length) { theFunction(fruits(i)) } } def talkAboutFruit = { val fruits = List(new Fruit("apple"), new Fruit("cherry"), new Fruit("strawberry")) val tellEm = { (f:Fruit) => System.out.println( "Hey the other day I ate a " + f) } foreach(fruits, tellEm) } }
  • 37. MORE ABSTRACTERER! foreach(theList:List(A), theFunction: (A) => Unit): Unit abstract class Collection[A] { ... def foreach(theFunction: (A) => Unit): Unit ... } def talkAboutFruit = { val fruits = List(new Fruit("apple"), new Fruit("cherry"), new Fruit("strawberry")) val tellEm = { (f:Fruit) => System.out.println( "Hey the other day I ate a " + f) } fruits.foreach(tellEm) } }
  • 38. THIS: abstract class Collection[A] { ... def foreach(theFunction: (A) => Unit): Unit = { for (i <- 0 until this.length) { theFunction(this(i)) } } ... } IS NOT HOW SCALA IMPLEMENTED FOREACH tough to mess with powerful
  • 39. SOMETHING A LITTLE JUICIER def makePies: List[Pie] = { val fruits = List(new Fruit("apple"), new Fruit("cherry"), new Fruit("strawberry")) var pies = List() for (i <- 0 until fruits.length) { new Pie(fruits(i)) :: pies } pies } on a collection of A, you can map(theFunction: (A) => B): Collection[B] def makePies: List[Pie] = { val fruits = List(new Fruit("apple"), new Fruit("cherry"), new Fruit("strawberry")) val makePie = { (f: Fruit) => new Pie(f) } fruits.map(makePie) }
  • 40. ANONYMOUS FUNCTIONS val kindOfFruit: String = "blueberry" val blueberryFruit = new Fruit(kindOfFruit) val alsoBlueberry = new Fruit("blueberry") val makePie = { (f: Fruit) => new Pie(f) } fruits.map(makePie) //equivalent to fruits.map( { (f: Fruit) => new Pie(f) } ) def makePies: List[Pie] = { val fruits = List(new Fruit("apple"), new Fruit("cherry"), new Fruit("strawberry")) fruits.map( { (f: Fruit) => new Pie(f) } ) } def makePies(fruits: List[Fruit]) : List[Pie] = fruits.map( { (f: Fruit) => new Pie(f) } ) beautiful
  • 41. COLLECTION HANDLING FILTER val theList = List(new Fruit("apple"), new Fruit("pear"), new Fru it("cherry"), new Fruit("strawberry"), new Fruit("honeydew")) scala> theList.filter( { (f: Fruit) => f.isDelicious } ) res0: List[Fruit] = List(apple, cherry, strawberry) FOLD scala> theList.fold("The fruits on this list are: ")( { (stringSo Far: String, f: Fruit) => stringSoFar + " " + f.name } ) res1: String = "The fruits on this list are: apple pear cherry st rawberry honeydew" REDUCE scala> theList.fold(0)( { (count: Int, f: Fruit) => count + " " + f.totalPieces } ) res2: Int = 42300 theList.reduce( { (f: Fruit) => f.totalPieces } ) res3: Int = 42300
  • 42. NESTED FOR-LOOPS def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]): List(Serving[Pie, IceCream]) { val servings = List[Serving[Pie,IceCream]]() for (p <- 0 until pies.length) { for (i <- 0 until iceCreams.length) { val serving = new Serving(p, i) serving :: servings } } servings } def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]): List(Serving[Pie, IceCream]) { pies.map( { (p: Pie) => iceCreams.map( { (i: IceCream) => new Serving(p, i) } ) } ) }
  • 43. IS THIS AN IMPROVEMENT? def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]): L ist(Serving[Pie, IceCream]) { val servingsLists = pies.map( { (p: Pie) => iceCreams.map( { (i: IceCream) => new Serving(p, i) } ) } ) servingsLists.flatten }
  • 44. FUNCTION COMPOSITION def bakeAPie(f: Fruit, c: Crust): Pie def eatAPie(p: Pie): HappyKelsey def bakeAndEatAPie(f: Fruit, c: Crust): HappyKelsey = eatAPie com pose bakeAPie //could also be written bakeAPie andThen eatAPie flatten compose map is flatMap, and it's MAGIC
  • 45. FOR-YIELD def tryAllPairings(pies: List[Pie], iceCreams: List[IceCream]): List(Serving[Pie, IceCream]) { for { p <- pies i <- iceCreams } yield { new Serving(p,i) } } beautiful!
  • 46. FUN WITH FOR-YIELD def goodPairings(pies: List[Pie], iceCreams: List[IceCream]): Li st(Serving[Pie, IceCream]) { for { p <- pies i <- iceCreams val serving = new Serving(p,i) if (serving.isGood) } yield { serving } } def pleaseEverybody(audience: List[Person], pies: List[Pie], ice Creams: List[IceCream]): List(ThankYou) { for { person <- audience p <- pies i <- iceCreams val serving = new Serving(p,i) if (serving.isGood) } yield { person.feed(serving) } }
  • 47. partial application higher order functions function composition for-yield
  • 48. AND NOW FOR SOMETHING (NOT REALLY) COMPLETELY DIFFERENT
  • 49. NULL.
  • 50. YUCK public Serving<Pie, IceCream> serveBestALaMode(Pie key, Map<Pie, IceCream> pairings) { if(pairings != null) { IceCream iceCream = pairings.get(key); if(iceCream != null) { return new Serving(key, iceCream) } else { return null; } } } SCALA PROGRAMMING DOESN'T USE NULL. YIPPEE!
  • 51. OPTION Option[T] is either a Some with a value of type T inside, or None representing nothing. val someOption: Option[String] = Some("this is a value") val noneOption: Option[String] = None val theSomeValue = someOption.get //returns "this is a value" val someIsDefined = someOption.isDefined //returns true val theNoneValue = noneOption.get //throws NoSuchElementException val someIsDefined = someOption.isDefined //returns false
  • 52. def serveBestALaMode(key: Pie, pairings: Map[Pie, IceCream]): Op tion[Serving[Pie,IceCream]] = { iceCream: Option[IceCream] = pairings.get(key); if (iceCream.isDefined) { Some(new Serving(key, iceCream.get)) } else { None } }
  • 53. OPTION IS KIND OF LIKE A COLLECTION .MAP someOption.map( {(str:String) => str + " SAN DIMAS HIGH SCHOOL FO OTBALL RULES"} ) //returns Some("this is a value SAN DIMAS HIGH SCHOOL FOO TBALL RULES") noneOption.map( {(str:String) => str + " SAN DIMAS HIGH SCHOOL FO OTBALL RULES"} ) //returns None .FLATMAP val favoritePie: Option[Pie] = Some(rhubarb) favoritePie.map({ (pie: Pie) => pairings.get(pie) }) //returns Some(Some(butterPecan))--whoops! favoritePie.flatMap( { (pie: Pie) => pairings.get(pie) } ) //returns Some(butterPecan) .FILTER val todaysSpecial: Option[Pie] val myOrder = todaysSpecial.filter( { (pie: Pie) => (pie != butte rPecan) }
  • 54. FOR-YIELD OVER OPTION for { pie <- todaysSpecial bestIceCream <- pairings.get(pie) iceCream <- availableFlavors.get(bestIceCream) } yield { myDessert } beautiful powerful tough to mess with
  • 55. OPTION IS A MONAD WHAT IS A MONAD?
  • 56. "Let’s look at what it is that makes Thing a monad. The first thing is that I can wrap up a value inside of a new Thing...We have a function of type A => Thing; a function which takes some value and wraps it up inside a new Thing. We also have this fancy bind function, which digs inside our Thing and allows a function which we supply to use that value to create a new Thing. Scala calls this function “flatMap“.... What’s interesting here is the fact that bind is how you combine two things together in sequence. We start with one thing and use its value to compute a new thing." —Daniel Spiewak
  • 57. FLATMAP IS MAGIC flatMap hides our boilerplate. For Lists, it abstracts away a for-loop, letting us create a new List from an existing list. For Options, it abstracts away a null check, letting us create a new nullable value from an existing one. tough to mess with
  • 58. OTHER MONADS accumulating errors a cursor position in a database or file states in a state machine an environment that changes powerful
  • 59. EXTRA CREDIT WHOA A SEMICOLON IS A MONAD
  • 60. partial application higher order functions function composition for-yield monads
  • 62. READABILITY “Is Clojure code hard to understand? Imagine if every time you read Java source code and encountered syntax elements like if statements, for loops, and anonymous classes, you had to pause and puzzle over what they mean. There are certain things that must be obvious to a person who wants to be a productive Java developer. Likewise there are parts of Clojure syntax that must be obvious for one to efficiently read and understand code. Examples include being comfortable with the use of let, apply, map, filter, reduce and anonymous functions...”—R. Mark Volkmann
  • 63. DSLS class HelloWorldSpec extends Specification { "The 'Hello world' string" should { "contain 11 characters" in { "Hello world" must have size(11) } "start with 'Hello'" in { "Hello world" must startWith("Hello") } "end with 'world'" in { "Hello world" must endWith("world") } } } from specs2
  • 64. PURITY “The truth is that good programmers mix the styles quite a bit. We program imperatively when needed, and functionally when possible.” - Michael O. Church