Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Functional Programming in Scala in a Nutshell: ...

Functional Programming in Scala in a Nutshell: Review of Functional Programming in Scala Ch. 1

Avatar for Namuk Park

Namuk Park

March 26, 2017
Tweet

Other Decks in Programming

Transcript

  1. Java is too Verbose // construct a empty list List<Integer>

    list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); // introduce a counting index, i for (int i = 0; i<list.size(); i++) { Integer element = list.get(i); System.out.println(element); } 3
  2. Elegant Functional Programming Way val (openerO, wineO) = (Some(Opener), Some(Wine(vintage

    = 1997))) val contentsO = for { opener <- openerO wine <- wineO } yield opener.open(wine) // contentsO: Option[Contents] = Some(contentsOfWine) // no null, no NullPointerException 5
  3. Elegant Functional Programming Way val (openerO, wineO) = (Some(Opener), None)

    val contentsO = for { opener <- openerO wine <- wineO } yield opener.open(wine) // contentsO: Option[Contents] = None // no null, no NullPointerException 6
  4. Scala supports OOP, too // OOP polymorphism val newOpener: Opener

    = new NormalOpener() val oldOpener: Opener = new BrokenOpener() val wine = new Wine() println(newOpener.open(wine)) // contentsOfWine println(oldOpener.open(wine)) // Exception occurs! 7
  5. Scala is Compatible with Java Compatible with Hadoop and Spark

    → Official language for the bigdata community // joda time based on java import org.joda.time.DateTime, java.util.Date val jodaDt: DateTime = new DateTime(new Date()) val month = month = dt.getMonthOfYear() 8
  6. … and Vice Versa // scala code object Person {

    val MALE = "m"; } // java code public class App { public static void main(String argv[]) { Person$ person = Person$.MODULE$; System.out.println(person.MALE()); } } 9
  7. By Definition, A function is called pure if all its

    inputs are declared as inputs - none of them are hidden - and likewise all its outputs are declared as outputs. 1 — Kris Jenkins 1 It is not a concrete definition but easy and intuitive. 11
  8. Immutability // value, not variable val a = 1 a

    = 2 // error: reassignment to val // list val ints1: List[Int] = 1 :: 2 :: Nil val ints2: List[Int] = ints1 :+ 3 println(ints1) // List(1, 2) println(ints2) // List(1, 2, 3) println(ints2 == 1 :: 2 :: 3 :: Nil) // true 12
  9. Immutability def fibonacci(n : Int): Int = { // while

    loop requires temporary varables var (a, b, i) = (0, 1, 0) while( i < n ) { val c = a + b a = b b = c i = i + 1 } return a } 13
  10. Immutability // recursion doesn't requires temporary varables def fibonacci(n :

    Int): Int = n match { case 0 | 1 => n case _ => fibonacci(n - 1) + fibonacci(n - 2) } 14
  11. Side Effect, by Definition A function is said to have

    a side effect if it modifies some state outside its scope or has an observable interaction with its calling functions or the outside world. — Side effect (computer science), Wikipedia 15
  12. Side Effect // this def has a side effect def

    currentProgram(guide: TVGuide, channel: Int): Program = { val schedule = guide.getSchedule(channel) schedule.programAt(new Date()) } 16
  13. Side Effect // now it has no more side effects

    // and it is immutable def program(guide: TVGuide, channel: Int, date: Date): Program = { val schedule = guide.getSchedule(channel) schedule.programAt(date) } 17
  14. Let's Start at the Beginning Again… A Program is functional

    iff it has no side effects.2 2 cf. Definition using Referential Transparency 18
  15. SoC: Seperation Of Concerns, By Definition Soc is separating a

    computer program into distinct sections, such that each section addresses a separate concern. 20
  16. Testing // algebraic test: // it tests the **rule** of

    the startsWith method. // a and b is stateless, and startsWith has no sideEffect. property("startsWith") = forAll { (a: String, b: String) => (a+b).startsWith(a) } 22
  17. Asynchronous Programming val task = Task { // IO tasks

    ... } task.unsafePerformAsync(v => v.fold(e => e.printStackTrace(), a => println(a)) ) 23
  18. Caution! for FP val list = 1 to 10 //

    good list .map(a => a * a) .foldLeft(0)((sum, a) => sum + a) // bad list .foldLeft(0)((sum, a) => sum + a * a) 25
  19. The Rules for the Functional Programming 1. Elliminate the Side

    Effects 2. Don't use var keyword 3. Don't use new keyword 4. Use Unit type extremely carefully 5. Use case class 6. Define equals 26
  20. FAQ Q. Should i learn haskell? A. ೙ࣻח ইפ׮. ױ,

    ؊ աইоӝ ਤ೧ Haskell੉ ب਑ ੉ ؼ ࣻ ੓׮. ؀ࠗ࠙੄ Functional Programming ޙ ࢲח Haskellਸ ਤ઱۽ ࢸݺظ੓׮. 27
  21. FAQ Q. PiS A. ࠙۝ب ݆Ҋ, ޖ঺ࠁ׮ ೣࣻഋ ೐۽Ӓې߁ী ୡ੼੉

    ݏ୾૓ ଼੉ ইפযࢲ ୶ୌೞ૑ ঋח׮. 28
  22. FizzBuzz Write a program that prints the ints from 1

    to 100. But: - for multiples of three, print Fizz - for multiples of five, print Buzz - for multiples of both three and five, print FizzBuzz 32
  23. FizzBuzz in a Row Write a fizzbuzz program that combines

    the result with comma. 1, 2, Fizz, 4, Buzz, …, 98, Fizz, Buzz 34
  24. Odd Number & to-200 FizzBuzz Write a fizzbuzz-in-a-row program with

    the odd number stream from 1 to 199 . 1, Fizz, Buzz, …, 193, FizzBuzz, 197, 199 35
  25. Grammars · झணۄ ೟Ү! · झணۄ ҕध ب௸ݢ౟ ੑޙ ·

    Effective Scala by Twitter · Effective Scala by Heejong Lee · Hacker Rank for Tutorials · Exercism 37
  26. Textbooks & References · ! झணۄ۽ ߓ਋ח ೣࣻഋ ೐۽Ӓې߁ ·

    Functional Programming Principles in Scala on Coursera · Big Data Analysis with Scala and Spark on Coursera · Scala Excercises 39
  27. Popular Scala Libraries · ! Scalaz: Scala library for functional

    programming · Cats: Lightweight, modular, and extensible library for functional programming · Monix: Asynchronous Programming for Scala · Circe: A JSON library for Scala powered by Cats 40
  28. Haskell · Eta Programming Language, Haskell on the JVM ·

    (о੢ ए਍) ೞझு ଼ : וӚೞ૑݅ ਋ইೞҊ ࣁ۲ػ ೣࣻഋ ঱য 41