Functional Programming in Kotlin

Book description

Master techniques and concepts of functional programming to deliver safer, simpler, and more effective Kotlin code.

In Functional Programming in Kotlin you will learn:

  • Functional programming techniques for real-world applications
  • Write combinator libraries
  • Common structures and idioms in functional design
  • Simplicity and modularity (and fewer bugs!)

Functional Programming in Kotlin is a reworked version of the bestselling Functional Programming in Scala, with all code samples, instructions, and exercises translated into the powerful Kotlin language. In this authoritative guide, you’ll take on the challenge of learning functional programming from first principles. Complex concepts are demonstrated through exercises that you’ll love to test yourself against. You’ll start writing Kotlin code that’s easier to read, easier to reuse, better for concurrency, and less prone to bugs and errors.

About the Technology
Improve performance, increase maintainability, and eliminate bugs! How? By programming the functional way. Kotlin provides strong support for functional programming, taking a pragmatic approach that integrates well with OO codebases. By applying the techniques you’ll learn in this book, your code will be safer, less prone to errors, and much easier to read and reuse.

About the Book
Functional Programming in Kotlin teaches you how to design and write Kotlin applications using typed functional programming. Offering clear examples, carefully-presented explanations, and extensive exercises, it moves from basic subjects like types and data structures to advanced topics such as stream processing. This book is based on the bestseller Functional Programming in Scala by Rúnar Bjarnason and Paul Chiusano.

What's Inside
  • Functional programming techniques for real-world situations
  • Common structures and idioms in functional design
  • Simplicity, modularity, and fewer bugs!


About the Reader
For Kotlin developers. No functional programming experience required.

About the Authors
Marco Vermeulen has two decades of programming experience on the JVM.

Rúnar Bjarnason and Paul Chiusano are the authors of Functional Programming in Scala.

Quotes
The best book for any developer who is serious about leveling up their Kotlin skills!
- Gustavo Gomes, Troido

An elegant and rigorous introduction to functional programming.
- Marco Carnini, Features Analytics

A comprehensive guide that leverages Kotlin’s basic and more advanced functional programming capabilities!
- Jean-François Morin, Laval University

An excellent springboard for enabling Kotlin developers to embrace coding in the functional style.
- Garth Gilmour, Instil Software

A fantastic book if you want to finally understand what all the fuss about FP is about.
- Felipe Fernández Domínguez, Gradle

