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

Learnings From Functional Programming

Learnings From Functional Programming

Journey to learn the basic concepts of Functional Programming.
Short intro and examples on Category Theory and some real life examples of its applications
Step into some core fundamentals of Functional Programming
Introduce function composition whereby composition is an aspect inherited from Category Theory

Pascal How

March 26, 2020
Tweet

More Decks by Pascal How

Other Decks in Programming

Transcript

  1. Motivations You will write better code! Better understanding of RxJava

    Kotlin is a Functional Language Your code will be more robust It’s the next BIG thing!
  2. Journey Reading! Reading! Reading! Category Theory? Application to FP Arrow

    Framework It’s a Long Long Road Brain Damage Brain Damage
  3. Category Theory Eugenia Cheng - “Category Theory is the mathematics

    of mathematics and mathematics is the logical study of how logical things work” Daniela Sfrigola - “Category Theory is about how things compose” Bartosz Milewski - “Category Theory is the science of composition and abstraction”
  4. Basis of Category Theory • Study relationships rather than characteristics

    • A lot can be learned from object interactions
  5. Basis of Category Theory A category consists of • Some

    objects A, B, C • Some morphisms • Compositions and identities • Associativity and unit laws
  6. Composition A B C Is the mother of Is the

    mother of Is the grandmother of
  7. Composition A B C Is the mother of Is the

    mother of Is the grandmother of Composition allows you to deduce arrows that can be omitted
  8. Sameness All equations are lies… or useless 8 + 1

    = 1 + 8 2 x 5 = 5 x 2 (8 + 5) + 5 = 8 + (5 + 5)
  9. Sameness All equations are lies… or useless 8 + 1

    = 1 + 8 2 x 5 = 5 x 2 (8 + 5) + 5 = 8 + (5 + 5) The only equation that is not a lie is x = x
  10. Lessons From Category Theory • Everything should be understood in

    context • Everything should be studied in relationship with other things, not in isolation
  11. What is Functional Programming (FP)? It is a way of

    thinking in order to build software
  12. Pure Functions • Given some inputs, the output is always

    the same • No side effects • Predictable and easy to test
  13. Pure Functions • Given some inputs, the output is always

    the same • No side effects • Predictable and easy to test
  14. Pure Functions • Given some inputs, the output is always

    the same • No side effects • Predictable and easy to test
  15. Pure Functions fun add(x: Int): Int { val y: Int

    = readNumFromFile() return x + y }
  16. Pure Functions fun add(x: Int): Int { val y: Int

    = readNumFromFile() return x + y }
  17. Side Effects fun add(x: Int, y: Int): Int { val

    result = x + y writeResultToFile(result) return result }
  18. Side Effects fun add(x: Int, y: Int): Int { val

    result = x + y writeResultToFile(result) return result }
  19. Side Effects • Any code that writes to the outside

    world e.g. file, DB, delete • Depends on historical context • Less predictable
  20. Side Effects • Any code that writes to the outside

    world e.g. file, DB, delete • Depends on historical context • Less predictable
  21. Side Effects • Any code that writes to the outside

    world e.g. file, DB, delete • Depends on historical context • Less predictable
  22. Immutability val fancyCar = Car("Jessica") val fancyCar = Car("Shakira") or

    val otherFancyCar = fancyCar.copy(name = "Shakira")
  23. Avoid Shared State • Any variable, object or memory space

    that exists in a shared scope • The classic problem - Race Condition • Changing order in which functions are called can cause failures
  24. Avoid Shared State • Any variable, object or memory space

    that exists in a shared scope • The classic problem - Race Condition • Changing order in which functions are called can cause failures
  25. Avoid Shared State • Any variable, object or memory space

    that exists in a shared scope • The classic problem - Race Condition • Changing order in which functions are called can cause failures
  26. Avoid Shared State Thread 1 Car Thread 2 getNoOfDrivers 5

    setNoOfDrivers(7) Does calculation based on assumption that Car has 5 drivers
  27. Avoid Shared State Thread 1 Car Thread 2 getNoOfDrivers 5

    Create car with NoOfDrivers (7) Does calculation based on assumption that Car has 5 drivers Thread 2 gets new copy of car Does stuff with Car of 7 drivers
  28. Explicitness fun divide(x: Int, y: Int) = x / y

    fun processData(data: String) { if (data.isNotEmpty()) { println("Good data") } else { throw Exception("Data is crap") } }
  29. Explicitness fun divide(x: Int, y: Int) = x / y

    fun processData(data: String) { if (data.isNotEmpty()) { println("Good data") } else { throw Exception("Data is crap") } } What about divide by 0? Function does not say it can throw an exception
  30. Explicitness fun divide(x: Int, y: Int) = x / y

    fun processData(data: String) { if (data.isNotEmpty()) { println("Good data") } else { throw Exception("Data is crap") } } What about divide by 0? Function does not say it can throw an exception These are LIES!
  31. Explicitness fun divide(x: Int, y: Int) = x / y

    fun divide(x: Int, y: Int): Option<Int> { return if (y > 0) { Option.just(x / y) } else { Option.empty() } }
  32. Explicitness sealed class Result { class Success(val value: String): Result()

    class Failure(val message: String): Result() } fun processData(data: String): Result { return if (data.isNotEmpty()) { Result.Success("Good Data") } else { Result.Failure("Crap Data") } }
  33. Explicitness - Arrow: Either Object CrapData fun processData(data: String): Either<String,

    NotApplicable> { return if (data.isNotEmpty()) { Either.Left(data) } else { Either.Right(CrapData) } }
  34. Explicitness - Arrow: Try fun processData(data: String): Try<String> { return

    Try { if (data.isNotEmpty()) { "Good data" } else { throw Exception("Data is crap") } } }
  35. Abstraction • Make code more concise and easier to understand

    • Abstract using functions • Hard to remember implementation details but we remember what a function does and we use them
  36. Abstraction fun itDoesSomething(elements: List<String>): HashMap<String, Int> { var i =

    0 val results = hashMapOf<String, Int>() while (i < elements.size) { val element = results[elements[i]] if (element != null) { results[elements[i]] = element + 1 } else { results[elements[i]] = 1 } i++ } return results }
  37. High Order Functions • In Functional Programming, functions are first

    class citizens • Functions that take functions as parameters and can return functions
  38. High Order Functions interface CompressionStrategy { fun compress(files: List<File>) }

    class ZipCompressionStrategy : CompressionStrategy { fun compress(files: List<File>) { // Do ZIP stuff } } class RarCompressionStrategy : CompressionStrategy { fun compress(files: List<File>) { // Do RAR stuff } }
  39. High Order Functions fun decideStrategy(strategy: Strategy): CompressionStrategy { when (strategy)

    { ZIP -> return ZipCompressionStrategy() RAR -> return RarCompressionStrategy() } }
  40. High Order Functions • A lot of ceremony • All

    we are trying to do is use a variable to choose a business logic
  41. High Order Functions fun compress(files: List<File>, applyStrategy: (List<File>) -> CompressedFiles)

    { applyStrategy(files) } // At call site compress(fileList, { files -> ZipCompression() } ) compress(fileList, { files -> RARCompression() } )
  42. Composition • Create small pieces of code (functions) that can

    be used in small building blocks to build bigger systems
  43. Composition fun isOdd(x: Int): Boolean = x % 2 !=

    0 fun length(s: String): Int = s.length fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C { return { x -> f(g(x)) } }
  44. Composition val oddLength = compose(::isOdd, ::length) val strings = listOf("a",

    "ab", "abc") println(strings.filter(oddLength)) // Output [a, abc]
  45. Where to Go From There? • Tip of the iceberg

    • Functors • Arrow Framework • Change of mindset when writing code • Practice! Practice! Practice!
  46. Resources and Inspirations • Category Theory in Life - Eugenia

    Cheng (This is where I got my examples for the Category Theory slides) https://www.youtube.com/watch?v=ho7oagHeqNc • Category Theory 1.1: Motivation and Philosophy - Bartosz Milewski (Very popular series on Category Theory) https://www.youtube.com/watch?v=I8LbkfSSR58 • Functional Programming with Kotlin - Hadi Hariri https://www.youtube.com/watch?v=eNe5Nokrjdg • Functional Programming for Android Developers - Part 1 (4 Parts series) https://medium.com/free-code-camp/functional-programming-for-android-developers-part-1-a58d40d6e742 • Functional Programming with Kotlin and Arrow: Getting Started - Massimo Carli (2 Parts series) https://www.raywenderlich.com/9527-functional-programming-with-kotlin-and-arrow-getting-started • Effective Kotlin - Marcin Moskala (I bought the pdf) https://leanpub.com/effectivekotlin • The Science Behind Functional Programming - Rafa Paradela https://www.47deg.com/blog/science-behind-functional-programming/