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

Functional Programming in Kotlin using Arrow

Functional Programming in Kotlin using Arrow

6289244df2b7ed2e27ff5dfdd93f058a?s=128

Monika Kumar Jethani

October 13, 2018
Tweet

More Decks by Monika Kumar Jethani

Other Decks in Programming

Transcript

  1. Leveraging the power of Arrow to build Android(Kotlin) apps using

    Functional Programming MONIKA KUMAR JETHANI
  2. About Me

  3. Agenda 1- Overview of Functional Programming 2- Functional Constructs of

    Kotlin 3- Introduction to Arrow 4- Deep dive into Arrow Data Types: Option, Either, Try 5- Deep dive into Arrow Type Classes: Functor, Monad, Applicative 6- More FP Concepts 7- Sample Apps
  4. What is Functional Programming??? Functional Programming is a programming paradigm—a

    style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”. Source: Wikipedia
  5. Defining a Pure Function Input Output F Characteristics of a

    Pure function: 1- Provides the same output for the same input at all times. 2- Works only on the parameters supplied to it, doesn’t modify anything outside function.
  6. Advantages of Functional Programming over OOP  Brevity  Modularization

    of code  Easier to test  Code becomes predictable  Encourages safe programming by providing constructs such as immutability and pure functions.
  7. Functional Programming Languages  Any Language that treats functions as

    first class citizens.  Functions can be passed to other functions, returned from other functions and functions can be assigned to a variable.  Examples: Scala, Haskell, Kotlin.
  8. Functional Constructs of Kotlin  Immutability  Higher-Order Functions 

    Lambdas  Lazy Evaluation  Tail Call Recursion  Extension Functions  Null Safety  Pattern Matching
  9. Limitations of Kotlin w.r.t. FP  Doesn’t support typed functional

    programming.  Doesn’t enforce FP.
  10. Arrow  Functional Companion to Kotlin’s standard library.  Library

    that provides Typed Functional Programming in Kotlin.  Introduced in 2017.  Fusion of 2 most popular Kotlin libraries: Kategory and funcKTionale.  Documentation available at : https://arrow-kt.io/  Latest release: 0.7.3
  11. Data Types  Option  Either  Try

  12. Option Option<A> is a container for an optional value of

    type A. If the value of type A is present, the Option<A> is an instance of Some<A>, containing the present value of type A. If the value is absent, the Option<A> is the object None.
  13. More to Option

  14. Option with getOrElse getOrElse() allow us to provide default value

    if None.
  15. Use case for Option  A Registration form filled by

    users where entities like Name, Date-of-Birth are optional. Searching the user by name, would results in a type Optional.  Can also be used in when clause of Kotlin.
  16. Either  As its name implies, Either uses either of

    the two values.  By convention, right hand side of Either holds successful values and the left side holds the exceptional case.
  17. More on Either

  18. Extraction of values of Either

  19. Using getOrElse with Either getOrElse allows us to provide a

    default value for the left-side.
  20. Use case for Either Displaying Validation Messages: A form contains

    valid patterns for email, phone, name. The input entered by the user can be either valid or invalid.
  21. Try  Try checks if a particular value exists and

    then routes towards success or failure.  A Try instance where the operation has been successful, which is represented as Success<A>  a Try instance where the computation has failed is represented with a Throwable, which represents Failure.
  22. Extracting value of Try We can extract Try inner values

    using ‘when’ clause.
  23. Using recover Recover allows us to handle the exception if

    it’s a Failure.
  24. Use case for Try Catching exceptions- User pass two values

    to the function for divide. Either the function would return the result or throw an exception.
  25. Type Classes  Functor  Monad  Applicative

  26. Functor Allow us to apply a function to a wrapped

    value using map. Here, ‘f’ is a function transforming the wrapped value. And map() returns the transformed value wrapped in same context. Present at: Arrow.typeclasses.Functor
  27. How Functor works? fmap :: (a -> b) -> f(a)

    -> f(b) fmap takes a Function And a Functor And returns a new Functor
  28. How Functor works? Continued… 2 (+3) 2 5 5 Unwrap

    value from Context. Apply Function. Rewrap value in Context. No value. (+3) Don’t apply function. End up with Nothing.
  29. Functor applied to Array (+3) (+3) (+3) 2 4 6

    5 7 9 Apply the function to each value.
  30. Functor applied to a function Source: https://hackernoon.com/kotlin-functors- applicatives-and-monads-in-pictures-part-1-3- c47a1b1ce251

  31. Polymorphism with Functor

  32. Applicative Allow you to apply a wrapped function to a

    wrapped value using apply.
  33. How Applicative works? (+3) <*> 2 5 Function wrapped in

    a Context Value in a Context (+3) 2 Unwrap both and apply the function to the value New value in a context
  34. Applying Applicative to an array of values Source: https://hackernoon.com/kotlin-functors-applicatives-and- monads-in-pictures-part-2-3-f99a09efd1ec

  35. Applicative Builder Preserves Type Information when computing over different Option

    types. Callback is invoked when all values are completed, if all values are Some.
  36. Monads Monads apply a wrapped value to a function that

    returns a wrapped value using flatMap.
  37. How does Monad work? (>>=) :: ma -> (a ->

    mb) -> mb >>= takes a Monad And a function that returns a Monad And it returns a Monad
  38. Monad Chaining

  39. Monad Binding

  40. An interesting relation Functor Applicative Monad

  41. More Functional Programming Concepts  Function composition  Memoization 

    Pipes  Logical Complement
  42. Function Composition  Process of building a function using existing

    functions.  Compose is an infix function.  Compose takes the value from the function on the right, applies it to the function on the left and continues to pass it to the left.
  43. Piping  Reverse of ‘compose’.  Takes a value from

    the function on the left and sequentially applies it to the function on the right.
  44. Logical Component  Takes any function that returns a Boolean

    type and negates it.
  45. Memoization  A technique to cache results of pure functions.

     A function that is memorized behaves as a normal function, but stores the result of previous computations associated with the parameters supplied to produce that result.
  46. Integration of Arrow with Android Studio project Add dependencies

  47. Calculator app using Arrows FP constructs

  48. Calculator app using Arrows FP constructs

  49. Modelling division as Try When Divisor is zero When Divisor

    is non-zero
  50. Form validation using Arrow

  51. Modelling data with Option When no input is provided When

    input is provided
  52. Best practices when using Arrow for Android  Push side

    effects to a single point on your system to keep the rest of the architecture completely pure.  Be clear on the concepts of different data types and their differences.  Be clear on the concepts of different type classes and incorporate them in your computations accordingly.
  53. Projects using Arrow  raulh82vlc/FunctionalKotlin  dcampogiani/AndroidFunctionalValidation  47deg/helios You

    can check the projects that are being done/have being done using Arrow here: https://arrow-kt.io/docs/quickstart/projects/
  54. Are you READY to try out Arrow? THANK YOU For

    queries, please reach out to me at monikakj23@gmail.com