Table of contents

  1. Functional Programming with Kotlin
  2. Copyright
  3. contents
  4. front matter
    1. foreword
    2. preface
    3. acknowledgments
    4. about this book
      1. Who should read this book
      2. How this book is organized
      3. How to read this book
      4. About the code
      5. liveBook discussion forum
  5. Part 1. Introduction to functional programming
  6. 1 What is functional programming?
    1. 1.1 The benefits of FP: A simple example
      1. 1.1.1 A program with side effects
      2. 1.1.2 A functional solution: Removing the side effects
    2. 1.2 Exactly what is a (pure) function?
    3. 1.3 RT, purity, and the substitution model
    4. 1.4 What lies ahead
    5. Summary
  7. 2 Getting started with functional programming in Kotlin
    1. 2.1 Higher-order functions: Passing functions to functions
      1. 2.1.1 A short detour: Writing loops functionally
      2. 2.1.2 Writing our first higher-order function
    2. 2.2 Polymorphic functions: Abstracting over types
      1. 2.2.1 An example of a polymorphic function
      2. 2.2.2 Calling HOFs with anonymous functions
    3. 2.3 Following types to implementations
    4. Summary
  8. 3 Functional data structures
    1. 3.1 Defining functional data structures
    2. 3.2 Working with functional data structures
      1. 3.2.1 The “when” construct for matching by type
      2. 3.2.2 The when construct as an alternative to if-else logic
      3. 3.2.3 Pattern matching and how it differs from Kotlin matching
    3. 3.3 Data sharing in functional data structures
      1. 3.3.1 The efficiency of data sharing
    4. 3.4 Recursion over lists and generalizing to HOFs
      1. 3.4.1 More functions for working with lists
      2. 3.4.2 Lists in the Kotlin standard library
      3. 3.4.3 Inefficiency of assembling list functions from simpler components
    5. 3.5 Trees
    6. Summary
  9. 4 Handling errors without exceptions
    1. 4.1 The problems with throwing exceptions
    2. 4.2 Problematic alternatives to exceptions
      1. 4.2.1 Sentinel value
      2. 4.2.2 Supplied default value
    3. 4.3 Encoding success conditions with Option
      1. 4.3.1 Usage patterns for Option
      2. 4.3.2 Option composition, lifting, and wrapping exception-oriented APIs
      3. 4.3.3 For-comprehensions with Option
    4. 4.4 Encoding success and failure conditions with Either
      1. 4.4.1 For-comprehensions with Either
    5. Summary
  10. 5 Strictness and laziness
    1. 5.1 Strict and non-strict functions
    2. 5.2 An extended example: Lazy lists
      1. 5.2.1 Memoizing streams and avoiding recomputation
      2. 5.2.2 Helper functions for inspecting streams
    3. 5.3 Separating program description from evaluation
    4. 5.4 Producing infinite data streams through corecursive functions
    5. 5.5 Conclusion
    6. Summary
  11. 6 Purely functional state
    1. 6.1 Generating random numbers using side effects
    2. 6.2 Purely functional random number generation
    3. 6.3 Making stateful APIs pure
    4. 6.4 An implicit approach to passing state actions
      1. 6.4.1 More power by combining state actions
      2. 6.4.2 Recursive retries through nested state actions
      3. 6.4.3 Applying the combinator API to the initial example
    5. 6.5 A general state action data type
    6. 6.6 Purely functional imperative programming
    7. 6.7 Conclusion
    8. Summary
  12. Part 2. Functional design and combinator libraries
  13. 7 Purely functional parallelism
    1. 7.1 Choosing data types and functions
      1. 7.1.1 A data type for parallel computations
      2. 7.1.2 Combining parallel computations to ensure concurrency
      3. 7.1.3 Marking computations to be forked explicitly
    2. 7.2 Picking a representation
    3. 7.3 Refining the API with the end user in mind
    4. 7.4 Reasoning about the API in terms of algebraic equations
      1. 7.4.1 The law of mapping
      2. 7.4.2 The law of forking
      3. 7.4.3 Using actors for a non-blocking implementation
    5. 7.5 Refining combinators to their most general form
    6. Summary
  14. 8 Property-based testing
    1. 8.1 A brief tour of property-based testing
    2. 8.2 Choosing data types and functions
      1. 8.2.1 Gathering initial snippets for a possible API
      2. 8.2.2 Exploring the meaning and API of properties
      3. 8.2.3 Discovering the meaning and API of generators
      4. 8.2.4 Generators that depend on generated values
      5. 8.2.5 Refining the property data type
    3. 8.3 Test case minimization
    4. 8.4 Using the library and improving the user experience
      1. 8.4.1 Some simple examples
      2. 8.4.2 Writing a test suite for parallel computations
    5. 8.5 Generating higher-order functions and other possibilities
    6. 8.6 The laws of generators
    7. 8.7 Conclusion
    8. Summary
  15. 9 Parser combinators
    1. 9.1 Designing an algebra
      1. 9.1.1 A parser to recognize single characters
      2. 9.1.2 A parser to recognize entire strings
      3. 9.1.3 A parser to recognize repetition
    2. 9.2 One possible approach to designing an algebra
      1. 9.2.1 Counting character repetition
      2. 9.2.2 Slicing and nonempty repetition
    3. 9.3 Handling context sensitivity
    4. 9.4 Writing a JSON parser
      1. 9.4.1 Defining expectations of a JSON parser
      2. 9.4.2 Reviewing the JSON format
      3. 9.4.3 A JSON parser
    5. 9.5 Surfacing errors through reporting
      1. 9.5.1 First attempt at representing errors
      2. 9.5.2 Accumulating errors through error nesting
      3. 9.5.3 Controlling branching and backtracking
    6. 9.6 Implementing the algebra
      1. 9.6.1 Building up the algebra implementation gradually
      2. 9.6.2 Sequencing parsers after each other
      3. 9.6.3 Capturing error messages through labeling parsers
      4. 9.6.4 Recovering from error conditions and backtracking over them
      5. 9.6.5 Propagating state through context-sensitive parsers
    7. 9.7 Conclusion
    8. Summary
  16. Part 3. Common structures in functional design
  17. 10 Monoids
    1. 10.1 What is a monoid?
    2. 10.2 Folding lists with monoids
    3. 10.3 Associativity and parallelism
    4. 10.4 Example: Parallel parsing
    5. 10.5 Foldable data structures
    6. 10.6 Composing monoids
      1. 10.6.1 Assembling more complex monoids
      2. 10.6.2 Using composed monoids to fuse traversals
    7. Summary
  18. 11 Monads and functors
    1. 11.1 Functors
      1. 11.1.1 Defining the functor by generalizing the map function
      2. 11.1.2 The importance of laws and their relation to the functor
    2. 11.2 Monads: Generalizing the flatMap and unit functions
      1. 11.2.1 Introducing the Monad interface
    3. 11.3 Monadic combinators
    4. 11.4 Monad laws
      1. 11.4.1 The associative law
      2. 11.4.2 Proving the associative law for a specific monad
      3. 11.4.3 The left and right identity laws
    5. 11.5 Just what is a monad?
      1. 11.5.1 The identity monad
      2. 11.5.2 The State monad and partial type application
    6. Summary
  19. 12 Applicative and traversable functors
    1. 12.1 Generalizing monads for reusability
    2. 12.2 Applicatives as an alternative abstraction to the monad
    3. 12.3 The difference between monads and applicative functors
      1. 12.3.1 The Option applicative vs. the Option monad
      2. 12.3.2 The Parser applicative vs. the Parser monad
    4. 12.4 The advantages of applicative functors
      1. 12.4.1 Not all applicative functors are monads
    5. 12.5 Reasoning about programs through the applicative laws
      1. 12.5.1 Laws of left and right identity
      2. 12.5.2 Law of associativity
      3. 12.5.3 Law of naturality
    6. 12.6 Abstracting traverse and sequence using traversable functors
    7. 12.7 Using Traversable to iteratively transform higher kinds
      1. 12.7.1 From monoids to applicative functors
      2. 12.7.2 Traversing collections while propagating state actions
      3. 12.7.3 Combining traversable structures
      4. 12.7.4 Traversal fusion for single pass efficiency
      5. 12.7.5 Simultaneous traversal of nested traversable structures
      6. 12.7.6 Pitfalls and workarounds for monad composition
    8. Summary
  20. Part 4. Effects and I/O
  21. 13 External effects and I/O
    1. 13.1 Factoring effects out of an effectful program
    2. 13.2 Introducing the IO type to separate effectful code
      1. 13.2.1 Handling input effects
      2. 13.2.2 Benefits and drawbacks of the simple IO type
    3. 13.3 Avoiding stack overflow errors by reification and trampolining
      1. 13.3.1 Reifying control flow as data constructors
      2. 13.3.2 Trampolining: A general solution to stack overflow
    4. 13.4 A more nuanced IO type
      1. 13.4.1 Reasonably priced monads
      2. 13.4.2 A monad that supports only console I/O
      3. 13.4.3 Testing console I/O by using pure interpreters
    5. 13.5 Non-blocking and asynchronous I/O
    6. 13.6 A general-purpose IO type
      1. 13.6.1 The main program at the end of the universe
    7. 13.7 Why the IO type is insufficient for streaming I/O
    8. Summary
  22. 14 Local effects and mutable state
    1. 14.1 State mutation is legal in pure functional code
    2. 14.2 A data type to enforce scoping of side effects
      1. 14.2.1 A domain-specific language for scoped mutation
      2. 14.2.2 An algebra of mutable references
      3. 14.2.3 Running mutable state actions
      4. 14.2.4 The mutable array represented as a data type for the ST monad
      5. 14.2.5 A purely functional in-place quicksort
    3. 14.3 Purity is contextual
      1. 14.3.1 Definition by example
      2. 14.3.2 What counts as a side effect?
    4. Summary
  23. 15 Stream processing and incremental I/O
    1. 15.1 Problems with imperative I/O: An example
    2. 15.2 Transforming streams with simple transducers
      1. 15.2.1 Combinators for building stream transducers
      2. 15.2.2 Combining multiple transducers by appending and composing
      3. 15.2.3 Stream transducers for file processing
    3. 15.3 An extensible process type for protocol parameterization
      1. 15.3.1 Sources for stream emission
      2. 15.3.2 Ensuring resource safety in stream transducers
      3. 15.3.3 Applying transducers to a single-input stream
      4. 15.3.4 Multiple input streams
      5. 15.3.5 Sinks for output processing
      6. 15.3.6 Hiding effects in effectful channels
      7. 15.3.7 Dynamic resource allocation
    4. 15.4 Application of stream transducers in the real world
    5. Summary
    6. Final words
  24. Appendix A. Exercise hints and tips
    1. A.1 Chapter 3: Functional data structures
      1. Exercise 3.1
      2. Exercise 3.2
      3. Exercise 3.3
      4. Exercise 3.4
      5. Exercise 3.5
      6. Exercise 3.6
      7. Exercise 3.7
      8. Exercise 3.12
      9. Exercise 3.14
      10. Exercise 3.15
      11. Exercise 3.16
      12. Exercise 3.17
      13. Exercise 3.18
      14. Exercise 3.19
      15. Exercise 3.23
      16. Exercise 3.28
    2. A.2 Chapter 4: Handling errors without exceptions
      1. Exercise 4.3
      2. Exercise 4.4
      3. Exercise 4.5
      4. Exercise 4.6
      5. Exercise 4.7
      6. Exercise 4.8
    3. A.3 Chapter 5: Strictness and laziness
      1. Exercise 5.1
      2. Exercise 5.2
      3. Exercise 5.4
      4. Exercise 5.6
      5. Exercise 5.9
      6. Exercise 5.10
      7. Exercise 5.11
      8. Exercise 5.14
      9. Exercise 5.15
      10. Exercise 5.16
    4. A.4 Chapter 6: Purely functional state
      1. Exercise 6.2
      2. Exercise 6.5
      3. Exercise 6.6
      4. Exercise 6.7
      5. Exercise 6.8
      6. Exercise 6.9
      7. Exercise 6.10
    5. A.5 Chapter 7: Purely functional parallelism
      1. Exercise 7.1
      2. Exercise 7.2
      3. Exercise 7.3
      4. Exercise 7.5
      5. Exercise 7.7
    6. A.6 Chapter 8: Property-based testing
      1. Exercise 8.4
      2. Exercise 8.5
      3. Exercise 8.6
      4. Exercise 8.9
      5. Exercise 8.12
      6. Exercise 8.13
      7. Exercise 8.16
    7. A.7 Chapter 9: Parser combinators
      1. Exercise 9.1
      2. Exercise 9.2
      3. Exercise 9.7
      4. Exercise 9.9
      5. Exercise 9.10
      6. Exercise 9.12
    8. A.8 Chapter 10: Monoids
      1. Exercise 10.2
      2. Exercise 10.3
      3. Exercise 10.4
      4. Exercise 10.5
      5. Exercise 10.6
      6. Exercise 10.7
      7. Exercise 10.8
      8. Exercise 10.9
      9. Exercise 10.13
      10. Exercise 10.19
    9. A.9 Chapter 11: Monads and functors
      1. Exercise 11.1
      2. Exercise 11.2
      3. Exercise 11.3
      4. Exercise 11.4
      5. Exercise 11.6
      6. Exercise 11.7
      7. Exercise 11.8
      8. Exercise 11.9
      9. Exercise 11.10
      10. Exercise 11.13
      11. Exercise 11.16
      12. Exercise 11.18
      13. Exercise 11.19
    10. A.10 Chapter 12: Applicative and traversable functors
      1. Exercise 12.2
      2. Exercise 12.3
      3. Exercise 12.5
      4. Exercise 12.6
      5. Exercise 12.7
      6. Exercise 12.8
      7. Exercise 12.9
      8. Exercise 12.10
      9. Exercise 12.11
      10. Exercise 12.12
      11. Exercise 12.13
      12. Exercise 12.15
      13. Exercise 12.16
      14. Exercise 12.17
      15. Exercise 12.18
      16. Exercise 12.19
    11. A.11 Chapter 13: External effects and I/O
      1. Exercise 13.1
      2. Exercise 13.2
      3. Exercise 13.4
    12. A.12 Chapter 14: Local effects and mutable state
      1. Exercise 14.1
      2. Exercise 14.2
      3. Exercise 14.3
    13. A.13 Chapter 15: Stream processing and incremental I/O
      1. Exercise 15.3
      2. Exercise 15.5
      3. Exercise 15.6
      4. Exercise 15.7
      5. Exercise 15.9
      6. Exercise 15.10
      7. Exercise 15.11
      8. Exercise 15.12
  25. Appendix B. Exercise solutions
    1. B.1 Before you proceed to the solutions
    2. B.2 Getting started with functional programming
      1. Exercise 2.1
      2. Exercise 2.2
      3. Exercise 2.3
      4. Exercise 2.4
      5. Exercise 2.5
    3. B.3 Functional data structures
      1. Exercise 3.1
      2. Exercise 3.2
      3. Exercise 3.3
      4. Exercise 3.4
      5. Exercise 3.5
      6. Exercise 3.6
      7. Exercise 3.7
      8. Exercise 3.8
      9. Exercise 3.9
      10. Exercise 3.10
      11. Exercise 3.11
      12. Exercise 3.12 (Hard)
      13. Exercise 3.13
      14. Exercise 3.14 (Hard)
      15. Exercise 3.15
      16. Exercise 3.16
      17. Exercise 3.17
      18. Exercise 3.18
      19. Exercise 3.19
      20. Exercise 3.20
      21. Exercise 3.21
      22. Exercise 3.22
      23. Exercise 3.23
      24. Exercise 3.24
      25. Exercise 3.25
      26. Exercise 3.26
      27. Exercise 3.27
      28. Exercise 3.28
    4. B.4 Handling errors without exceptions
      1. Exercise 4.1
      2. Exercise 4.2
      3. Exercise 4.3
      4. Exercise 4.4
      5. Exercise 4.5
      6. Exercise 4.6
      7. Exercise 4.7
      8. Exercise 4.8
    5. B.5 Strictness and laziness
      1. Exercise 5.1
      2. Exercise 5.2
      3. Exercise 5.3
      4. Exercise 5.4
      5. Exercise 5.5
      6. Exercise 5.6 (Hard)
      7. Exercise 5.7
      8. Exercise 5.8
      9. Exercise 5.9
      10. Exercise 5.10
      11. Exercise 5.11
      12. Exercise 5.12
      13. Exercise 5.13
      14. Exercise 5.14 (Hard)
      15. Exercise 5.15
      16. Exercise 5.16 (Hard)
    6. B.6 Purely functional state
      1. Exercise 6.1
      2. Exercise 6.2
      3. Exercise 6.3
      4. Exercise 6.4
      5. Exercise 6.5
      6. Exercise 6.6
      7. Exercise 6.7
      8. Exercise 6.8
      9. Exercise 6.9
      10. Exercise 6.10
      11. Exercise 6.11
    7. B.7 Purely functional parallelism
      1. Exercise 7.1
      2. Exercise 7.2
      3. Exercise 7.3
      4. Exercise 7.4
      5. Exercise 7.5
      6. Exercise 7.6
      7. Exercise 7.7 (Hard)
      8. Exercise 7.8 (Hard)
      9. Exercise 7.9 (Hard/Optional)
      10. Exercise 7.10
      11. Exercise 7.11
      12. Exercise 7.12
      13. Exercise 7.13
    8. B.8 Property-based testing
      1. Exercise 8.1
      2. Exercise 8.2
      3. Exercise 8.3
      4. Exercise 8.4
      5. Exercise 8.5
      6. Exercise 8.6
      7. Exercise 8.7
      8. Exercise 8.8
      9. Exercise 8.9
      10. Exercise 8.10
      11. Exercise 8.11
      12. Exercise 8.12
      13. Exercise 8.13
      14. Exercise 8.14
      15. Exercise 8.15
      16. Exercise 8.16
      17. Exercise 8.17
    9. B.9 Parser combinators
      1. Exercise 9.1
      2. Exercise 9.2 (Hard)
      3. Exercise 9.3
      4. Exercise 9.4
      5. Exercise 9.5
      6. Exercise 9.6
      7. Exercise 9.7
      8. Exercise 9.8
      9. Exercise 9.9 (Hard)
      10. Exercise 9.10
      11. Exercise 9.11
      12. Exercise 9.12
      13. Exercise 9.13
      14. Exercise 9.14
    10. B.10 Monoids
      1. Exercise 10.1
      2. Exercise 10.2
      3. Exercise 10.3
      4. Exercise 10.4
      5. Exercise 10.5
      6. Exercise 10.6
      7. Exercise 10.7
      8. Exercise 10.8 (Hard/Optional)
      9. Exercise 10.9 (Hard/Optional)
      10. Exercise 10.10
      11. Exercise 10.11
      12. Exercise 10.12
      13. Exercise 10.13
      14. Exercise 10.14
      15. Exercise 10.15
      16. Exercise 10.16
      17. Exercise 10.17
      18. Exercise 10.18
      19. Exercise 10.19
    11. B.11 Monads and functors
      1. Exercise 11.1
      2. Exercise 11.2
      3. Exercise 11.3
      4. Exercise 11.4
      5. Exercise 11.5
      6. Exercise 11.6 (Hard)
      7. Exercise 11.7
      8. Exercise 11.8 (Hard)
      9. Exercise 11.9
      10. Exercise 11.10
      11. Exercise 11.11
      12. Exercise 11.12
      13. Exercise 11.13 (Hard/Optional)
      14. Exercise 11.14 (Hard/Optional)
      15. Exercise 11.15 (Hard/Optional)
      16. Exercise 11.16
      17. Exercise 11.17
      18. Exercise 11.18
      19. Exercise 11.19 (Hard)
    12. B.12 Applicative and traversable functors
      1. Exercise 12.1
      2. Exercise 12.2 (Hard)
      3. Exercise 12.3
      4. Exercise 12.4
      5. Exercise 12.5
      6. Exercise 12.6
      7. Exercise 12.7 (Hard)
      8. Exercise 12.8
      9. Exercise 12.9
      10. Exercise 12.10
      11. Exercise 12.11
      12. Exercise 12.12 (Hard)
      13. Exercise 12.13 (Hard)
      14. Exercise 12.14
      15. Exercise 12.15
      16. Exercise 12.16
      17. Exercise 12.17
      18. Exercise 12.18 (Hard)
      19. Exercise 12.19 (Hard/Optional)
    13. B.13 External effects and I/O
      1. Exercise 13.1
      2. Exercise 13.2
      3. Exercise 13.3 (Hard)
      4. Exercise 13.4 (Hard/Optional)
    14. B.14 Local effects and mutable state
      1. Exercise 14.1
      2. Exercise 14.2
      3. Exercise 14.3
    15. B.15 Stream processing and incremental I/O
      1. Exercise 15.1
      2. Exercise 15.2
      3. Exercise 15.3
      4. Exercise 15.4
      5. Exercise 15.5 (Hard)
      6. Exercise 15.6
      7. Exercise 15.7 (Optional)
      8. Exercise 15.8
      9. Exercise 15.9 (Optional)
      10. Exercise 15.10
      11. Exercise 15.11
      12. Exercise 15.12
  26. Appendix C. Higher-kinded types
    1. C.1 A compiler workaround
    2. C.2 Partially applied type constructors
    3. C.3 Boilerplate code generation with Arrow Meta
  27. Appendix D. Type classes
    1. D.1 Polymorphism
    2. D.2 Using type classes to express ad hoc polymorphism
    3. D.3 Type classes foster a separation of concerns
  28. index

Product information

  • Title: Functional Programming in Kotlin
  • Author(s): Runar Bjarnason, Paul Chiusano, Marco Vermeulen
  • Release date: September 2021
  • Publisher(s): Manning Publications
  • ISBN: 9781617297168