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
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
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.
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.
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.
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
This slide deck can work both as an aide mémoire (memory jogger), or as a first (not completely trivial) example of using left folds, left scans and iteration, to implement mathematical induction.
Errata: on almost half of the slides there is some minor typo or imperfection or in some cases a minor error and in one case, an omission. See a later version for corrections and some improvements.
(for best quality images, either download or view here: https://philipschwarz.dev/fpilluminated/?page_id=455)
Scala code for latest version: https://github.com/philipschwarz/fp-fold-scan-iterate-triad-a-first-example-scala
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
(download for picture-perfect quality) Follow along as Trampolining is used to overcome Stack Overflow issues with the simple IO monad, deepening you understanding of the IO monad in the process. See Game of Life IO actions migrated to the Cats Effect IO monad, which is trampolined in its flatMap evaluation.
Errata:
slide 33: "impure factorial function" should be "initial factorial function"
slide 34: there is a pointless short vertical bar inside a speech bubble
slide 39: "it is till annoying" should be "it is still annoying"
slide 44: "values that we are interested" should be "values that we are interested in"
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
Errata:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑎 should be 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑒
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
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.
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.
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.
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
This slide deck can work both as an aide mémoire (memory jogger), or as a first (not completely trivial) example of using left folds, left scans and iteration, to implement mathematical induction.
Errata: on almost half of the slides there is some minor typo or imperfection or in some cases a minor error and in one case, an omission. See a later version for corrections and some improvements.
(for best quality images, either download or view here: https://philipschwarz.dev/fpilluminated/?page_id=455)
Scala code for latest version: https://github.com/philipschwarz/fp-fold-scan-iterate-triad-a-first-example-scala
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
(download for picture-perfect quality) Follow along as Trampolining is used to overcome Stack Overflow issues with the simple IO monad, deepening you understanding of the IO monad in the process. See Game of Life IO actions migrated to the Cats Effect IO monad, which is trampolined in its flatMap evaluation.
Errata:
slide 33: "impure factorial function" should be "initial factorial function"
slide 34: there is a pointless short vertical bar inside a speech bubble
slide 39: "it is till annoying" should be "it is still annoying"
slide 44: "values that we are interested" should be "values that we are interested in"
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
Errata:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑎 should be 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑒
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
Take the very first baby steps on the path to doing graphics in Haskell and Scala.
Learn about a simple yet educational recursive algorithm producing images that are pleasing to the eye.
Learn how functional programs deal with the side effects required to draw images.
See how libraries like Gloss and Doodle make drawing Sierpinski’s triangle a doddle.
Code for this slide deck:
https://github.com/philipschwarz/sierpinski-triangle-haskell-gloss
https://github.com/philipschwarz/sierpinski-triangle-scala-cats-io
https://github.com/philipschwarz/sierpinski-triangle-scala-awt-and-doodle
Errata:
1. the title 'Sierpinski Triangle' on the front slide could be improved by replacing it with 'Sierpinski's Triangle'.
2. a couple of typos on two slides
3. the triangles drawn using Doodle are not equilateral, as intended but isosceles.
(UPDATE 2021-06-15 I opened PR https://github.com/creativescala/doodle/pull/99 and as a result, an equilateral triangle has now been added to Doodle: https://github.com/creativescala/doodle/commit/30d20efebcc2016942e9cdbae85fefca5b95fa3c).
Here is a corrected version of the deck: https://www.slideshare.net/pjschwarz/sierpinski-triangle-polyglot-fp-for-fun-and-profit-haskell-and-scala-with-minor-corrections
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.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Philip Schwarz
(download for perfect quality) See aggregation functions defined inductively and implemented using recursion.
Learn how in many cases, tail-recursion and the accumulator trick can be used to avoid stack-overflow errors.
Watch as general aggregation is implemented and see duality theorems capturing the relationship between left folds and right folds.
Through the work of Sergei Winitzki and Richard Bird.
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Philip Schwarz
(download for picture-perfect quality) Follow along as the impure functions in the Game of Life are translated from Haskell into Scala, deepening you understanding of the IO monad in the process.
This is simply a copy of the original with an error corrected on slides 3 and 52, which were supposed to show Scala code and instead showed the Haskell equivalent! Plus removal of a few minor aesthetic imperfections.
Original: https://www.slideshare.net/pjschwarz/game-of-life-polyglot-fp-haskell-scala-unison-part-2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
(download for perfect quality) - See how recursive functions and structural induction relate to recursive datatypes.
Follow along as the fold abstraction is introduced and explained.
Watch as folding is used to simplify the definition of recursive functions over recursive datatypes
Part 1 - through the work of Richard Bird and Graham Hutton.
Errata:
slide 7, 11 fib(0) is 0,rather than 1
slide 23: was supposed to be followed by 2-3 slides recapitulating definitions of factorial and fibonacci with and without foldr, plus translation to scala
slide 36: concat not invoked in concat example
slides 48 and 49: unwanted 'm' in definition of sum
throughout: a couple of typographical errors
throughout: several aesthetic imperfections (wrong font, wrong font colour)
(download for flawless quality) State Monad - Learn how it works - Follow Alvin Alexander’s example-driven build up to the State Monad and then branch off into a detailed look at its inner workings.
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
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
(download for perfect quality) - See how recursive functions and structural induction relate to recursive datatypes.
Follow along as the fold abstraction is introduced and explained.
Watch as folding is used to simplify the definition of recursive functions over recursive datatypes
Part 1 - through the work of Richard Bird and Graham Hutton.
This version corrects the following issues:
slide 7, 11 fib(0) is 0,rather than 1
slide 23: was supposed to be followed by 2-3 slides recapitulating definitions of factorial and fibonacci with and without foldr, plus translation to scala
slide 36: concat not invoked in concat example
slides 48 and 49: unwanted 'm' in definition of sum
throughout: a couple of typographical errors
throughout: several aesthetic imperfections (wrong font, wrong font colour)
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Philip Schwarz
Embark on an informative and fun journey through everything you need to know to understand how the Applicative instance for functions makes for a terse palindrome checker function definition in point-free style.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
This version eliminates some minor imperfections and corrects the following two errors:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 푠푓표푙푑푙 (⊕) 푎 should be 푠푓표푙푑푙 (⊕) 푒
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
This slide deck can work both as an aide mémoire (memory jogger), or as a first (not completely trivial) example of using left folds, left scans and iteration, to implement mathematical induction.
This is just an updated version of the original slide deck which makes minor improvements and minor corrections in almost half of the slides.
(for best quality images, either download or view here: https://philipschwarz.dev/fpilluminated/?page_id=455)
You can see the Scala code here: https://github.com/philipschwarz/fp-fold-scan-iterate-triad-a-first-example-scala
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold.
It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out.
I have not yet come across a better introduction to these three functions.
The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here:
https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html.
Download for original image quality.
Errata:
slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction.
Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme
Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure
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
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
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
(download for better quality)
Introducing Assignment invalidates the Substitution Model of Evaluation and violates Referential Transparency
- as explained in SICP (the Wizard Book)
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
(download for perfect quality) See aggregation functions defined inductively and implemented using recursion.
Learn how in many cases, tail-recursion and the accumulator trick can be used to avoid stack-overflow errors.
Watch as general aggregation is implemented and see duality theorems capturing the relationship between left folds and right folds.
Through the work of Sergei Winitzki and Richard Bird.
This version corrects the following issues:
slide 32: = reverse --> reverse =
Slide 33: 100_000 -> 1_000_000
It also adds slides 36, 37 and 38
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
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
Take the very first baby steps on the path to doing graphics in Haskell and Scala.
Learn about a simple yet educational recursive algorithm producing images that are pleasing to the eye.
Learn how functional programs deal with the side effects required to draw images.
See how libraries like Gloss and Doodle make drawing Sierpinski’s triangle a doddle.
Code for this slide deck:
https://github.com/philipschwarz/sierpinski-triangle-haskell-gloss
https://github.com/philipschwarz/sierpinski-triangle-scala-cats-io
https://github.com/philipschwarz/sierpinski-triangle-scala-awt-and-doodle
Errata:
1. the title 'Sierpinski Triangle' on the front slide could be improved by replacing it with 'Sierpinski's Triangle'.
2. a couple of typos on two slides
3. the triangles drawn using Doodle are not equilateral, as intended but isosceles.
(UPDATE 2021-06-15 I opened PR https://github.com/creativescala/doodle/pull/99 and as a result, an equilateral triangle has now been added to Doodle: https://github.com/creativescala/doodle/commit/30d20efebcc2016942e9cdbae85fefca5b95fa3c).
Here is a corrected version of the deck: https://www.slideshare.net/pjschwarz/sierpinski-triangle-polyglot-fp-for-fun-and-profit-haskell-and-scala-with-minor-corrections
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.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Philip Schwarz
(download for perfect quality) See aggregation functions defined inductively and implemented using recursion.
Learn how in many cases, tail-recursion and the accumulator trick can be used to avoid stack-overflow errors.
Watch as general aggregation is implemented and see duality theorems capturing the relationship between left folds and right folds.
Through the work of Sergei Winitzki and Richard Bird.
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Philip Schwarz
(download for picture-perfect quality) Follow along as the impure functions in the Game of Life are translated from Haskell into Scala, deepening you understanding of the IO monad in the process.
This is simply a copy of the original with an error corrected on slides 3 and 52, which were supposed to show Scala code and instead showed the Haskell equivalent! Plus removal of a few minor aesthetic imperfections.
Original: https://www.slideshare.net/pjschwarz/game-of-life-polyglot-fp-haskell-scala-unison-part-2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
(download for perfect quality) - See how recursive functions and structural induction relate to recursive datatypes.
Follow along as the fold abstraction is introduced and explained.
Watch as folding is used to simplify the definition of recursive functions over recursive datatypes
Part 1 - through the work of Richard Bird and Graham Hutton.
Errata:
slide 7, 11 fib(0) is 0,rather than 1
slide 23: was supposed to be followed by 2-3 slides recapitulating definitions of factorial and fibonacci with and without foldr, plus translation to scala
slide 36: concat not invoked in concat example
slides 48 and 49: unwanted 'm' in definition of sum
throughout: a couple of typographical errors
throughout: several aesthetic imperfections (wrong font, wrong font colour)
(download for flawless quality) State Monad - Learn how it works - Follow Alvin Alexander’s example-driven build up to the State Monad and then branch off into a detailed look at its inner workings.
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
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
(download for perfect quality) - See how recursive functions and structural induction relate to recursive datatypes.
Follow along as the fold abstraction is introduced and explained.
Watch as folding is used to simplify the definition of recursive functions over recursive datatypes
Part 1 - through the work of Richard Bird and Graham Hutton.
This version corrects the following issues:
slide 7, 11 fib(0) is 0,rather than 1
slide 23: was supposed to be followed by 2-3 slides recapitulating definitions of factorial and fibonacci with and without foldr, plus translation to scala
slide 36: concat not invoked in concat example
slides 48 and 49: unwanted 'm' in definition of sum
throughout: a couple of typographical errors
throughout: several aesthetic imperfections (wrong font, wrong font colour)
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Philip Schwarz
Embark on an informative and fun journey through everything you need to know to understand how the Applicative instance for functions makes for a terse palindrome checker function definition in point-free style.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
This version eliminates some minor imperfections and corrects the following two errors:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 푠푓표푙푑푙 (⊕) 푎 should be 푠푓표푙푑푙 (⊕) 푒
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
This slide deck can work both as an aide mémoire (memory jogger), or as a first (not completely trivial) example of using left folds, left scans and iteration, to implement mathematical induction.
This is just an updated version of the original slide deck which makes minor improvements and minor corrections in almost half of the slides.
(for best quality images, either download or view here: https://philipschwarz.dev/fpilluminated/?page_id=455)
You can see the Scala code here: https://github.com/philipschwarz/fp-fold-scan-iterate-triad-a-first-example-scala
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold.
It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out.
I have not yet come across a better introduction to these three functions.
The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here:
https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html.
Download for original image quality.
Errata:
slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction.
Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme
Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure
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
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
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
(download for better quality)
Introducing Assignment invalidates the Substitution Model of Evaluation and violates Referential Transparency
- as explained in SICP (the Wizard Book)
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
(download for perfect quality) See aggregation functions defined inductively and implemented using recursion.
Learn how in many cases, tail-recursion and the accumulator trick can be used to avoid stack-overflow errors.
Watch as general aggregation is implemented and see duality theorems capturing the relationship between left folds and right folds.
Through the work of Sergei Winitzki and Richard Bird.
This version corrects the following issues:
slide 32: = reverse --> reverse =
Slide 33: 100_000 -> 1_000_000
It also adds slides 36, 37 and 38
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
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
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
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.
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.
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.
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).
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
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Haskell, Scala and Java.
Inspired by the example in Scott Wlaschin’s F# book: Domain Modeling Made Functional.
Download for better results.
Java 19 Code: https://github.com/philipschwarz/fruit-salad-and-fruit-snack-ADT-example-java
Jordan Peterson - The pursuit of meaning and related ethical axiomsPhilip Schwarz
I have only recently become aware of the work of Jordan Peterson. Because I am finding it so interesting, I hope that the following small collection of excerpts from some of his writings and speeches might entice any fellow latecomers to find out more about his work. See below for my own summary of some of the subjects touched upon in these slides.
Download for best results.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
RISE with SAP and Journey to the Intelligent Enterprise
Monad Fact #4
1. MONAD FACT #4
@philip_schwarzslides by
https://www.slideshare.net/pjschwarz
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
2. We’ve seen three minimal sets of primitive Monad combinators, and instances of Monad will
have to provide implementations of one of these sets:
• unit and flatMap
• unit and compose
• unit, map, and join
And we know that there are two monad laws to be satisfied, associativity and identity, that can be
formulated in various ways. So we can state plainly what a monad is:
A monad is an implementation of one of the minimal sets of monadic combinators,
satisfying the laws of associativity and identity.
That’s a perfectly respectable, precise, and terse definition. And if we’re being precise, this is the
only correct definition. A monad is precisely defined by its operations and laws; no more, no less.
Runar Bjarnason
@runarorama
Paul Chiusano
@pchiusano
Functional Programming in Scala
by Paul Chiusano and Runar Bjarnason
3. One of the minimal sets of primitive Monad combinators seen on the previous slide consists of
a unit function and a compose function.
The compose function in question is Kleisli composition.
If you need an introduction to Kleisli composition then see MONAD FACT #2.
If you need an introduction to the unit function then see MONAD FACT #1.
Another set of combinators includes the join function. In Scala this function is known as flatten.
@philip_schwarz
4. Let’s take the simplest monad, i.e. the identity monad, which does nothing, and let’s define it in terms of Kleisli composition and unit.
The Id monad wraps a value of some type A
Id also acts as the unit function. i.e. to lift the value 3 into the Id monad we use Id(3).
case class Id[A](value: A)
Now we have to come up with a body for the Kleisli composition function (shown below as the infix fish operator >=>):
The body must be a function of type A => Id[C]
a => ???
The only way we can get an Id[C] is by calling g, which takes a B as a parameter. But all we have to work with are the a parameter,
which is of type A, and function f. But that is fine because if we call f with a we get an Id[B] and if we then ask the latter for the B
value that it wraps, we have the B that we need to invoke g.
a => g(f(a).value)
And here is a simple test for the functionSo here is how we define Kleisli composition
implicit class IdFunctionOps[A,B](f: A => Id[B]) {
def >=>[C](g: B => Id[C]): A => Id[C] = ???
}
implicit class IdFunctionOps[A,B](f: A => Id[B]) {
def >=>[C](g: B => Id[C]): A => Id[C] =
a => g(f(a).value)
}
val double: Int => Id[Int] = n => Id(n * 2)
val square: Int => Id[Int] = n => Id(n * n)
assert( (double >=> square)(3) == Id(36))
5. Here is a simple test for join
Here is a test for our map function
So yes, we have defined the identity monad in terms of Kleisli
composition and unit.
But we want to be able to use the monad in a for comprehension, so
we now have to define a flatMap function and a map function. The
flatMap function can be defined in terms of Kleisli composition:
and map can then be defined in terms of flatMap:
case class Id[A](value: A)
object Id {
implicit class IdFunctionOps[A,B](f: A => Id[B]) {
def >=>[C](g: B => Id[C]): A => Id[C] =
a => g(f(a).value)
}
}
case class Id[A](value: A) {
def flatMap[B](f: A => Id[B]): Id[B] =
(((_:Unit) => this) >=> f)(())
}
case class Id[A](value: A) {
def flatMap[B](f: A => Id[B]): Id[B] =
(((_:Unit) => this) >=> f)(())
def map[B](f: A => B): Id[B] =
this flatMap { a => Id(f(a)) }
}
val increment: Int => Int = n => n + 1
assert( (Id(3) map increment) == Id(4) )
And here is a test for both our map and
flatMap functions
val result =
for {
six <- double(3)
thirtySix <- square(six)
} yield six + thirtySix
assert(result == Id(42))
We can also define join (aka flatten) in terms of
the flatMap function
def join[A](mma: Id[Id[A]]): Id[A] =
mma flatMap identity
assert( join(Id(Id(3))) == Id(3) )
6. Here is the whole code for the identity monad
In this slide deck we are going to compare the identity monad with the Option monad and the List monad.
How do the functions of the above identity monad, which is defined in terms of Kleisli composition, relate
to the equivalent Option monad functions?
See the next slide for the differences.
case class Id[A](value: A) {
def flatMap[B](f: A => Id[B]): Id[B] =
(((_:Unit) => this) >=> f)(())
def map[B](f: A => B): Id[B] =
this flatMap { a => Id(f(a)) }
}
object Id {
implicit class IdFunctionOps[A,B](f: A => Id[B]) {
def >=>[C](g: B => Id[C]): A => Id[C] =
a => g(f(a).value)
}
def join[A](mma: Id[Id[A]]): Id[A] =
mma flatMap identity
}
val double: Int => Id[Int] = n => Id(n * 2)
val square: Int => Id[Int] = n => Id(n * n)
assert( (double >=> square)(3) == Id(36))
val increment: Int => Int = n => n + 1
assert( (Id(3) map increment) == Id(4) )
assert( join(Id(Id(3))) == Id(3) )
val result =
for {
six <- double(3)
thirtySix <- square(six)
} yield six + thirtySix
assert(result == Id(42))
7. First of all we see that apart from the obvious swapping of Id for Option in their signatures, the flatMap and join functions of
the two monads are identical.
The only difference between the map functions of the two monads are the unit functions that they use: one uses Id and the other
uses Some.
So the only real difference between the two monads is the logic in the fish operator. That makes sense, since the monads are
defined in terms of unit and Kleisli composition, and since unit is a very simple function.
@philip_schwarz
8. The same is true of the differences between the functions of the Id monad and those of the List monad: the differences are in
the fish operator;
The apparent additional difference between the map functions is only due to the fact that we are using Cons(x,Nil) as a unit
function rather List(x), i.e. some singleton list constructor that we could define.
9. Let’s now turn to the function that differentiates the monads, i.e. Kleisli composition (the fish operator)
The composite function that it returns (the composition of f and g) has the following responsibilities (let’s call them
compositional responsibilities):
1) use f to compute a first value wrapped in a functional effect
2) dig underneath the wrapper to access the first value, discarding the wrapper
3) Use g to compute, using the first value, a second value also wrapped in a functional effect
4) return a third value wrapped in a functional effect that represents the composition (combination) of the first two
functional effects
As a slight variation on that, we can replace ‘wrapped in’ with ‘in the context of’
1) use f to compute a first value in the context of a functional effect
2) dig inside the context to access the first value, discarding the context
3) Use g to compute, using the first value, a second value also in the context of a functional effect
4) return a third value in the context of a functional effect that represents the composition (combination) of the first two
functional effects
implicit class IdFunctionOps[A,B](f: A => Id[B]) {
def >=>[C](g: B => Id[C]): A => Id[C] =
a => ???
}
10. Here are the Kleisli composition functions of the three monads (their fish operators).
Notice how different they are. The one in the identity monad seems to do almost nothing, the one in the Option monad seems to do a bit more
work, and the one in the List monad does quite a bit more.
See the next slide for some test code for the Option monad and the List monad.
object Option {
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
}
}
}
object Id {
implicit class IdFunctionOps[A,B](f: A => Id[B]) {
def >=>[C](g: B => Id[C]): A => Id[C] =
a => g(f(a).value)
}
}
sealed trait List[+A] {
def foldRight[B](b: B, f: (A,B) => B): B =
this match {
case Nil => b
case Cons(a, tail) =>
f(a, tail.foldRight(zero, f))
}
}
object List {
implicit class ListFunctionOps[A,B](f: A => List[B]) {
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(Nil,
(b:B, cs:List[C]) => concatenate(g(b), cs))
}
def concatenate[A](left: List[A], right: List[A]): List[A] =
left match {
case Nil => right
case Cons(head, tail) => Cons(head, concatenate(tail, right))
}
}
11. // Tests for Option monad
assert( join(Some(Some(3))) == Some(3) )
val increment: Int => Int = n => n + 1
assert( (Some(3) map increment) == Some(4) )
val double: Int => Option[Int] =
n => if (n % 2 == 1) Some(n * 2) else None
val square: Int => Option[Int] =
n => if (n < 100) Some(n * n) else None
assert( (double >=> square)(3) == Some(36))
val result =
for {
six <- double(3)
thirtySix <- square(six)
} yield six + thirtySix
assert(result == Some(42))
// Tests for List monad
assert( join(Cons(
Cons(1, Cons(2, Nil)),
Cons(
Cons(3, Cons(4, Nil)),
Nil))
) == Cons(1, Cons(2, Cons(3, Cons(4, Nil))) ) )
val increment: Int => Int = n => n + 1
assert( (Cons(1, Cons(2, Cons(3, Cons(4, Nil))) ) map increment)
== Cons(2, Cons(3, Cons(4, Cons(5, Nil))) ) )
val double: Int => List[Int] = n => Cons(n, Cons(n * 2, Nil))
val square: Int => List[Int] = n => Cons(n, Cons(n * n, Nil))
assert( (double >=> square)(3) == Cons(3,Cons(9,Cons(6,Cons(36, Nil)))))
val result =
for {
x <- double(3)
y <- square(x)
} yield Cons(x, Cons(y, Nil))
assert(result == Cons(
Cons(3,Cons(3,Nil)),
Cons(
Cons(3,Cons(9,Nil)),
Cons(
Cons(6,Cons(6,Nil)),
Cons(
Cons(6,Cons(36,Nil)),
Nil)))))
12. Next, we are going to look at the Kleisli composition functions of Id, Option
and List to see how each of them discharges its compositional responsibilities.
@philip_schwarz
13. In the special case of the Identity monad, which does nothing, the compositional responsibilities are discharged in a degenerate and
curious way:
1) use f to compute a first value wrapped in a functional effect
just call f
f(a)
2) dig underneath the wrapper to access the first value, discarding the wrapper
digging under the wrapper simply amounts to asking the resulting Id[B] for the B that it is wrapping
f(a).value
3) use g to compute, using the first value, a second value also wrapped in a functional effect
just call g with the first value
g(f(a).value)
4) return a third value wrapped in a functional effect that represents the composition (combination) of the first two functional effects
because the effect of the Id monad is nonexistent, there simply is nothing to combine, so just return the second value
g(f(a).value)
implicit class IdFunctionOps[A,B](f: A => Id[B]) {
def >=>[C](g: B => Id[C]): A => Id[C] =
a => g(f(a).value)
}
14. Next, let’s look at how the compositional responsibilities are discharged in the Option monad:
1) use f to compute a first value wrapped in a functional effect
just call f
f(a)
2) dig underneath the wrapper to access the first value, discarding the wrapper
digging under the wrapper and discarding it is done by pattern matching, destructuring Option[B] to get the wrapped B value
Some(b)
3) use g to compute, using the first value, a second value also wrapped in a functional effect
just call g with the first value
g(b)
4) return a third value wrapped in a functional effect that represents the composition (combination) of the first two functional effects
If the 1st effect is that a value is defined then the 3rd value is just the 2nd value and composition of the 1st effect with the 2nd effect is
just the 2nd effect
case Some(b) => g(b)
If the 1st effect is that no value is defined then there is no 3rd value as the composition of the 1st and 2nd effects is just the 1st effect
case None => None
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
}
}
15. Let’s now look at how the compositional responsibilities are discharged in the List monad:
1) use f to compute a first value wrapped in a functional effect
just call f – the first value consists of the B items in the resulting List[B]
f(a)
2) dig underneath the wrapper to access the first value, discarding the wrapper
digging under the wrapper and discarding it is done by foldRight, which calls its callback function with each B item in the first value
f(a).foldRight(Nil, (b:B, cs:List[C]) => concatenate(g(b), cs))
3) use g to compute, using the first value, a second value also wrapped in a functional effect
callback function g is called with each B item in the first value, so the second value consists of all List[C] results returned by g
(b:B, …) => …(g(b), …))
4) return a third value wrapped in a functional effect that represents the composition (combination) of the first two functional effects
If the 1st effect is that there are no B items then there are no 2nd and 3rd values and the composition of 1st and 2nd effect is also that
there are no items
f(a) is Nil so f(a).foldright(…) is also Nil
otherwise the 1st effect is the multiplicity of items in the 1st value, the 2nd effect is the multiplicity of items in the 2nd value, the 3rd
value is the concatenation of all the List[C] results returned by g, and the composition of the 1st and 2nd effects is the multiplicity
of items in the concatenation
f(a).foldRight(Nil, (b:B, cs:List[C]) => concatenate(g(b), cs))
implicit class ListFunctionOps[A,B](f: A => List[B]) {
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(Nil, (b:B, cs:List[C]) => concatenate(g(b), cs))
}
def foldRight[B](b: B,
f:(A, B) => B): B =
this match {
case Nil => b
case Cons(a, tail) =>
f(a, tail.foldRight(b, f))
}
def concatenate[A](left: List[A],
right: List[A]): List[A] =
left match {
case Nil =>
right
case Cons(head, tail) =>
Cons(head, concatenate(tail, right))
}
16. What we have done so far is take three monads and define them in terms of Kleisli composition and unit.
In the next three slides we are going to refactor the three monads so that they are defined in terms of
flatMap and unit and see how the compositional responsibilities get redistributed.@philip_schwarz
17. COMPOSITIONAL RESPONSIBILITY
1. use f to compute a first value wrapped in a functional effect
2. dig underneath the wrapper to access the first value, discarding the wrapper
3. use g to compute, using the first value, a second value also wrapped in a functional effect
4. return a third value wrapped in a functional effect that represents the composition (combination) of the first two functional effects
LOCATION CHANGE
remains in >=>
moves from >=> to flatMap
moves from >=> to flatMap
moves from >=> to flatMap
Id monad defined in terms of Kleisli composition and unit Id monad defined in terms of flatMap and unit
dig underneath wrapper
invoke 2nd function
discard wrapper
invoke 1st function
compose effects
dig underneath wrapper
invoke 2nd function
discard wrapper
compose effects
invoke 1st function
18. Option monad defined in terms of Kleisli composition and unit Option monad defined in terms of flatMap and unit
dig underneath wrapper
invoke 2nd function
discard wrapper
invoke 1st function
compose effects
dig underneath wrapper
invoke 2nd function discard wrapper
invoke 1st function
compose effects
19. List monad defined in terms of Kleisli composition and unit List monad defined in terms of flatMap and unit
invoke 2nd function
invoke 1st function dig underneath wrapper discard wrappercompose effects
dig underneath wrapper
invoke 2nd function
discard wrapper
invoke 1st function
compose effects
20. And finally, we are going to refactor the three monads so that they are defined in terms of map,
join and unit and again see how the compositional responsibilities get redistributed.
@philip_schwarz
21. COMPOSITIONAL RESPONSIBILITY
1. use f to compute a first value wrapped in a functional effect
2. dig underneath the wrapper to access the first value, discarding the wrapper
3. use g to compute, using the first value, a second value also wrapped in a functional effect
4. return a third value wrapped in a functional effect that represents the composition (combination) of the first two functional effects
LOCATION CHANGE
remains in >=>
moves from flatMap to map/join
moves from flatMap to map
moves from flatMap to join
Id monad defined in terms of flatMap and unit Id monad defined in terms of map, join and unit
dig underneath wrapper
invoke 2nd function
discard wrapper
compose effects
invoke 1st function
discard wrapper
compose effects
invoke 2nd function
invoke 1st function
dig underneath wrapper
22. Option monad defined in terms of flatMap and unit Option monad defined in terms of map, join and unit
c
discard wrapper
compose effects
dig underneath wrapper
invoke 2nd function
discard wrapper
compose effects
invoke 1st function
invoke 2nd function
dig underneath wrapper
invoke 1st function
23. c
List monad defined in terms of flatMap and unit List monad defined in terms of map, join and unit
dig underneath wrapper
invoke 2nd function
discard wrapper
compose effects
invoke 1st function
invoke 2nd function
dig underneath wrapper
invoke 1st function discard wrapper
compose effects
24. See the following slide deck for
the list of all available decks in
the MONAD FACT series
https://www.slideshare.net/pjschwarz