This document provides a study aid to help learn and recall the implementation and interrelation of the monadic functions Kleisli composition, flatMap, join, map, and unit. It presents different ways of implementing these functions for the Option and List monads, including hand-coding Kleisli composition, defining it generically in terms of flatMap, and defining it in terms of map and join. The goal is to reinforce understanding of these core monadic concepts and how they work together.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala
The document discusses functor composition and the functor laws. It explains that the composition of two functors F and G is itself a functor, where the map operation maps a function f by first applying F's map to lift f into F, and then applying G's map to lift the result into G. This satisfies the functor laws, where the mapping of a composition of functions is the composition of their individual mappings.
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Philip Schwarz
The document discusses symmetries between flatMap, foldMap, traverse, flatten, fold, and sequence. Specifically:
- flatMapping is mapping and then flattening. Flattening is just flatMapping with the identity function.
- Traversing is mapping and then sequencing. Sequencing is just traversing with the identity function.
- foldMapping is mapping and then folding. Folding is just foldMapping with the identity function.
The document also notes that while foldMap can often be defined in terms of map for Foldable types, it is not always possible, but Traverse's foldMap can always be defined in terms of map.
download for better quality - Learn about the sequence and traverse functions through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and Sam Halliday, author of "Functional Programming for Mortals with Scalaz" https://leanpub.com/fpmortals
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
The document discusses monoids in Scalaz and Cats, specifically for the Option type. It explains that in Scalaz there are three Option monoids (optionFirst, optionLast, optionMonoid) that combine Options in different ways, while Cats only has one Option monoid (optionMonoid) that combines the contents. It also introduces MonoidK, which allows constructing a monoid that behaves like optionFirst by combining Options based on their orElse method. The document provides examples and explanations of how Semigroup, SemigroupK, Monoid, and MonoidK work and differ for types like List, Set, and Option. It also defines a monoid for endofunctions that composes
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala
The document discusses functor composition and the functor laws. It explains that the composition of two functors F and G is itself a functor, where the map operation maps a function f by first applying F's map to lift f into F, and then applying G's map to lift the result into G. This satisfies the functor laws, where the mapping of a composition of functions is the composition of their individual mappings.
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Philip Schwarz
The document discusses symmetries between flatMap, foldMap, traverse, flatten, fold, and sequence. Specifically:
- flatMapping is mapping and then flattening. Flattening is just flatMapping with the identity function.
- Traversing is mapping and then sequencing. Sequencing is just traversing with the identity function.
- foldMapping is mapping and then folding. Folding is just foldMapping with the identity function.
The document also notes that while foldMap can often be defined in terms of map for Foldable types, it is not always possible, but Traverse's foldMap can always be defined in terms of map.
download for better quality - Learn about the sequence and traverse functions through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and Sam Halliday, author of "Functional Programming for Mortals with Scalaz" https://leanpub.com/fpmortals
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
The document discusses monoids in Scalaz and Cats, specifically for the Option type. It explains that in Scalaz there are three Option monoids (optionFirst, optionLast, optionMonoid) that combine Options in different ways, while Cats only has one Option monoid (optionMonoid) that combines the contents. It also introduces MonoidK, which allows constructing a monoid that behaves like optionFirst by combining Options based on their orElse method. The document provides examples and explanations of how Semigroup, SemigroupK, Monoid, and MonoidK work and differ for types like List, Set, and Option. It also defines a monoid for endofunctions that composes
What would be a good answer to the question of what functors are? To help formulating a reasonably well rounded answer, I have made some slides capturing what I considere particularly useful aspects of the following sources’ exposition of the concept of Functor:
* Bartosz Milewski’s Scala eXchange 2017 Keynote, The Maths Behind Types
*Paul Chiusano and Runar Bjarnason’s book, Functional Programming in Scala
* Debasish Ghosh’s book - Functional and Reactive Domain Modeling
* Christopher Allen, and Julie Moronuki's book - Haskell Programming from First Principles
Scala collection methods flatMap and flatten are more powerful than monadic f...Philip Schwarz
The flatten and flatMap methods of Scala's monad instances do not support mixing of collection types, such as flattening a List of Sets. However, the native flatten and flatMap methods of Scala collections like List, Vector, and Set do support mixing types. They are implemented using traversals, builders, and implicit CanBuildFrom builder factories that can build collections with heterogeneous element types. When flattening or flatMapping a collection, the appropriate CanBuildFrom is used to get a builder that adds elements of the nested collection to the output collection being built.
The document discusses Arrow, a generalization of functions in Scala. Arrows can represent computations with multiple inputs through tuples. The document defines Arrow traits and shows examples of Arrow combinators like first, second, split, and combine. It also compares Arrows to Applicatives and Monads. Arrows provide building blocks for functional reactive programming but have clumsy syntax. The document further discusses Arrow extensions like ArrowChoice and ArrowLoop, which enables feedback loops through lazy evaluation. It concludes with Comonads, which consume context, and MonadFix, which enables stackless recursion.
The document discusses Applicative Functors, Monads, Foldables and Traversables in Scala. Some key points:
1. Applicative Functors allow applying functions to values inside data structures in a point-free style, while preserving the structure.
2. Monads are more powerful than Applicative Functors as they can flatten nested structures and change behavior through chaining of functions.
3. Foldables allow aggregating values inside a data structure using a Monoid. Traversables generalize Foldables by keeping the structure intact using an Applicative instead of a Monoid.
4. Composition of Applicative Functors is possible generically, but composition of
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and others (Martin Odersky, Derek Wyatt, Adelbert Chang)
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
Inspired by Runar Bjarnason's scala exchange 2017 keynote https://skillsmatter.com/skillscasts/10746-keynote-composing-programs, I made a slide deck on Functor laws. Download for better quality.
Download for flawless quality (slides viewed online look a bit grainy and out of focus).
Equivalence of nested flatMaps and chained flatMaps for Kleisli arrow composition.
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
The document defines an IO monad for representing computations with side effects in Scala. The IO trait defines map and flatMap methods to allow sequencing of effectful computations. Functions like ReadLine and PrintLine are defined to interact with the console. A temperature conversion program is implemented using the IO monad, separating the pure computation from executing side effects.
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
A monoid is an algebraic structure consisting of a set and a binary operation that is associative and has an identity element. Some key properties of monoids include:
1) A monoid consists of a type A, a binary operation op that combines two values of type A, and a zero value that acts as an identity.
2) The binary operation must be associative, meaning op(op(x,y),z) = op(x,op(y,z)).
3) The zero value must satisfy the identity laws: op(x, zero) = x and op(zero, x) = x.
4) Common examples of monoids include string concatenation
Download for flawless quality (slides viewed online look a bit grainy and out of focus). A monad is an implementation of one of the minimal sets of monadic combinators, satisfying the laws of associativity and identity - see how compositional responsibilities are distributed in each combinator set
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
Scala 3 enum for a terser Option Monad Algebraic Data TypePhilip Schwarz
(download for flawless slides)
* Explore a terser definition of the Option Monad that uses a Scala 3 enum as an Algebraic Data Type.
* In the process, have a tiny bit of fun with Scala 3 enums.
* Get a refresher on the Functor and Monad laws.
* See how easy it is to use Scala 3 extension methods, e.g. to add convenience methods and infix operators.
The diagrams for function composition and Kleisli composition were made using https://q.uiver.app/ by https://twitter.com/varkora.
Source code: https://github.com/philipschwarz/scala-3-enum-for-terser-option-monad-algebraic-data-type
Errata:
slide 14 is an unwanted leftover - it is the same as slide 15 minus a diagram.
on slide 19, the colons in the extension method declarations are not needed
This presentation takes you on a functional programming journey, it starts from basic Scala programming language design concepts and leads to a concept of Monads, how some of them designed in Scala and what is the purpose of them
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaPhilip Schwarz
See a program structure flowchart used to highlight how an FP program breaks down into a functional core and imperative shell
View a program structure flowchart for the Game of Life
See the code for Game of Life’s functional core and imperative shell, both in Haskell and in Scala.
Code:
https://github.com/philipschwarz/functional-core-imperative-shell-scala
https://github.com/philipschwarz/functional-core-imperative-shell-haskell
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...Philip Schwarz
Learn how to write FP code that displays a graphical representation of all the numerous N-Queens solutions for N=4,5,6,7,8 .
See how to neatly solve the problem by exploiting its self-similarity and using a divide and conquer approach.
Make light work of assembling multiple images into a whole, by exploiting Doodle’s facilities for combining images using a relative layout.
See relevant FP functions, like Foldable’s intercalate and intersperse, in action.
Code for part 3: https://github.com/philipschwarz/n-queens-combinatorial-problem-scala-part-3
Here I link up up some very useful material by Robert Norris (@tpolecat) and Martin Odersky (@odersky) to introduce Monad laws and reinforce the importance of checking the laws. E.g. while Option satisfies the laws, Try is not a lawful Monad: it trades the left identity law for the bullet-proof principle.
* ERRATA *
1) on the first slide the Kleisli composition signature appears three times, but one of the occurrences is incorrect in that it is (>=>)::(a->mb)->(b->mb)->(a->mc) whereas is should be (>=>)::(a->mb)->(b->mc)->(a->mc) - thank you Jules Ivanic.
The document discusses functional programming concepts like monads, functors, and for comprehensions in Scala. It provides definitions and laws for functors, monads, and monadic operations like map, flatMap, filter. It shows the equivalence between for comprehensions and flatMap/map implementations. It also discusses monadic zeros and filtering laws. Key concepts covered include the functor laws, monad laws, equivalence between map/flatMap and for comprehensions, and laws for operations like filter.
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Philip Schwarz
Kleisli composition, flatMap, join, map, unit. A study/memory aid, to help learn/recall their implementation/interrelation.
Version 2, updated for Scala 3
AdRoll Tech Talk Presentation:
In this talk I present three approaches to understanding monads:
- How Monads Arise Naturally
- Monads as Implemented in Haskell
- Monads in Category Theory
What would be a good answer to the question of what functors are? To help formulating a reasonably well rounded answer, I have made some slides capturing what I considere particularly useful aspects of the following sources’ exposition of the concept of Functor:
* Bartosz Milewski’s Scala eXchange 2017 Keynote, The Maths Behind Types
*Paul Chiusano and Runar Bjarnason’s book, Functional Programming in Scala
* Debasish Ghosh’s book - Functional and Reactive Domain Modeling
* Christopher Allen, and Julie Moronuki's book - Haskell Programming from First Principles
Scala collection methods flatMap and flatten are more powerful than monadic f...Philip Schwarz
The flatten and flatMap methods of Scala's monad instances do not support mixing of collection types, such as flattening a List of Sets. However, the native flatten and flatMap methods of Scala collections like List, Vector, and Set do support mixing types. They are implemented using traversals, builders, and implicit CanBuildFrom builder factories that can build collections with heterogeneous element types. When flattening or flatMapping a collection, the appropriate CanBuildFrom is used to get a builder that adds elements of the nested collection to the output collection being built.
The document discusses Arrow, a generalization of functions in Scala. Arrows can represent computations with multiple inputs through tuples. The document defines Arrow traits and shows examples of Arrow combinators like first, second, split, and combine. It also compares Arrows to Applicatives and Monads. Arrows provide building blocks for functional reactive programming but have clumsy syntax. The document further discusses Arrow extensions like ArrowChoice and ArrowLoop, which enables feedback loops through lazy evaluation. It concludes with Comonads, which consume context, and MonadFix, which enables stackless recursion.
The document discusses Applicative Functors, Monads, Foldables and Traversables in Scala. Some key points:
1. Applicative Functors allow applying functions to values inside data structures in a point-free style, while preserving the structure.
2. Monads are more powerful than Applicative Functors as they can flatten nested structures and change behavior through chaining of functions.
3. Foldables allow aggregating values inside a data structure using a Monoid. Traversables generalize Foldables by keeping the structure intact using an Applicative instead of a Monoid.
4. Composition of Applicative Functors is possible generically, but composition of
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and others (Martin Odersky, Derek Wyatt, Adelbert Chang)
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
Inspired by Runar Bjarnason's scala exchange 2017 keynote https://skillsmatter.com/skillscasts/10746-keynote-composing-programs, I made a slide deck on Functor laws. Download for better quality.
Download for flawless quality (slides viewed online look a bit grainy and out of focus).
Equivalence of nested flatMaps and chained flatMaps for Kleisli arrow composition.
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
The document defines an IO monad for representing computations with side effects in Scala. The IO trait defines map and flatMap methods to allow sequencing of effectful computations. Functions like ReadLine and PrintLine are defined to interact with the console. A temperature conversion program is implemented using the IO monad, separating the pure computation from executing side effects.
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
A monoid is an algebraic structure consisting of a set and a binary operation that is associative and has an identity element. Some key properties of monoids include:
1) A monoid consists of a type A, a binary operation op that combines two values of type A, and a zero value that acts as an identity.
2) The binary operation must be associative, meaning op(op(x,y),z) = op(x,op(y,z)).
3) The zero value must satisfy the identity laws: op(x, zero) = x and op(zero, x) = x.
4) Common examples of monoids include string concatenation
Download for flawless quality (slides viewed online look a bit grainy and out of focus). A monad is an implementation of one of the minimal sets of monadic combinators, satisfying the laws of associativity and identity - see how compositional responsibilities are distributed in each combinator set
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
Scala 3 enum for a terser Option Monad Algebraic Data TypePhilip Schwarz
(download for flawless slides)
* Explore a terser definition of the Option Monad that uses a Scala 3 enum as an Algebraic Data Type.
* In the process, have a tiny bit of fun with Scala 3 enums.
* Get a refresher on the Functor and Monad laws.
* See how easy it is to use Scala 3 extension methods, e.g. to add convenience methods and infix operators.
The diagrams for function composition and Kleisli composition were made using https://q.uiver.app/ by https://twitter.com/varkora.
Source code: https://github.com/philipschwarz/scala-3-enum-for-terser-option-monad-algebraic-data-type
Errata:
slide 14 is an unwanted leftover - it is the same as slide 15 minus a diagram.
on slide 19, the colons in the extension method declarations are not needed
This presentation takes you on a functional programming journey, it starts from basic Scala programming language design concepts and leads to a concept of Monads, how some of them designed in Scala and what is the purpose of them
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaPhilip Schwarz
See a program structure flowchart used to highlight how an FP program breaks down into a functional core and imperative shell
View a program structure flowchart for the Game of Life
See the code for Game of Life’s functional core and imperative shell, both in Haskell and in Scala.
Code:
https://github.com/philipschwarz/functional-core-imperative-shell-scala
https://github.com/philipschwarz/functional-core-imperative-shell-haskell
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...Philip Schwarz
Learn how to write FP code that displays a graphical representation of all the numerous N-Queens solutions for N=4,5,6,7,8 .
See how to neatly solve the problem by exploiting its self-similarity and using a divide and conquer approach.
Make light work of assembling multiple images into a whole, by exploiting Doodle’s facilities for combining images using a relative layout.
See relevant FP functions, like Foldable’s intercalate and intersperse, in action.
Code for part 3: https://github.com/philipschwarz/n-queens-combinatorial-problem-scala-part-3
Here I link up up some very useful material by Robert Norris (@tpolecat) and Martin Odersky (@odersky) to introduce Monad laws and reinforce the importance of checking the laws. E.g. while Option satisfies the laws, Try is not a lawful Monad: it trades the left identity law for the bullet-proof principle.
* ERRATA *
1) on the first slide the Kleisli composition signature appears three times, but one of the occurrences is incorrect in that it is (>=>)::(a->mb)->(b->mb)->(a->mc) whereas is should be (>=>)::(a->mb)->(b->mc)->(a->mc) - thank you Jules Ivanic.
The document discusses functional programming concepts like monads, functors, and for comprehensions in Scala. It provides definitions and laws for functors, monads, and monadic operations like map, flatMap, filter. It shows the equivalence between for comprehensions and flatMap/map implementations. It also discusses monadic zeros and filtering laws. Key concepts covered include the functor laws, monad laws, equivalence between map/flatMap and for comprehensions, and laws for operations like filter.
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Philip Schwarz
Kleisli composition, flatMap, join, map, unit. A study/memory aid, to help learn/recall their implementation/interrelation.
Version 2, updated for Scala 3
AdRoll Tech Talk Presentation:
In this talk I present three approaches to understanding monads:
- How Monads Arise Naturally
- Monads as Implemented in Haskell
- Monads in Category Theory
This document summarizes a presentation about type classes in Scala. It introduces type classes like Monoid and Functor. It provides examples of Monoid instances for types like Int and Option. It explains how to define type classes for new types. It shows how to generalize functions like sequence and traverse to work for any Applicative functor using type classes. Finally, it discusses related concepts like Semigroup, Semigroupal functors, and NonEmptyList.
This document introduces functional programming concepts like functors, applicatives, and monads in Scala. It defines type classes like Functor, Applicative, and Monad to capture these concepts. Implementations for Option and List are provided as examples. Laws are discussed to ensure type class instances behave as expected. The Cats library is introduced as providing pre-defined type classes and instances that can be used instead of rolling your own.
This document provides an overview of algebraic structures like monoids, lattices, groups, and rings. It discusses how these structures appear at both the value level and type level in Scala. At the value level, concepts like monoids, semigroups, and groups are demonstrated with examples. At the type level, product and sum types are shown to form monoids, and union/intersection types form lattices. Higher kinded type classes are used to abstract over these structures. Applications to data processing and error handling are also covered. In conclusion, algebraic structures provide useful abstractions both mathematically and in Scala's type system.
This document discusses algebraic data types and generic programming using origami patterns. It defines List and Binary Tree as algebraic data types in Haskell and Scala. It shows how operations like map, fold, and build can be defined generically for any algebraic data type using a Bifunctor abstraction and the Fix type. This allows defining common functions like folding, mapping, and building on different data types in a consistent way.
Different Ways of Function Composition in Scala:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Fine-grained composability of functions is one of the core advantages of FP.
Treating "Functions as Data" means that we can store, manipulate, pass functions around and compose them in much the same way we do with data.
This talk demonstrates different ways of function composition in Scala.
The focus lies on scala.Function1, because due to tupling and currying we can regard any FunctionN (except Function0) as a Function1. Curried functions are easier to compose.
Starting with the composition methods of scala.Function1: apply, compose and andThen, we will investigate folding a Seq of functions.
We can also define a pipe operator |> as in F# in order to 'pipe' values through a pipeline of functions.
Defining a Monoid for Function1 allows us to combine two or more functions into a new one.
A function can also be seen as a Functor and a Monad. That means: Functions can be mapped and flatMapped over. And we can write for-comprehensions in a Function1 context just as we do with List, Option, Future, Either etc.
Being Monads, we can use functions in any monadic context. We will see that Function1 is the Reader Monad.
The most powerful way of function composition is Kleisli (also known as ReaderT). We will see that Kleisli (defined with the Id context) is the Reader Monad again.
From Functor Composition to Monad TransformersHermann Hueck
In a List[Option[A]] or Future[Option[A]] we want to access the value of type A conveniently without nested mapping and flatMapping.
We can avoid nested mapping with composed Functors. Functors compose, but Monads do not! What can we do?
Monad transformers to the rescue!
After going through Functor composition I show how 2 Monads are bolted together with a Monad transformer and how to use this construct. I demonstrate this with the Option transformer OptionT and will end up with best practices.
This document provides an overview of algebraic structures like monoids, lattices, groups, and rings. It discusses how these concepts can be generalized to higher-kinded type classes in Scala. It also explores how Scala's type system relates to these structures, with sum and product types forming commutative rigs. Finally, it discusses how these structures can be useful for modeling parallelism, error handling, and other programming patterns in Scala.
This document outlines a talk on using category theory concepts in functional programming. It begins by introducing the definition of a category from category theory and using Scala examples to demonstrate how types and functions in Scala satisfy this definition. It then defines functors, natural transformations, and monads from category theory and provides examples showing how options, lists, and functions in Scala form a monad. It proves that the category theory definition of a monad is equivalent to the definition used in functional programming. The document suggests category theory concepts help formalize design patterns and make code more refactorable.
Monad as functor with pair of natural transformationsPhilip Schwarz
Explains why a Monad is a functor with a pair of natural transformations (plus associativity and identity laws). It then explores this by looking at an example, with code in Scala.
Inspired and based on videos/publications by Bartosz Milewski, Rúnar Bjarnason and Rob Norris.
Download for better quality.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...Philip Schwarz
See how feeding FP workhorses map and filter with monadic steroids turns them into the intriguing mapM and filterM.
Graduate to foldM by learning how it behaves with the help of three simple yet instructive examples of its usage.
Use the powers of foldM to generate all permutations of a collection with a simple one-liner.
Exploit what you learned about foldM to solve the N-Queens Combinatorial Problem with an iterative approach rather than a recursive one.
Optics with monocle - Modeling the part and the wholeIlan Godik
Functional Programming is based on the concept of using pure functions, which at first sight limit us from various things as I/O, mutation - change and throwing exceptions - dealing with errors or uncertainty.
Optics help us deal with change inside compound structures and with branches (as with error handling), by providing facilities for looking into complex structures, and modifying a part of them, as well as powerful abstractions for composing optics, in order to build even more complex systems.
In this talk, I will introduce some of the optics, as Lenses, Prisms and Isomorphisms, and the motivation behind them, powerful use cases with Polymorphic Optics in Monocle, and if time will allow, explain the interesting representation of Lenses through Van Laarhoven Lenses.
Monad and Algebraic Design in Functional ProgrammingNamuk Park
This document discusses functional programming concepts including SOLID design principles, strategy pattern, composition over inheritance, algebraic design, functors, monads, applicatives, and how monads can be used for railway oriented programming. It provides code examples for defining functors and monads in Scala as well as examples of type representations for monomorphism, epimorphism, and isomorphism.
Functions are treated as objects in Scala, with the function type A => B being an abbreviation for the class scala.Function1[A, B]. Functions are objects that have an apply method. Case classes implicitly define companion objects with apply methods, allowing constructor-like syntax. Pattern matching provides a way to generalize switch statements to class hierarchies. The for expression provides a cleaner syntax than higher-order functions like map and flatMap for working with collections, but compiles to calls to these functions. Types like Option and Try are examples of monads in Scala, making failure or missing data explicit in the type while hiding boilerplate code.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.
Free Monads are a powerful technique that can separate the representation of programs from the messy details of how they get run.
I'll go into the details of how they work, how to use them for fun and profit in your own code, and demonstrate a live Free Monad-driven tank game.
Supporting code at https://github.com/kenbot/free
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...Philip Schwarz
See how the guard function has migrated from MonadPlus to Alternative and learn something about the latter.
Learn how to write a Scala program that draws an N-Queens solution board using the Doodle graphics library.
See how to write the equivalent Haskell program using the Gloss graphics library.
Learn how to use Monoid and Foldable to compose images both in Haskell and in Scala.
Link to part 1: https://www.slideshare.net/pjschwarz/nqueens-combinatorial-problem-polyglot-fp-for-fun-and-profit-haskell-and-scala-part-1
Errata:
On slide 22, the last line of the showQueens function should of course be show(solution).draw(frame) rather than show(solution).draw
On slide 43, it would be better if the definitions of the beside, above and on Monoids were also shown.
Similar to Kleisli composition, flatMap, join, map, unit - implementation and interrelation (20)
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidPhilip Schwarz
The subject of this deck is the small Print[A] program in the following blog post by Noel Welsh: https://www.inner-product.com/posts/direct-style-effects/.
Keywords: "direct-style", "context function", "context functions", "algebraic effect", "algebraic effects", "scala", "effect system", "effect systems", "effect", "side effect", "composition", "fp", "functional programming"
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
For functions that can be defined both as an instance of a right fold and as an instance of a left fold, one may be more efficient than the other.
Let's look at the example of a function 'decimal' that converts a list of digits into the corresponding decimal number.
Erratum: it has been pointed out that it is possible to define the zip function using a right fold (see slide 5).
Folding Cheat Sheet #3 - third in a seriesPhilip Schwarz
This document summarizes the universal property of fold, which states that for finite lists the fold function is the unique function that satisfies its defining recursive equations. It provides examples of how common list functions like sum, product, length, concatenation (⧺) can be defined in terms of fold. It also notes that the universal property can be generalized to handle partial and infinite lists. Finally, it states that map, filter and fold form the "triad" or basic building blocks of functional programming.
Folding Cheat Sheet #2 - second in a seriesPhilip Schwarz
This document provides definitions and examples of foldr and foldl functions in functional programming. Foldr recursively applies a function from right to left, associating at each step. Foldl recursively applies a function from left to right, associating at each step. Examples are given applying foldr and foldl to a list with elements a0 through a3, using a function f and initial value b. Programmatic and mathematical definitions of foldr and foldl are also presented.
Folding Cheat Sheet #1 - first in a seriesPhilip Schwarz
This document provides examples of using fold functions to define recursive functions over natural numbers (Nat) and lists. It shows common patterns for defining recursive functions over Nat using foldn and over lists using foldr. Three examples are given of functions defined over Nat using foldn: addition, multiplication, and exponentiation. Three examples are also given of functions defined over lists using foldr: sum, length, and append.
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
Tagless Final Encoding - Algebras and Interpreters and also Programs - An introduction, through the work of Gabriel Volpe.
Slide deck home: http://fpilluminated.com/assets/tagless-final-encoding-algebras-interpreters-and-programs.html
A sighting of traverseFilter and foldMap in Practical FP in ScalaPhilip Schwarz
Slide deck home: http://fpilluminated.com/assets/sighting-of-scala-cats-traverseFilter-and-foldMap-in-practical-fp-in-scala.html.
Download PDF for perfect image quality.
A sighting of sequence function in Practical FP in ScalaPhilip Schwarz
Slide deck home: http://fpilluminated.com/assets/sighting-of-scala-cats-sequence-function-in-practical-fp-in-scala.html.
Download PDF for perfect image quality.
This talk was presented on Aug 3rd 2023 during the Scala in the City event a ITV in London https://www.meetup.com/scala-in-the-city/events/292844968/
Visit the following for a description, slideshow, all slides with transcript, pdf, github repo, and eventually a video recording: http://fpilluminated.com/assets/n-queens-combinatorial-puzzle-meets-cats.html
At the centre of this talk is the N-Queens combinatorial puzzle. The reason why this puzzle features in the Scala book and functional programming course by Martin Odersky (the language’s creator), is that such puzzles are a particularly suitable application area of 'for comprehensions'.
We’ll start by (re)acquainting ourselves with the puzzle, and seeing the role played in it by permutations. Next, we’ll see how, when wanting to visualise candidate puzzle solutions, Cats’ monoidal functions fold and foldMap are a great fit for combining images.
While we are all very familiar with the triad providing the bread, butter and jam of functional programming, i.e. map, filter and fold, not everyone knows about the corresponding functions in Cats’ monadic variant of the triad, i.e. mapM, filterM and foldM, which we are going to learn about next.
As is often the case in functional programming, the traverse function makes an appearance, and we shall grab the opportunity to point out the symmetry that exists in the interrelation of flatMap / foldMap / traverse and flatten / fold / sequence.
Armed with an understanding of foldM, we then look at how such a function can be used to implement an iterative algorithm for the N-Queens puzzle.
The talk ends by pointing out that the iterative algorithm is smarter than the recursive one, because it ‘remembers’ where it has already placed previous queens.
Nat, List and Option Monoids -from scratch -Combining and Folding -an examplePhilip Schwarz
Nat, List and Option Monoids, from scratch. Combining and Folding: an example.
This is a new version of the original which has some cosmetic changes and a new 7th slide which only differs from slide 6 in that it defines the fold function in terms of the foldRight function.
Code: https://github.com/philipschwarz/nat-list-and-option-monoids-from-scratch-combining-and-folding-an-example
Nat, List and Option Monoids -from scratch -Combining and Folding -an examplePhilip Schwarz
Nat, List and Option Monoids, from scratch. Combining and Folding: an example.
Code: https://github.com/philipschwarz/nat-list-and-option-monoids-from-scratch-combining-and-folding-an-example
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...Philip Schwarz
When I posted the deck for Part 1 to the Scala users forum, Odd Möller linked to a paper titled "The Genuine Sieve of Eratosthenes", which speaks of the Unfaithful Sieve.
Part 2 is based on that paper and on Richard Bird's faithful Haskell implementation of the Sieve, which we translate into Scala.
Scala code for Richard Bird's infinite primes Haskell program: https://github.com/philipschwarz/sieve-of-eratosthenes-part-2-scala
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
- The document describes how product types (built using AND) and sum types (built using OR) are used to define types for representing fruit salads and fruit snacks in F#, Haskell, Scala, and Java.
- Product types combine elements and are used to define the FruitSalad type, while sum types allow alternatives and are used to define the FruitSnack type consisting of different fruits.
- Pattern matching is demonstrated to write functions that analyze and return different strings based on the values of FruitSalad and FruitSnack types.
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
Most important New features of Oracle 23c for DBAs and Developers. You can get more idea from my youtube channel video from https://youtu.be/XvL5WtaC20A
When it is all about ERP solutions, companies typically meet their needs with common ERP solutions like SAP, Oracle, and Microsoft Dynamics. These big players have demonstrated that ERP systems can be either simple or highly comprehensive. This remains true today, but there are new factors to consider, including a promising new contender in the market that’s Odoo. This blog compares Odoo ERP with traditional ERP systems and explains why many companies now see Odoo ERP as the best choice.
What are ERP Systems?
An ERP, or Enterprise Resource Planning, system provides your company with valuable information to help you make better decisions and boost your ROI. You should choose an ERP system based on your company’s specific needs. For instance, if you run a manufacturing or retail business, you will need an ERP system that efficiently manages inventory. A consulting firm, on the other hand, would benefit from an ERP system that enhances daily operations. Similarly, eCommerce stores would select an ERP system tailored to their needs.
Because different businesses have different requirements, ERP system functionalities can vary. Among the various ERP systems available, Odoo ERP is considered one of the best in the ERp market with more than 12 million global users today.
Odoo is an open-source ERP system initially designed for small to medium-sized businesses but now suitable for a wide range of companies. Odoo offers a scalable and configurable point-of-sale management solution and allows you to create customised modules for specific industries. Odoo is gaining more popularity because it is built in a way that allows easy customisation, has a user-friendly interface, and is affordable. Here, you will cover the main differences and get to know why Odoo is gaining attention despite the many other ERP systems available in the market.
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
Unveiling the Advantages of Agile Software Development.pdfbrainerhub1
Learn about Agile Software Development's advantages. Simplify your workflow to spur quicker innovation. Jump right in! We have also discussed the advantages.
SMS API Integration in Saudi Arabia| Best SMS API ServiceYara Milbes
Discover the benefits and implementation of SMS API integration in the UAE and Middle East. This comprehensive guide covers the importance of SMS messaging APIs, the advantages of bulk SMS APIs, and real-world case studies. Learn how CEQUENS, a leader in communication solutions, can help your business enhance customer engagement and streamline operations with innovative CPaaS, reliable SMS APIs, and omnichannel solutions, including WhatsApp Business. Perfect for businesses seeking to optimize their communication strategies in the digital age.
Using Query Store in Azure PostgreSQL to Understand Query PerformanceGrant Fritchey
Microsoft has added an excellent new extension in PostgreSQL on their Azure Platform. This session, presented at Posette 2024, covers what Query Store is and the types of information you can get out of it.
What to do when you have a perfect model for your software but you are constrained by an imperfect business model?
This talk explores the challenges of bringing modelling rigour to the business and strategy levels, and talking to your non-technical counterparts in the process.
How Can Hiring A Mobile App Development Company Help Your Business Grow?ToXSL Technologies
ToXSL Technologies is an award-winning Mobile App Development Company in Dubai that helps businesses reshape their digital possibilities with custom app services. As a top app development company in Dubai, we offer highly engaging iOS & Android app solutions. https://rb.gy/necdnt
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
Measures in SQL (SIGMOD 2024, Santiago, Chile)Julian Hyde
SQL has attained widespread adoption, but Business Intelligence tools still use their own higher level languages based upon a multidimensional paradigm. Composable calculations are what is missing from SQL, and we propose a new kind of column, called a measure, that attaches a calculation to a table. Like regular tables, tables with measures are composable and closed when used in queries.
SQL-with-measures has the power, conciseness and reusability of multidimensional languages but retains SQL semantics. Measure invocations can be expanded in place to simple, clear SQL.
To define the evaluation semantics for measures, we introduce context-sensitive expressions (a way to evaluate multidimensional expressions that is consistent with existing SQL semantics), a concept called evaluation context, and several operations for setting and modifying the evaluation context.
A talk at SIGMOD, June 9–15, 2024, Santiago, Chile
Authors: Julian Hyde (Google) and John Fremlin (Google)
https://doi.org/10.1145/3626246.3653374
Kleisli composition, flatMap, join, map, unit - implementation and interrelation
1. Kleisli composition, flatMap, join, map, unit
a study/memory aid
to help learn/recall their implementation/interrelation
inspired by, and based on, the work of
@philip_schwarzslides by
Rob Norris
@tpolecat @BartoszMilewski
Bartosz Milewski Runar Bjarnason
@runarorama
Paul Chiusano
@pchiusano
2. This slide deck is meant both for (1) those who are familiar with the monadic functions that are Kleisli
composition, unit, map, join and flatMap, and want to reinforce their knowledge (2) and as a memory aid, for
those who sometimes need a reminder of how these functions are implemented and how they interrelate.
I leaned about this subject mainly from Functional Programming in Scala, from Bartosz Milewski’s YouTube
videos (and his book), and from Rob Norris’s YouTube video, Functional Programming with Effects.
@philip_schwarz
Functional Programming in ScalaRob Norris
@tpolecat@BartoszMilewski
Bartosz Milewski
Paul ChiusanoRunar Bjarnason
@pchiusano@runarorama
If you need an intro to, or refresher on, the monadic functions that are
Kleisli composition, unit, map, join and flatMap, then see the following
https://www.slideshare.net/pjschwarz/kleisli-monad-as-functor-with-pair-of-natural-transformations
https://www.slideshare.net/pjschwarz/fish-operator-anatomy
https://www.slideshare.net/pjschwarz/compositionality-and-category-theory-a-montage-of-slidestranscript-for-sections-of-rnar-bjarnasons-keynote-composing-programs
https://www.slideshare.net/pjschwarz/kleisli-composition
https://www.slideshare.net/pjschwarz/rob-norrisfunctionalprogrammingwitheffects
See the final slide of this deck for some of the
inspiration/ideas I got from Rob Norris’s video.
3. case class Insurance(name:String)
case class Car(insurance: Option[Insurance])
case class Person(car: Option[Car])
val car: Person => Option[Car] =
person => person.car
val insurance: Car => Option[Insurance] =
car => car.insurance
val toChars: String => List[Char] = _.toList
val toAscii: Char => List[Char] = _.toInt.toString.toList
assert( toChars("AB") == List('A','B'))
assert( toAscii('A') == List('6','5') )
val carInsurance: Person => Option[Insurance] =
car >=> insurance
val non-driver= Person(car=None)
val uninsured = Person(Some(Car(insurance=None)))
val insured = Person(Some(Car(Some(Insurance("Acme")))))
assert(carInsurance(non-driver).isEmpty )
assert(carInsurance(uninsured).isEmpty )
assert(carInsurance(insured).contains(Insurance("Acme")))
val toCharsAscii: String => List[Char] =
toChars >=> toAscii
assert(toCharsAscii("AB") == List('6','5','6','6'))
implicit class OptionFunctionOps[A,B](f:A=>Option[B]) {
def >=>[C](g: B => Option[C]): A => Option[C] =
a => f(a) match {
case Some(b) => g(b)
case None => None
}
}
implicit class ListFunctionOps[A,B](f:A=>List[B] ) {
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(List[C]())((b, cs) => g(b) ++ cs)
}
A simple example of hand-coding Kleisli composition (i.e. >=>, the fish operator) for Option and List
Option List
4. @philip_schwarz
In the previous slide, it is the implicits OptionFunctionOps and ListFunctionOps
that are making available the fish operator >=> on functions whose codomain is a
List or an Option.
To see the fish operator and ordinary
function arrows in all their glory, select
the Fira Code font (e.g. in IntelliJ IDEA)
5. We have implemented >=> by hand. Twice. Once for Option and once for List.
Now let’s make >=> generic and implement it in terms of the built-in flatMap
function of the Option and List Monads.
6. implicit class OptionFunctionOps[A, B](f: A => Option[B] ) {
def >=>[C](g: B => Option[C]): A => Option[C] =
a => f(a) match {
case Some(b) => g(b)
case None => None
}
}
implicit class ListFunctionOps[A, B](f: A => List[B] ) {
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(List[C]())((b, cs) => g(b) ++ cs)
}
implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
a => M.flatMap(f(a))(g)
}
trait Monad[F[_]] {
def unit[A](a: => A): F[A]
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def flatMap[A, B]
(fa: Option[A])(f: A => Option[B]): Option[B] = fa flatMap f
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def flatMap[A, B]
(fa: List[A])(f: A => List[B]): List[B] = fa flatMap f
}
Before After
>=> is hand-coded and specialised for Option and List >=> is generic and defined in terms of built-in flatMap
7. I first saw the definition of >=> in a YouTube video by Bartosz Milewski.
Bartosz Milewski’s definition of the fish operator (Kleisli
composition) in his lecture on monads.
Category Theory 10.1: Monads@BartoszMilewski
Kleisli Composition (fish operator) >=> compose
Bind >>= flatMap
lifts a to m a (lifts A to F[A]) return unit/pure
See the next slide for more
8. class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
class Monad m where
(>=>) :: (a -> m b) -> (b -> m c) -> (a -> m c)
return :: a -> m a
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Functor m => Monad m where
join :: m(m a) -> ma
return :: a -> m a
>=> Kleisli Composition (aka the fish operator)
>>= Bind
f >=> g = λa -> let mb = f a in mb >>= g
= λa -> (f a) >>= g
Kleisli Composition (fish operator) >=> compose
Bind >>= flatMap
lifts a to m a (lifts A to F[A]) return unit/pure
9. @philip_schwarz
In the previous slides (and in future slides), where you see the implicits optionMonad, listMonad, and MonadFunctionOps,
here is how they work together to make available the fish operator >=> on functions whose codomain is a List or an Option.
10. Now let’s hand-code ourselves the flatMap
functions of the Option and List Monads.
11. implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] =
Some(a)
def flatMap[A, B](fa:Option[A])(f: A => Option[B]):Option[B] =
fa flatMap f
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] =
List(a)
def flatMap[A, B](fa:List[A])(f: A => List[B]):List[B] =
fa flatMap f
}
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] =
Some(a)
def flatMap[A, B](fa: Option[A])(f: A => Option[B]): Option[B] =
fa match {
case Some(a) => f(a)
case None => None
}
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] =
List(a)
def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] =
fa.foldRight(List[B]())((a,bs) => f(a) ++ bs)
}
trait Monad[F[_]] { implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def unit[A](a: => A): F[A] def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B] a => M.flatMap(f(a))(g)
} }
Before After
>=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of hand-coded flatMap
12. Earlier we implemented a generic >=> in terms of the built-in flatMap function
of the Option and List Monads.
Let’s do that again but this time implementing >=> in terms of the built-in map
and join functions of the Option and List Monads.@philip_schwarz
in Scala, join is called flatten
The next slide is just a refresher on the fact that it is possible to define a Monad
in terms of unit, map and join, instead of in terms of unit and flatMap, or in
terms of unit and the fish operator. If it is the first time that you go through this
slide deck you may want to skip the next slide.
13. Bartosz Milewski introduces a third definition of Monad in terms of join and return, based on Functor
So this (join and return) is an alternative definition of a monad. But in this case I have to specifically say that m is a Functor, which is actually a nice thing, that I have to explicitly specify it.
…
But remember, in this case (join and return) you really have to assume that it is a functor. In this way, join is the most basic thing. Using just join and return is really more atomic than using
either bind or the Kleisli arrow, because they additionally susbsume functoriality, whereas here, functoriality is separate, separately it is a functor and separately we define join, and
separately we define return.
…
So this definition (join and return) or the definition with the Kleisli arrow, they are not used in Haskell, although they could have been. But Haskell people decided to use this (>>= and return)
as their basic definition and then for every monad they separately define join and the Kleisli arrow. So if you have a monad you can use join and the Kleisli arrow because they are defined in
the library for you. So it’s always enough to define just bind, and then fish and join will be automatically defined for you, you don’t have to do it.
#1
#2
#3
Category Theory 10.1: Monads @BartoszMilewski
14. implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def map[A, B](fa: Option[A])(f: A => B): Option[B] =
fa map f
def join[A](ffa: Option[Option[A]]): Option[A] =
ffa flatten
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def join[A](ffa: List[List[A]]): List[A] =
ffa flatten
def map[A, B](fa: List[A])(f: A => B): List[B] =
fa map f
}
Before After
>=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of built-in map and join
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def flatMap[A, B](fa:Option[A])(f: A => Option[B]):Option[B] =
fa flatMap f
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def flatMap[A, B](fa:List[A])(f: A => List[B]):List[B] =
fa flatMap f
}
trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
trait Monad[F[_]] extends Functor[F] {
def unit[A](a: => A): F[A]
def join[A](ffa: F[F[A]]): F[A]
}
implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
a => M.join(M.map(f(a))(g))
}
trait Monad[F[_]] {
def unit[A](a: => A): F[A]
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}
implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
a => M.flatMap(f(a))(g)
}
15. Now let’s hand-code ourselves the map and
join functions of the Option and List Monads.
16. implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa map f
def join[A](ffa: Option[Option[A]]): Option[A] = ffa flatten
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def map[A, B](fa: List[A])(f: A => B): List[B] = fa map f
def join[A](ffa: List[List[A]]): List[A] = ffa flatten
}
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa match {
case Some(a) => Some(f(a))
case None => None
}
def join[A](ffa: Option[Option[A]]): Option[A] = ffa match {
case Some(a) => a
case None => None
}
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def map[A, B](fa: List[A])(f: A => B): List[B] = fa match {
case Nil => Nil
case head :: tail => f(head) :: map(tail)(f)
}
def join[A](ffa: List[List[A]]): List[A] = ffa match {
case Nil => Nil
case head :: tail => head ++ join(tail)
}
}
trait Functor[F[_]] {
def map[A,B](fa:F[A])(f:A =>B):F[B]
}
trait Monad[F[_]] extends Functor[F] {
def unit[A](a: => A):F[A]
def join[A](ffa:F[F[A]]):F[A]
}
implicit class MonadFunctionOps[F[_],A,B](f:A =>F[B]) {
def >=>[C](g:B=>F[C])(implicit M:Monad[F]):A =>F[C] =
a => M.join(M.map(f(a))(g))
}
Before After
>=> is generic and defined in terms of built-in map and join >=> is generic and defined in terms of hand-coded map and join
17. Now a bonus slide: let’s hand-code again the
flatMap and join functions of List, but this time
without using built-ins foldRight and ++.
@philip_schwarz
18. implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def map[A, B](fa: List[A])(f: A => B): List[B] = fa match {
case Nil => Nil
case head :: tail => f(head) :: map(tail)(f)
}
def join[A](ffa: List[List[A]]): List[A] = ffa match {
case Nil => Nil
case head :: tail => head ++ join(tail)
}
}
def concatenate[A](left: List[A], right: List[A]): List[A] =
left match {
case Nil => right
case head :: tail => head :: concatenate(tail, right)
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] =
List(a)
def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] =
fa.foldRight(List[B]())((a,bs) => f(a) ++ bs)
}
Bonus Slide – hand-coding flatMap and join for List without using built-in foldRight and ++
def join[A](ffa: List[List[A]]): List[A] =
ffa match {
case Nil => Nil
case head :: tail => concatenate(head, join(tail))
}
def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] =
fa match {
case Nil => Nil
case head :: tail => concatenate(f(head), flatMap(tail)(f))
}
19. I would like to thank Rob Norris for his great talk (see next slide), from which I
learned a lot about Kleisli composition and in which I first saw the use of a
syntax class to add the fish operator to a type class.
20. scale.bythebay.io
Rob Norris
Functional Programming with Effects
Rob Norris @tpolecat
the fish operator (Kleisli composition), can
be implemented using flatMap.
And this Fishy typeclass that we have derived from nothing,
using math, is Monad. So this scary thing, it just comes
naturally and I haven’t seen people talk about getting to it
from this direction. And so I hope that was helpful.
We can implement compose, the fish operator using
flatMap, so the fish operator is something we can
derive later really, the operation we need is flatMap.
We can define a syntax class
that adds these methods so that
anything that is an F[A], if there
is a Fishy instance, gets these
operations by syntax.