(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Functional Programming in JavaScript by Luis AtencioLuis Atencio
This document provides an overview of functional programming concepts using JavaScript. It discusses thinking functionally by avoiding side effects, writing declaratively, and ensuring functions always return values. Functional techniques like currying, composition, and memoization are explained. It also covers paradigms like referential transparency and the Liskov substitution principle. The document discusses how JavaScript supports functional programming with features like closures and higher-order functions. Common libraries for functional programming in JavaScript are listed. Finally, the document covers advanced topics like functors, monads, and how they can be used for error handling.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
The document discusses functional programming concepts like higher-order functions, function composition, currying, and lazy evaluation. It provides examples of implementing strategies like converting between units using functions and creating streams of prime numbers lazily to avoid stack overflows. Tail call optimization is mentioned as a way to avoid stack overflows with recursive functions.
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
This document discusses domain modeling in a functional world based on the speaker's real life experiences. The speaker covers topics like immutability and algebraic data types, updating domain models functionally using lenses, type classes for domain modeling, and managing states functionally. The speaker advocates for isolating pure domain logic from side effects to make the logic easier to test, reason about, and parallelize. Functional composition is emphasized as a way to build complex abstractions from simpler ones.
(Video of these slides here http://fsharpforfunandprofit.com/rop)
(My response to "this is just Either" here: http://fsharpforfunandprofit.com/rop/#monads)
Many examples in functional programming assume that you are always on the "happy path". But to create a robust real world application you must deal with validation, logging, network and service errors, and other annoyances.
So, how do you handle all this in a clean functional way? This talk will provide a brief introduction to this topic, using a fun and easy-to-understand railway analogy.
(Video and code at https://fsharpforfunandprofit.com/pipeline/)
Passing data through a pipeline of transformations is an alternative approach to classic OOP. The LINQ methods in .NET are designed around this, but the pipeline approach can be used for so much more than manipulating collections.
In this talk, I'll look at pipeline-oriented programming and how it relates to functional programming, the open-closed principle, unit testing, the onion architecture, and more. I'll finish up by showing how you can build a complete web app using only this approach.
Functional programming can be an excellent approach to designing decoupled, reusable systems with a rich domain model. In fact, the lessons from applying DDD in a functional language translate well to object-oriented programming.
The document provides an overview of RecyclerView in Android, including:
1. RecyclerView components like LayoutManager, Adapter, ItemDecoration, and ItemAnimator and examples of how to set them up.
2. How to create ViewHolders and Adapters to display data in RecyclerView.
3. Techniques for handling click listeners and displaying multiple view types.
4. Examples of using item decorations and animators.
5. Recommended resources for further learning about RecyclerView.
(Video and code at http://fsharpforfunandprofit.com/composition)
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
This document discusses JavaScript variables, functions, and objects. It covers JavaScript datatypes like numbers, strings, and objects. It describes variable scope and how variables are hoisted or moved to the top of their function. It also discusses how functions can be defined and used as variables. Global objects like the window object are described. Finally, it provides examples of defining basic functions and using objects with properties and methods.
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard LibraryDongMin Choi
Microsoft Melting Pot
C++ Korea 2nd Seminar
Ranges for The Cpp Standard Library
https://channel9.msdn.com/Events/Channel9-Korea/cplusplus/Ranges-for-The-C-Standard-Library
Domain Driven Design with the F# type System -- NDC London 2013Scott Wlaschin
(Video of these slides here http://fsharpforfunandprofit.com/ddd)
Statically typed functional programming languages like F# encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers.
Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time.
In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Code, links to video, etc., at http://fsharpforfunandprofit.com/ddd
For more on DDD and F# see:
http://fsharpforfunandprofit.com/ddd/
http://tomasp.net/blog/type-first-development.aspx/
http://gorodinski.com/blog/2013/02/17/domain-driven-design-with-fsharp-and-eventstore/
The document provides idiomatic Kotlin coding style guidelines and best practices for expressions, classes, functions, and the standard library. Some key recommendations include using 'when' and 'try' as expression bodies, avoiding classes just for functions, extracting non-essential APIs to extensions, using data classes, type aliases, and destructuring declarations, and leveraging functions like 'apply', 'filterIsInstance', and 'groupBy' from the standard library. Overall the document advises organizing code in a concise and functional way that fully utilizes Kotlin language features.
The document provides information on object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It defines classes like Shape, Rectangle, Circle and Triangle to demonstrate these concepts. It also discusses Java data types, constructors, access modifiers, interfaces and abstract classes.
(video and more at http://fsharpforfunandprofit.com/fppatterns)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID. The functional programming community has design patterns and principles as well. This talk will provide an overview of some of these patterns (such as currying, monads), and present some demonstrations of FP design in practice. We'll also look at some of the ways you can use these patterns as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
The document provides an overview of Kotlin collections including lists, sets, and maps. It discusses collection interfaces like List, Set, and Map and their characteristics. The document then demonstrates various operations that can be performed on collections like filtering, mapping, partitioning, zipping, associating, and more through examples. It also compares the differences between iterables and sequences in Kotlin.
Lieven DOCLO gave a presentation on implementing Clean Architecture. Clean Architecture advocates separating domains, applications, and interfaces into separate layers. This allows the inner layers to be independent of the outer layers and frameworks. The presentation demonstrated creating building-related use cases and domain models, implementing repositories, and exposing use cases through REST endpoints. It discussed issues like decoupling tradeoffs, pragmatic compromises, and applying Clean Architecture to legacy projects.
Designing an extensible, flexible schema that supports user customization is a common requirement, but it's easy to paint yourself into a corner.
Examples of extensible database requirements:
- A database that allows users to declare new fields on demand.
- Or an e-commerce catalog with many products, each with distinct attributes.
- Or a content management platform that supports extensions for custom data.
The solutions we use to meet these requirements is overly complex and the performance is terrible. How should we find the right balance between schema and schemaless database design?
I'll briefly cover the disadvantages of Entity-Attribute-Value (EAV), a problematic design that's an example of the antipattern called the Inner-Platform Effect, That is, modeling an attribute-management system on top of the RDBMS architecture, which already provides attributes through columns, data types, and constraints.
Then we'll discuss the pros and cons of alternative data modeling patterns, with respect to developer productivity, data integrity, storage efficiency and query performance, and ease of extensibility.
- Class Table Inheritance
- Serialized BLOB
- Inverted Indexing
Finally we'll show tools like pt-online-schema-change and new features of MySQL 5.6 that take the pain out of schema modifications.
The document provides an overview of JavaScript design patterns including creational, structural, and behavioral patterns. It discusses common patterns like the module pattern, prototype pattern, factory pattern, decorator pattern, observer pattern, and more. Code examples are provided to demonstrate how each pattern works in JavaScript.
Let's make a contract: the art of designing a Java APIMario Fusco
The document discusses best practices for designing Java APIs. It emphasizes making APIs intuitive, consistent, discoverable and easy to use. Some specific tips include using static factories to create objects, promoting fluent interfaces, using the weakest possible types, supporting lambdas, avoiding checked exceptions and properly managing resources using try-with-resources. The goal is to design APIs that are flexible, evolvable and minimize surprises for developers.
Towards Functional Programming through Hexagonal ArchitectureCodelyTV
Slides of for the talk "Towards Functional Programming through Hexagonal Architecture" delivered at the Software Crafters Barcelona 2018 conference #scbcn18 by Juanma Serrano from Habla Computing and Javier Ferrer from CodelyTV
(Video available at https://fsharpforfunandprofit.com/composition/)
Composition is a fundamental building block of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with some basic examples, and ending with a complete (object-free!) web application.
The Fuss about || Haskell | Scala | F# ||Ashwin Rao
The document discusses functional programming languages Haskell, Scala, and F# and their advantages over imperative programming. It notes they encourage a different problem-solving approach using concepts like immutable values, recursion, and avoiding side effects. Specific features highlighted include static typing with type inference, algebraic data types, pattern matching, and monads for controlling program flow and errors in a functional way. Examples show equivalent algorithms in different languages to demonstrate these concepts.
This slide contains short introduction to different elements of functional programming along with some specific techniques with which we use functional programming in Swift.
(Video and code at http://fsharpforfunandprofit.com/composition)
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
This document discusses JavaScript variables, functions, and objects. It covers JavaScript datatypes like numbers, strings, and objects. It describes variable scope and how variables are hoisted or moved to the top of their function. It also discusses how functions can be defined and used as variables. Global objects like the window object are described. Finally, it provides examples of defining basic functions and using objects with properties and methods.
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard LibraryDongMin Choi
Microsoft Melting Pot
C++ Korea 2nd Seminar
Ranges for The Cpp Standard Library
https://channel9.msdn.com/Events/Channel9-Korea/cplusplus/Ranges-for-The-C-Standard-Library
Domain Driven Design with the F# type System -- NDC London 2013Scott Wlaschin
(Video of these slides here http://fsharpforfunandprofit.com/ddd)
Statically typed functional programming languages like F# encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers.
Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time.
In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Code, links to video, etc., at http://fsharpforfunandprofit.com/ddd
For more on DDD and F# see:
http://fsharpforfunandprofit.com/ddd/
http://tomasp.net/blog/type-first-development.aspx/
http://gorodinski.com/blog/2013/02/17/domain-driven-design-with-fsharp-and-eventstore/
The document provides idiomatic Kotlin coding style guidelines and best practices for expressions, classes, functions, and the standard library. Some key recommendations include using 'when' and 'try' as expression bodies, avoiding classes just for functions, extracting non-essential APIs to extensions, using data classes, type aliases, and destructuring declarations, and leveraging functions like 'apply', 'filterIsInstance', and 'groupBy' from the standard library. Overall the document advises organizing code in a concise and functional way that fully utilizes Kotlin language features.
The document provides information on object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It defines classes like Shape, Rectangle, Circle and Triangle to demonstrate these concepts. It also discusses Java data types, constructors, access modifiers, interfaces and abstract classes.
(video and more at http://fsharpforfunandprofit.com/fppatterns)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID. The functional programming community has design patterns and principles as well. This talk will provide an overview of some of these patterns (such as currying, monads), and present some demonstrations of FP design in practice. We'll also look at some of the ways you can use these patterns as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
The document provides an overview of Kotlin collections including lists, sets, and maps. It discusses collection interfaces like List, Set, and Map and their characteristics. The document then demonstrates various operations that can be performed on collections like filtering, mapping, partitioning, zipping, associating, and more through examples. It also compares the differences between iterables and sequences in Kotlin.
Lieven DOCLO gave a presentation on implementing Clean Architecture. Clean Architecture advocates separating domains, applications, and interfaces into separate layers. This allows the inner layers to be independent of the outer layers and frameworks. The presentation demonstrated creating building-related use cases and domain models, implementing repositories, and exposing use cases through REST endpoints. It discussed issues like decoupling tradeoffs, pragmatic compromises, and applying Clean Architecture to legacy projects.
Designing an extensible, flexible schema that supports user customization is a common requirement, but it's easy to paint yourself into a corner.
Examples of extensible database requirements:
- A database that allows users to declare new fields on demand.
- Or an e-commerce catalog with many products, each with distinct attributes.
- Or a content management platform that supports extensions for custom data.
The solutions we use to meet these requirements is overly complex and the performance is terrible. How should we find the right balance between schema and schemaless database design?
I'll briefly cover the disadvantages of Entity-Attribute-Value (EAV), a problematic design that's an example of the antipattern called the Inner-Platform Effect, That is, modeling an attribute-management system on top of the RDBMS architecture, which already provides attributes through columns, data types, and constraints.
Then we'll discuss the pros and cons of alternative data modeling patterns, with respect to developer productivity, data integrity, storage efficiency and query performance, and ease of extensibility.
- Class Table Inheritance
- Serialized BLOB
- Inverted Indexing
Finally we'll show tools like pt-online-schema-change and new features of MySQL 5.6 that take the pain out of schema modifications.
The document provides an overview of JavaScript design patterns including creational, structural, and behavioral patterns. It discusses common patterns like the module pattern, prototype pattern, factory pattern, decorator pattern, observer pattern, and more. Code examples are provided to demonstrate how each pattern works in JavaScript.
Let's make a contract: the art of designing a Java APIMario Fusco
The document discusses best practices for designing Java APIs. It emphasizes making APIs intuitive, consistent, discoverable and easy to use. Some specific tips include using static factories to create objects, promoting fluent interfaces, using the weakest possible types, supporting lambdas, avoiding checked exceptions and properly managing resources using try-with-resources. The goal is to design APIs that are flexible, evolvable and minimize surprises for developers.
Towards Functional Programming through Hexagonal ArchitectureCodelyTV
Slides of for the talk "Towards Functional Programming through Hexagonal Architecture" delivered at the Software Crafters Barcelona 2018 conference #scbcn18 by Juanma Serrano from Habla Computing and Javier Ferrer from CodelyTV
(Video available at https://fsharpforfunandprofit.com/composition/)
Composition is a fundamental building block of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with some basic examples, and ending with a complete (object-free!) web application.
The Fuss about || Haskell | Scala | F# ||Ashwin Rao
The document discusses functional programming languages Haskell, Scala, and F# and their advantages over imperative programming. It notes they encourage a different problem-solving approach using concepts like immutable values, recursion, and avoiding side effects. Specific features highlighted include static typing with type inference, algebraic data types, pattern matching, and monads for controlling program flow and errors in a functional way. Examples show equivalent algorithms in different languages to demonstrate these concepts.
This slide contains short introduction to different elements of functional programming along with some specific techniques with which we use functional programming in Swift.
This document discusses functional domain-driven design and the use of monads. It begins by stating that functional domain-driven design is still a work in progress. It then provides definitions of monads and functions as they relate to category theory. The document discusses how monads can be used with a functional approach to domain-driven design. It also includes brief biographical information about the software developer who posted this content.
This document introduces elm-d3, a library for building D3 visualizations in Elm. It discusses modeling D3 operations as Elm values and composing them functionally. Basic D3 operations like select, attr, and data binding are defined. Operations can be combined using method chaining and sequencing to build more complex behaviors. This allows defining D3 views in Elm idiomatically using types and composition. Examples show defining reusable operations on selections and widgets for data binding to build interactive visualizations.
This document provides an overview of functional programming with Haskell. It discusses key concepts of functional programming like immutable data structures and pure functions. It introduces Haskell types including basic types, tuples, lists, data types, and type classes. It covers Haskell functions like pattern matching, guards, and higher order functions. It also discusses Haskell concepts like laziness, currying, and polymorphism. Finally, it provides an introduction to monads in Haskell and discusses Haskell tools, frameworks, and performance.
This document provides an overview of the C++ programming language. It discusses that C++ is a statically typed, compiled language that supports procedural and object-oriented programming. C++ was developed in 1979 by Bjarne Stroustrup as an enhancement to C with object-oriented capabilities. The document then covers various C++ concepts like data types, operators, program structure, and differences between C and C++.
This document describes stacks and queues data structures and their application programming interfaces (APIs). It defines the common operations for stacks and queues, including push, pop, enqueue, and dequeue. It provides examples of using stacks and queues to evaluate postfix expressions and read input from a queue. Stacks and queues are widely used in applications like browsers, interpreters, and printing. The document also covers generics, autoboxing/unboxing, and real-world examples of stacks in programming languages and PostScript.
A brief introduction to functional programming.
Even if slides present some simple Python code, functional programming patterns applies to other languages too.
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
This document discusses various Yin-Yang concepts in software development, including:
- Effort and knowledge, theory and practice, design for manufacturing and design for assembly represent opposing yet interconnected concepts.
- Programs (E-programs) built on simpler programs (S-programs) balance ease of use and performance.
- Designing for both short-term efficiency and long-term evolvability requires balancing opposing priorities.
- Many software development processes involve balancing logical thinking with creative control, and reducing complexity through modularity.
The document discusses C++ functions. It defines what functions are and their uses in breaking down problems into smaller tasks. There are two types of functions: standard functions that are part of the C++ language and user-defined functions. A function has a signature defining its return type and parameters. Functions are declared and defined in two steps - declaration and implementation. Data can be shared between functions through parameters, which come in two varieties: value parameters that copy argument values, and reference parameters that can modify the original argument values.
The document discusses functors, applicatives, and monads in Haskell. It provides examples of how functors allow lifting functions to work on container types like Maybe and Logger using fmap. Applicatives allow applying functions to multiple arguments within a container using <*>. Monads generalize applicatives by allowing chained computations through >>= and return, handling context and effects like logging.
Functional Programming and Haskell - TWBR Away Day 2011Adriano Bonat
Explains why functional programming is back and shows some features from Haskell that are being ported to other languages. Presented at ThoughtWorks Brazil Away Day 2011.
This document discusses monads in functional programming. It provides examples of optionals, arrays, and functions in Swift that exhibit monadic properties. It then defines monads more formally and describes some common monad types like the writer, reader, and IO monads. It shows how monads allow encapsulating effects like logging or environment variables while preserving referential transparency. The document concludes by discussing potential applications of monads to mobile apps.
The document discusses functions and static variables in C++. It covers topics like:
- Creating functions, invoking functions, and passing arguments to functions.
- Determining the scope of local and global variables.
- Understanding the differences between pass-by-value and pass-by-reference.
- Using function overloading and dealing with ambiguous overloading.
- Using function prototypes for declaring function headers.
- Knowing how to use default arguments.
- Static variables.
This document provides an overview of functional programming concepts in Java including lambda expressions, functional interfaces like Function and Consumer, streams, and the Optional API. It discusses how these features allow expressing operations like mapping, filtering, reducing in a more declarative way. The document also mentions topics for further exploration like currying, monads, dependency injection and the future of design patterns with functional programming.
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
SubScript - это расширение языка Scala, добавляющее поддержку конструкций и синтаксиса аглебры общающихся процессов (Algebra of Communicating Processes, ACP). SubScript является перспективным расширением, применимым как для разработки высоконагруженных параллельных систем, так и для простых персональных приложений.
Domain Modeling Made Functional (DevTernity 2022)Scott Wlaschin
(video at https://fsharpforfunandprofit.com/ddd/)
Statically typed functional programming languages encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers. Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time. In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Building confidence in concurrent code with a model checker: TLA+ for program...Scott Wlaschin
As developers, we have a number of well-known practices to ensure code quality, such as unit tests, code review and so on. But these practices often break down when we need to design concurrent systems. Often, there can be subtle and serious bugs that are not found with conventional practices.
But there’s another approach that you can use -- model-checking -- that can detect potential concurrency errors at design time, and so dramatically increase your confidence in your code. In this talk, I’ll demonstrate and demystify TLA+, a powerful design and model-checking system. We’ll see how it can check your concurrent designs for errors, saving you time up front and frustration later!
The lazy programmer's guide to writing thousands of testsScott Wlaschin
We are all familiar with example-based testing, as typified by TDD and BDD, where each test is hand-crafted.
But there's another approach to writing tests. In the "property-based testing" approach, a single test is run hundreds of times with randomly generated inputs. Property-based testing is a great way to find edge cases, and also helps you to understand and document the behavior of your code under all conditions.
This talk will introduce property-based testing, show you how it works, and demonstrate why you should consider adding this powerful technique to your toolbelt.
Reinventing the Transaction Script (NDC London 2020)Scott Wlaschin
The Transaction Script pattern organizes business logic as a single procedure. It has always been considered less sophisticated and flexible than a layered architecture with a rich domain model. But is that really true?
In this talk, we'll reinvent the Transaction Script using functional programming principles. We'll see that we can still do domain-driven design, and still have code which is decoupled and reusable, all while preserving the simplicity and productivity of the original one-script-per-workflow approach.
The Functional Programmer's Toolkit (NDC London 2019)Scott Wlaschin
(slides and video at https://fsharpforfunandprofit.com/fptoolkit)
The functional programming community has a number of patterns with strange names such as monads, monoids, functors, and catamorphisms.
In this beginner-friendly talk, we'll demystify these techniques and see how they all fit together into a small but versatile "tool kit".
We'll then see how the tools in this tool kit can be applied to a wide variety of programming problems, such as handling missing data, working with lists, and implementing the functional equivalent of dependency injection.
Domain Modeling Made Functional (KanDDDinsky 2019)Scott Wlaschin
(video at https://fsharpforfunandprofit.com/ddd/)
Statically typed functional programming languages encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers. Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time. In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
The Functional Programming Toolkit (NDC Oslo 2019)Scott Wlaschin
(slides and video at https://fsharpforfunandprofit.com/fptoolkit)
The techniques and patterns used in functional programming are very different from object-oriented programming, and when you are just starting out it can be hard to know how they all fit together.
In this big picture talk for FP beginners, I'll present some of the common tools that can be found in a functional programmer's toolbelt; tools such as "map", "apply", "bind", and "sequence". What are they? Why are they important? How are they used in practice? And how do they relate to scary sounding concepts like functors, monads, and applicatives?
Four Languages From Forty Years Ago (NewCrafts 2019)Scott Wlaschin
(More info and video at fsharpforfunandprofit.com/fourfromforty)
The 1970's were a golden age for new programming languages, but do they have any relevance to programming today? Can we still learn from them?
In this talk, we'll look at four languages designed over forty years ago -- SQL, Prolog, ML, and Smalltalk -- and discuss their philosophy and approach to programming, which is very different from most popular languages today.
We'll come away with some practical principles that are still very applicable to modern development. And you might discover your new favorite programming paradigm!
(More info and video at fsharpforfunandprofit.com/fourfromforty)
The 1970's were a golden age for new programming languages, but do they have any relevance to programming today? Can we still learn from them?
In this talk, we'll look at four languages designed over forty years ago -- SQL, Prolog, ML, and Smalltalk -- and discuss their philosophy and approach to programming, which is very different from most popular languages today.
We'll come away with some practical principles that are still very applicable to modern development. And you might discover your new favorite programming paradigm!
(Video and more at fsharpforfunandprofit.com/csharp)
Curious about F# and want to understand how is it different from C#?
In this talk, we'll look at the basics of coding in F#, and how functional programming differs from object-oriented programming. Along the way, there will be many examples showing the same code written in C# and F# so that you can see for yourself how the two languages differ in style and approach.
(Video and code available at http://fsharpforfunandprofit.com/cap)
In this talk I'll look at a unusual approach to designing internal interfaces and external APIs -- a "capability-based" approach that takes the Principle Of Least Authority and applies it to software design.
When this approach is used, it produces a robust and modular design which captures the domain constraints, resulting in an API which is self-documenting and hard to misuse.
I'll demonstrate how to design and implement a capability based approach, how capabilities can be quickly combined and restricted easily, and how capabilities are a natural fit with a REST API that uses HATEOAS.
(Video and code available at http://fsharpforfunandprofit.com/turtle)
In this fast-paced talk, I'll start with the well known API for turtle graphics, and then stretch it to the breaking point by creating 13 different implementations, each demonstrating a different functional programming technique.
Along the way, we'll use partial application, functional dependency injection, validation
with Success/Failure results, the Either monad, the State monad, agents with message queues, event sourcing, stream processing, capability-based design, and the interpreter pattern (aka free monad). Phew!
(Demo code and video available at http://fsharpforfunandprofit.com/cap/)
We all want to produce modular and robust code that is easy to test and refactor, and we have design principles such as SOLID that help us do that.
In this talk I'll look at a very different approach to design using "capabilities" and the principle of least authority. I'll show how using these design techniques throughout your core domain (and not just at your API boundary) also leads to well-designed and modular code.
I'll demonstrate how to design and use a capability based approach, how capabilities can be quickly combined and restricted easily, and how capabilities are a natural fit with a REST API that uses HATEAOS.
(Video available at http://fsharpforfunandprofit.com/monadster/)
You've got a pile of assorted functions lying around. Each one is useful and reliable, but they just don't fit together properly. How can you assemble them into a complete system that can stand on its own two feet and terrorize the local villagers?
In this session, I'll show how functional programming can transform all sorts of existing code into shapes that are plug-compatible and which can be bolted together effortlessly.
SAFETY NOTE: The techniques demonstrated are perfectly harmless and can even be used at your workplace -- no lightning bolts required.
Video and related blog posts at fsharpforfunandprofit.com/ettt
Follow along as I ridiculously over-engineer a simple game to demonstrate how functional programming can be used to create a real-world "enterprise-ready" application.
Topics covered include: encoding business rules into types, data hiding with parametric polymorphism, using functions for capability-based security, exposing a REST API with HATEAOS, the functional approach to logging, actors, scalability and more.
Video and more content at fsharpforfunandprofit.com/pbt
"The lazy programmer's guide to writing 1000's of tests: An introduction to property based testing"
We are all familiar with example-based testing, as typified by TDD and BDD. Property-based testing takes a very different approach, where a single test is run hundreds of times with randomly generated inputs.
Property-based testing is a great way to find edge cases, and also helps you to understand and document the behaviour of your code under all conditions.
This talk will introduce property-based testing and show how it works, and why you should consider adding it to your arsenal of testing tools.
The document compares the Swift programming language to an unknown language X, describing various features and capabilities. It poses questions about language X that hint it is focused on cross-platform development, open source, safety, and functional programming. It is eventually revealed that language X is F#, and provides links to learn more about F# and its use for both front-end and back-end development across platforms like iOS, Android, and Azure.
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
(Video of these slides here http://fsharpforfunandprofit.com/ddd)
Statically typed functional programming languages like F# encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers.
Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time.
In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Code, links to video, etc., at http://fsharpforfunandprofit.com/ddd
NEW AND IMPROVED - added sections on:
* why OO, not FP is scary
* designing with states and transitions
This document discusses the key concepts of domain-driven design (DDD) including bounded contexts, ubiquitous language, entities, aggregates, repositories, services, anti-corruption layers, and continuous integration. It emphasizes that DDD focuses on modeling the core domain and collaboratively developing a shared language within and across bounded contexts to ensure alignment between technical and business goals.
TVersity Pro Media Server Free CRACK Downloadmohsinrazakpa43
🌍📱👉COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page👈🌍
TVersity Pro Media Server CRACK is an awesome application that has been developed which will help you detect and share multimedia files on the Internet. With this stellar application you can play as well as record online audio/video content.
Managing Changing Data with FME Part 1 - Compare & DetectSafe Software
Data changes are inevitable, but keeping up doesn’t have to be a struggle. Are you still manually tracking updates or managing unwieldy scripts? That’s a time-sink. Automate change detection with FME and ensure your data stays up-to-date – without the hassle.
Discover how FME’s powerful transformers, like the ChangeDetector, can compare and detect changes to your data, automating incremental updates to keep your data warehouse and other systems synchronized in real-time.
While many tools can achieve this, they often lack support for spatial data or require complex, time-consuming processes. With FME, you get a flexible, intuitive platform that supports all data types, making change detection simple and efficient.
Join this webinar to learn change management strategies from demos that include:
- Detecting changes in your data
- Detecting changes in spatial data
- Incremental updates and data synchronization
- and more!
With FME, change is no longer something to fear. Because no matter what type of data you have, or at what stage it is in your workflow, FME makes working with change easy.
* This is part 1 of a 2-part series on managing changing data with FME. Stay tuned for Part 2 in the weeks to follow, where we’ll cover further change-detection methods like database triggers and transaction logs!
Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...AxisTechnolabs
📊Ready to download Multicompany supported odoo dashboard module for analytic POS, Sales, CRM, Inventory and Accounting data in graphical view.
➡️Visit And Buy Now : https://bit.ly/4hJBHCp
➡️Lets checkout some important features of multi company odoo dashboard app:📊
✅Key features of multi company odoo dashboard📊:
➡️Major Chart Types supported odoo dashboard
➡️Multiple language supported odoo dashboard
➡️User friendly interface
➡️Date filter options for check data
➡️Pre-define dashboard layout template
And more ...
👉Just visit our below odoo app link🔗 and explore more new features of multicompany dashboard odoo module
➡️App download now :👇
Odoo 18 : https://bit.ly/4hJBHCp
Odoo 17 : https://bit.ly/3TK4iOf
Odoo 16 : https://bit.ly/3Wr85yO
Odoo 15 : https://bit.ly/3Gf8YS3
Odoo 14 : https://bit.ly/3ueeORu
Odoo 13 : https://bit.ly/3rbYNto
Odoo 12 : https://bit.ly/3s6VWRt
👉Our more #odooapps: https://bit.ly/3oFIOCF
✅Ask for DEMO: 📩business@axistechnolabs.com
👉Contact Us For odoo Services : https://bit.ly/3K6e6vi
✅For more discussion : 🌐 https://www.axistechnolabs.com
➡️ 🌍📱👉COPY & PASTE LINK👉👉👉 https://forum-up.org/download-now/
Wondershare Filmora 14.3.2 Crack is an excellent software for video editing. It is beneficial in perfect video editing with industry standards.
Wondershare Filmora Crack 2025 For Windows Freemohsinrazakpa43
🌍📱👉COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page👈🌍
Video Editing Simplified - Ignite Your Story. A powerful and intuitive video editing experience. Filmora 10hash two new ways to edit: Action Cam Tool (Correct lens distortion, Clean up your audio, New speed controls) and Instant Cutter (Trim or merge clips quickly, Instant export).
IObit Driver Booster Pro 12.3.0.557 Freeblouch51kp
🌍📱👉COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page👈🌍
For your Windows system to perform well, software and hardware need to work together. Therefore, it is necessary to update device drivers regularly so that they always function properly. Driver Booster 6 checks and updates over 2,500,000+ device drivers from Intel, Nvidia, AMD, etc., to help you reduce system freezing and crashing.
Parallels Desktop full version o🌍📱👉COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page👈🌍fflininstaller for macOS. It runs Windows and Mac applications side by side.It allows you to run Windows and Mac applications side by side. Choose your view to make Windows invisible while still using its applications, or keep your Mac's familiar Windows background and controls.
Imagine a world where you can respond instantly to any customer, anytime, anywhere.
Improve user satisfaction on every channel. With Jotform AI Agents, you can streamline your customer service processes. Easily train your agent with your company data, identify the common questions you receive and your answers. Let your agent handle the rest.
Learn more about the benefits of Jotform AI Agents with this slide. For more information, visit https://www.jotform.com/ai/agents/
🌍📱👉COPY LINK & PASTE ON GOOGLE👈https://up-community.wiki/ds/ 🌍
Wondershare Dr.Fone Crack is a comprehensive mobile phone management and recovery software designed to help users recover lost data, repair system issues, and manage mobile devices. It supports both Android and iOS platforms, offering a wide range of features aimed at restoring files, repairing software problems, and backing up or transferring data.
RocketVideos AI – The Ultimate AI Video Creation ToolRichmaven
Welcome to the complete walkthrough of RocketVideosAi, the cutting-edge, AI-powered tool that's transforming the way creators, marketers, and businesses produce high-quality videos—without the hassle of manual editing or expensive software.
In this SlideShare, we’ll dive deep into how RocketVideosAi helps you turn simple ideas into cinematic, scroll-stopping videos in just minutes. Whether you're a content creator, educator, advertiser, or entrepreneur, RocketVideosAi is designed to simplify your workflow and supercharge your content strategy!
🔍 What You’ll Learn in This Presentation:
✅ What is RocketVideosAi and how does it work
✅ Key features including AI storyboard, voiceovers, character animation & more
✅ How to create videos in 3 easy steps
✅ Who should use RocketVideosAi and why
✅ Complete pricing breakdown & OTOs (One-Time Offers)
✅ Bonuses worth over $50,000
✅ Pros, cons, and final verdict
💡 Why RocketVideosAi?
Gone are the days of complicated software and hours of video editing. With RocketVideosAi, all you need is a script or prompt. The AI takes care of storyboarding, character generation, realistic voiceovers, animations, captions, and more—giving you studio-quality videos in minutes.
🎁 Exclusive Bonuses Include:
🎯 Rocket QR URL Shortener
🎯 Rocket Bio Pages
🎯 Rocket Academy Course Builder
🎯 Rocket Proof Notification Widget
🎯 + $50,000+ Worth of Premium Bonuses Only Through Our Link!
💥 Perfect For:
📹 YouTubers & Influencers
📈 Marketers & Ecommerce Sellers
📚 Educators & Online Coaches
🏢 Small Businesses & Agencies
🧠 Anyone who wants to create videos without the learning curve!
💸 Launch Offer: One-Time Price – Only $39!
🔥 Use Discount Coupon: ROCKET5 for $5 OFF
🕒 Limited-Time Launch – Don’t Miss Out!
👉 Visit the official RocketVideosAi site to grab your access and get all launch bonuses before the timer runs out!
Marketo User Group - Singapore - April 2025BradBedford3
Singapore MUG: Elevate Your Marketo Game!
Marketo at Adobe Summit: Get the latest updates on Marketo's roadmap and highlights, including the new GenAI-powered email designer. Learn how this no-code tool is revolutionizing email marketing.
AI-Powered Email Marketing: See how Marketo Engage’s new features, like the AI Assistant and Adobe Express integrations, are helping teams create professional, on-brand emails effortlessly.
Business Outcomes with Marketo x SFDC: Explore how the integration of Marketo and Salesforce (SFDC) can enhance lead management, improve collaboration, and optimize campaign performance. Gain actionable insights from Andrew Ong on best practices for data synchronization, lead scoring, and more.
Image-Line FL Studio 20.8.3.2304 crack freealihamzakpa084
🌍📱👉COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page👈🌍
Free download FL Studio Mobile 3 Pro APK for Android, create and save complete multi-track music projects on your Android Phone or Tablet. Record, sequence, edit, mix, and render complete songs.
Threat Modeling & Risk Assessment Webinar: A Step-by-Step ExampleICS
Threat modeling and performing a risk assessment are required by the FDA as part of a 510(k) pre-market submission and will tell you what cybersecurity is needed to make sure your medical device is secure. Webinar presenters will go step-by-step through a threat model and risk assessment for a number of attack paths to clearly show how it is done. By the end of the webinar you will have a very good idea of how to develop a cybersecurity threat model and to perform risk analysis.
🌍📱👉COPY LINK & PASTE ON GOOGLE https://filmoracrack.info//after-verification-click-go-to-download-page/ 👈🌍📱
Revo Uninstaller Pro is innovative uninstaller program which helps you to uninstall unnecessary software and remove easily unwanted programs installed on your
NANO Antivirus Pro Crack + License Code Free 2025bhashmi963
👉 https://up-community.pro/dld/ 🌍📱 Copy Link and paste new tab:
NANO AntiVirus Pro Crack spells its purpose out to the user from the start. It is an antivirus solution that offers a simple interface through which one can ultimately gain access to protection against malware and other threats lurking on the internet.
Software Architecture and Design in the Age of Code Assist tools.pdfManu Pk
Code Assist tools, powered by advanced AI and machine learning algorithms, provide developers with real-time suggestions, code completions, and even automated refactoring. This has led to more efficient and error-free coding practices. We see more and more adoption of these tools by developers, they are faster and more productive in what they do. In this session I would like to explore the evolving role of Software Architects in future scenarios.
I looks at following topics,
-Bird eye view of developer assist tools across SDLC lifecycle
-Claims vs actual impact - Early feedback from real world data
-Future development & Architectural landscape
-What should I start do today to ride this powerful technology?
Async Excellence Unlocking Scalability with Kafka - Devoxx GreeceNatan Silnitsky
How do you scale 4,000 microservices while tackling latency, bottlenecks, and fault tolerance? At Wix, Kafka powers our event-driven architecture with practical patterns that enhance scalability and developer velocity.
This talk explores four key patterns for asynchronous programming:
1. Integration Events: Reduce latency by pre-fetching instead of synchronous calls.
2. Task Queue: Streamline workflows by offloading non-critical tasks.
3. Task Scheduler: Enable precise, scalable scheduling for delayed or recurring tasks.
4. Iterator: Handle long-running jobs in chunks for resilience and scalability.
Learn how to balance benefits and trade-offs, with actionable insights to optimize your own microservices architecture using these proven patterns.
Movavi Video Editor Crack + Activation Key [2025]l07307095
👉COPY & PASTE LINK👉
https://upcommunity.net/dl/
Movavi Video Editor is a beginner-friendly multimedia application that can help you create professional-level videos.
18. Core principles of FP design
Steal from mathematics
Types are not classes
Functions are things
Composition everywhere
Function
19. Core principle: Steal from mathematics
“Programming is one of the most difficult branches of applied mathematics” - E. W. Dijkstra
20. Why mathematics
Dijkstra said:
•Mathematical assertions tend to be unusually precise.
•Mathematical assertions tend to be general. They are applicable to a large (often infinite) class of instances.
•Mathematics embodies a discipline of reasoning allowing assertions to be made with an unusually high confidence level.
22. Mathematical functions
Function add1(x) input x maps to x+1
…
-1
0
1
2
3
…
Domain (int)
Codomain (int)
…
0
1
2
3
4
…
let add1 x = x + 1
val add1 : int -> int
23. Function add1(x) input x maps to x+1
…
-1
0
1
2
3
…
Domain (int)
Codomain (int)
…
0
1
2
3
4
…
Mathematical functions
int add1(int input)
{
switch (input)
{
case 0: return 1;
case 1: return 2;
case 2: return 3;
case 3: return 4;
etc ad infinitum
}
}
•Input and output values already exist
•A function is not a calculation, just a mapping
•Input and output values are unchanged (immutable)
24. Mathematical functions
•A (mathematical) function always gives the same output value for a given input value
•A (mathematical) function has no side effects
Function add1(x) input x maps to x+1
…
-1
0
1
2
3
…
Domain (int)
Codomain (int)
…
0
1
2
3
4
…
25. Functions don't have to be about arithmetic
Function CustomerName(x) input Customer maps to PersonalName
…
Cust1 Cust2 Cust3 Cust3 …
Customer (domain)
Name (codomain)
…
Alice Bob
Sue John
Pam…
Name CustomerName(Customer input)
{
switch (input)
{ case Cust1: return “Alice”;
case Cust2: return “Bob”;
case Cust3: return “Sue”;
etc
}
}
26. Functions can work on functions
Function List.map int->int maps to int list->int list
…
add1 times2 subtract3 add42 …
int->int
int list -> int list
…
eachAdd1 eachTimes2
eachSubtract3 eachAdd42
…
28. The practical benefits of pure functions
customer.SetName(newName);
let newCustomer = setCustomerName(aCustomer, newName)
Pure functions are easy to reason about
var name = customer.GetName();
let name,newCustomer = getCustomerName(aCustomer)
Reasoning about code that might not be pure:
Reasoning about code that is pure:
The customer is being changed.
29. The practical benefits of pure functions
let x = doSomething()
let y = doSomethingElse(x)
return y + 1
Pure functions are easy to refactor
30. The practical benefits of pure functions
Pure functions are easy to refactor
let x = doSomething()
let y = doSomethingElse(x)
return y + 1
31. The practical benefits of pure functions
Pure functions are easy to refactor
let helper() = let x = doSomething()
let y = doSomethingElse(x)
return y
return helper() + 1
32. More practical benefits of pure functions
•Laziness
–only evaluate when I need the output
•Cacheable results
–same answer every time
–"memoization"
•No order dependencies
–I can evaluate them in any order I like
•Parallelizable
–"embarrassingly parallel"
42. Functions as inputs and outputs
let useFn f = (f 1) + 2
let add x = (fun y -> x + y)
int->(int->int)
int ->int
int
int
int->int
let transformInt f x = (f x) + 1
int->int
int
int
Function as output
Function as input
Function as parameter
(int->int)->int
int->int
48. Product types
×
=
Alice, Jan 12th
Bob, Feb 2nd
Carol, Mar 3rd
Set of people
Set of dates
type Birthday = Person * Date
49. Sum types
Set of Cash values
Set of Cheque values
Set of CreditCard values
+
+
type PaymentMethod =
| Cash
| Cheque of ChequeNumber
| Card of CardType * CardNumber
52. Types represent constraints on input and output
type Suit = Club | Diamond | Spade | Heart
type String50 = // non-null, not more than 50 chars
type EmailAddress = // non-null, must contain ‘@’
type StringTransformer = string -> string
type GetCustomer = CustomerId -> Customer option
Instant mockability
54. Types are cheap
type Suit = Club | Diamond | Spade | Heart
type Rank = Two | Three | Four | Five | Six | Seven | Eight
| Nine | Ten | Jack | Queen | King | Ace
type Card = Suit * Rank
type Hand = Card list
Only one line of code to create a type!
56. twelveDividedBy(x) input x maps to 12/x
…
3
2
1
0
…
Domain (int)
Codomain (int)
…
4
6
12
…
Totality
int TwelveDividedBy(int input)
{
switch (input)
{
case 3: return 4;
case 2: return 6;
case 1: return 12;
case 0: return ??;
}
}
What happens here?
57. twelveDividedBy(x) input x maps to 12/x
…
3
2
1
-1
…
NonZeroInteger
int
…
4
6
12
…
Totality
int TwelveDividedBy(int input)
{
switch (input)
{
case 3: return 4;
case 2: return 6;
case 1: return 12;
case -1: return -12;
}
}
Constrain the input
0 is doesn’t have to be handled
NonZeroInteger -> int
0 is missing
Types are documentation
58. twelveDividedBy(x) input x maps to 12/x
…
3
2
1
0
-1
…
int
Option<Int>
…
Some 4
Some 6
Some 12
None …
Totality
int TwelveDividedBy(int input)
{
switch (input)
{
case 3: return Some 4;
case 2: return Some 6;
case 1: return Some 12;
case 0: return None;
}
}
Extend the output
0 is valid input
int -> int option
Types are documentation
60. Output types as error codes
LoadCustomer: CustomerId -> Customer
LoadCustomer: CustomerId -> SuccessOrFailure<Customer>
ParseInt: string -> int
ParseInt: string -> int option
FetchPage: Uri -> String
FetchPage: Uri -> SuccessOrFailure<String>
No nulls
No exceptions
Use the signature, Luke!
62. Types can represent business rules
type EmailContactInfo =
| Unverified of EmailAddress
| Verified of VerifiedEmailAddress
type ContactInfo =
| EmailOnly of EmailContactInfo
| AddrOnly of PostalContactInfo
| EmailAndAddr of EmailContactInfo * PostalContactInfo
64. Using sum vs. inheritance
interface IPaymentMethod {..}
class Cash : IPaymentMethod {..}
class Cheque : IPaymentMethod {..}
class Card : IPaymentMethod {..}
type PaymentMethod =
| Cash
| Cheque of ChequeNumber
| Card of CardType * CardNumber
class Evil : IPaymentMethod {..}
Definition is scattered around many locations
What goes in here? What is the common behaviour?
OO version:
68. It’s ok to expose public data
type PersonalName = {
FirstName: String50
MiddleInitial: String1 option
LastName: String50 }
Immutable
Can’t create invalid values
70. Types are executable documentation
type Suit = Club | Diamond | Spade | Heart
type Rank = Two | Three | Four | Five | Six | Seven | Eight
| Nine | Ten | Jack | Queen | King | Ace
type Card = Suit * Rank
type Hand = Card list
type Deck = Card list
type Player = {Name:string; Hand:Hand}
type Game = {Deck:Deck; Players: Player list}
type Deal = Deck –› (Deck * Card)
type PickupCard = (Hand * Card) –› Hand
71. Types are executable documentation
type CardType = Visa | Mastercard
type CardNumber = CardNumber of string
type ChequeNumber = ChequeNumber of int
type PaymentMethod =
| Cash
| Cheque of ChequeNumber
| Card of CardType * CardNumber
72. More on DDD and designing with types at fsharpforfunandprofit.com/ddd
Static types only! Sorry Clojure and JS developers
80. Transformation oriented programming
Input
Transformation to internal model
Internal Model
Output
Transformation from internal model
validation and wrapping happens here
unwrapping happens here
81. Outbound tranformation
Flow of control in a FP use case
Inbound tranformation
Customer
Domain
Validator
Update
Request DTO
Domain Type
Send
ToDTO
Response DTO
Works well with domain events, FRP, etc
82. Flow of control in a OO use case
Application Services
Customer
Domain
App Service
App Service
Validation
Value
Entity
Infrastructure
Entity
Customer Repo.
Value
Email Message
Value
Database Service
SMTP Service
83. Interacting with the outside world
Nasty, unclean outside world
Nasty, unclean outside world
Nasty, unclean outside world
Beautiful, clean, internal model
Gate with filters
Gate with filters
Gate with filters
84. Interacting with the other domains
Subdomain/ bounded context
Gate with filters
Subdomain/ bounded context
Gate with filters
85. Interacting with the other domains
Bounded context
Bounded context
Bounded context
88. Parameterize all the things
let printList() =
for i in [1..10] do
printfn "the number is %i" i
89. Parameterize all the things
It's second nature to parameterize the data input:
let printList aList =
for i in aList do
printfn "the number is %i" i
90. Parameterize all the things
let printList anAction aList =
for i in aList do
anAction i
FPers would parameterize the action as well:
We've decoupled the behavior from the data
91. Parameterize all the things
public static int Product(int n)
{
int product = 1;
for (int i = 1; i <= n; i++)
{
product *= i;
}
return product;
}
public static int Sum(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
return sum;
}
92. public static int Product(int n)
{
int product = 1;
for (int i = 1; i <= n; i++)
{
product *= i;
}
return product;
}
public static int Sum(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
return sum;
}
Parameterize all the things
93. Parameterize all the things
let product n =
let initialValue = 1
let action productSoFar x = productSoFar * x
[1..n] |> List.fold action initialValue
let sum n =
let initialValue = 0
let action sumSoFar x = sumSoFar+x
[1..n] |> List.fold action initialValue
Lots of collection functions like this: "fold", "map", "reduce", "collect", etc.
95. Generic code
let printList anAction aList =
for i in aList do
anAction i
// val printList :
// ('a -> unit) -> seq<'a> -> unit
Any kind of collection, any kind of action!
F# and other functional languages make code generic automatically
96. Generic code
int -> int
How many ways are there to implement this function?
'a -> 'a
How many ways are there to this function?
97. Generic code
int list -> int list
How many ways are there to implement this function?
'a list -> 'a list
How many ways are there to this function?
98. Generic code
('a -> 'b) -> 'a list -> 'b list
How many ways are there to implement this function?
100. Function types are interfaces
interface IBunchOfStuff
{
int DoSomething(int x);
string DoSomethingElse(int x);
void DoAThirdThing(string x);
}
Let's take the Single Responsibility Principle and the Interface Segregation Principle to the extreme...
Every interface should have only one method!
101. Function types are interfaces
interface IBunchOfStuff
{
int DoSomething(int x);
}
An interface with one method is a just a function type
type IBunchOfStuff: int -> int
Any function with that type is compatible with it
let add2 x = x + 2 // int -> int
let times3 x = x * 3 // int -> int
102. Strategy pattern is trivial in FP
class MyClass
{
public MyClass(IBunchOfStuff strategy) {..}
int DoSomethingWithStuff(int x) {
return _strategy.DoSomething(x)
}
}
Object-oriented strategy pattern:
Functional equivalent:
let DoSomethingWithStuff strategy x =
strategy x
103. Decorator pattern in FP
Functional equivalent of decorator pattern
let add1 x = x + 1 // int -> int
104. Decorator pattern in FP
Functional equivalent of decorator pattern
let add1 x = x + 1 // int -> int
let logged f x =
printfn "input is %A" x
let result = f x
printfn "output is %A" result
result
105. Decorator pattern in FP
Functional equivalent of decorator pattern
let add1 x = x + 1 // int -> int
let logged f x =
printfn "input is %A" x
let result = f x
printfn "output is %A" result
result
let add1Decorated = // int -> int
logged add1
[1..5] |> List.map add1
[1..5] |> List.map add1Decorated
107. Writing functions in different ways
let add x y = x + y
let add = (fun x y -> x + y)
let add x = (fun y -> x + y)
int-> int->int
int-> int->int
int-> (int->int)
108. let three = 1 + 2
let add1 = (+) 1
let three = (+) 1 2
let add1ToEach = List.map add1
110. let names = ["Alice"; "Bob"; "Scott"]
Names |> List.iter hello
let name = "Scott"
printfn "Hello, my name is %s" name
let name = "Scott"
(printfn "Hello, my name is %s") name
let name = "Scott"
let hello = (printfn "Hello, my name is %s")
hello name
115. Continuations
int Divide(int top, int bottom) {
if (bottom == 0)
{
throw new InvalidOperationException("div by 0");
}
else
{
return top/bottom;
}
}
Method has decided to throw an exception
116. Continuations
void Divide(int top, int bottom,
Action ifZero, Action<int> ifSuccess)
{
if (bottom == 0)
{
ifZero();
}
else
{
ifSuccess( top/bottom );
}
}
Let the caller decide what happens
what happens next?
117. Continuations
let divide ifZero ifSuccess top bottom =
if (bottom=0)
then ifZero()
else ifSuccess (top/bottom)
F# version
Four parameters is a lot though!
118. Continuations
let divide ifZero ifSuccess top bottom =
if (bottom=0)
then ifZero()
else ifSuccess (top/bottom)
let ifZero1 () = printfn "bad"
let ifSuccess1 x = printfn "good %i" x
let divide1 = divide ifZero1 ifSuccess1
//test
let good1 = divide1 6 3
let bad1 = divide1 6 0
setup the functions to print a message
Partially apply the continuations
Use it like a normal function – only two parameters
119. Continuations
let divide ifZero ifSuccess top bottom =
if (bottom=0)
then ifZero()
else ifSuccess (top/bottom)
let ifZero2() = None
let ifSuccess2 x = Some x
let divide2 = divide ifZero2 ifSuccess2
//test
let good2 = divide2 6 3
let bad2 = divide2 6 0
setup the functions to return an Option
Use it like a normal function – only two parameters
Partially apply the continuations
120. Continuations
let divide ifZero ifSuccess top bottom =
if (bottom=0)
then ifZero()
else ifSuccess (top/bottom)
let ifZero3() = failwith "div by 0"
let ifSuccess3 x = x
let divide3 = divide ifZero3 ifSuccess3
//test
let good3 = divide3 6 3
let bad3 = divide3 6 0
setup the functions to throw an exception
Use it like a normal function – only two parameters
Partially apply the continuations
122. Pyramid of doom: null testing example
let example input =
let x = doSomething input
if x <> null then
let y = doSomethingElse x
if y <> null then
let z = doAThirdThing y
if z <> null then
let result = z
result
else
null
else
null
else
null
I know you could do early returns, but bear with me...
123. Pyramid of doom: async example
let taskExample input =
let taskX = startTask input
taskX.WhenFinished (fun x ->
let taskY = startAnotherTask x
taskY.WhenFinished (fun y ->
let taskZ = startThirdTask y
taskZ.WhenFinished (fun z ->
z // final result
124. Pyramid of doom: null example
let example input =
let x = doSomething input
if x <> null then
let y = doSomethingElse x
if y <> null then
let z = doAThirdThing y
if z <> null then
let result = z
result
else
null
else
null
else
null
Nulls are a code smell: replace with Option!
125. Pyramid of doom: option example
let example input =
let x = doSomething input
if x.IsSome then
let y = doSomethingElse (x.Value)
if y.IsSome then
let z = doAThirdThing (y.Value)
if z.IsSome then
let result = z.Value
Some result
else
None
else
None
else
None
Much more elegant, yes?
No! This is fugly!
Let’s do a cut & paste refactoring
126. Pyramid of doom: option example
let example input =
let x = doSomething input
if x.IsSome then
let y = doSomethingElse (x.Value)
if y.IsSome then
let z = doAThirdThing (y.Value)
if z.IsSome then
let result = z.Value
Some result
else
None
else
None
else
None
127. Pyramid of doom: option example
let doWithX x =
let y = doSomethingElse x
if y.IsSome then
let z = doAThirdThing (y.Value)
if z.IsSome then
let result = z.Value
Some result
else
None
else
None
let example input =
let x = doSomething input
if x.IsSome then
doWithX x
else
None
128. Pyramid of doom: option example
let doWithX x =
let y = doSomethingElse x
if y.IsSome then
let z = doAThirdThing (y.Value)
if z.IsSome then
let result = z.Value
Some result
else
None
else
None
let example input =
let x = doSomething input
if x.IsSome then
doWithX x
else
None
129. Pyramid of doom: option example
let doWithY y =
let z = doAThirdThing y
if z.IsSome then
let result = z.Value
Some result
else
None
let doWithX x =
let y = doSomethingElse x
if y.IsSome then
doWithY y
else
None
let example input =
let x = doSomething input
if x.IsSome then
doWithX x
else
None
130. Pyramid of doom: option example refactored
let doWithZ z =
let result = z
Some result
let doWithY y =
let z = doAThirdThing y
if z.IsSome then
doWithZ z.Value
else
None
let doWithX x =
let y = doSomethingElse x
if y.IsSome then
doWithY y.Value
else
None
let optionExample input =
let x = doSomething input
if x.IsSome then
doWithX x.Value
else
None
Three small pyramids instead of one big one!
This is still ugly!
But the code has a pattern...
131. Pyramid of doom: option example refactored
let doWithZ z =
let result = z
Some result
let doWithY y =
let z = doAThirdThing y
if z.IsSome then
doWithZ z.Value
else
None
let doWithX x =
let y = doSomethingElse x
if y.IsSome then
doWithY y.Value
else
None
let optionExample input =
let x = doSomething input
if x.IsSome then
doWithX x.Value
else
None
But the code has a pattern...
132. let doWithY y =
let z = doAThirdThing y
if z.IsSome then
doWithZ z.Value
else
None
133. let doWithY y =
let z = doAThirdThing y
z |> ifSomeDo doWithZ
let ifSomeDo f x =
if x.IsSome then
f x.Value
else
None
134. let doWithY y =
y
|> doAThirdThing
|> ifSomeDo doWithZ
let ifSomeDo f x =
if x.IsSome then
f x.Value
else
None
135. let example input =
doSomething input
|> ifSomeDo doSomethingElse
|> ifSomeDo doAThirdThing
|> ifSomeDo (fun z -> Some z)
let ifSomeDo f x =
if x.IsSome then
f x.Value
else
None
146. let bind nextFunction optionInput =
match optionInput with
| Some s -> nextFunction s
| None -> None
Building an adapter block
Two-track input
Two-track output
147. let bind nextFunction optionInput =
match optionInput with
| Some s -> nextFunction s
| None -> None
Building an adapter block
Two-track input
Two-track output
148. let bind nextFunction optionInput =
match optionInput with
| Some s -> nextFunction s
| None -> None
Building an adapter block
Two-track input
Two-track output
149. let bind nextFunction optionInput =
match optionInput with
| Some s -> nextFunction s
| None -> None
Building an adapter block
Two-track input
Two-track output
151. Pyramid of doom: using bind
let bind f opt =
match opt with
| Some v -> f v
| None -> None
let example input =
let x = doSomething input
if x.IsSome then
let y = doSomethingElse (x.Value)
if y.IsSome then
let z = doAThirdThing (y.Value)
if z.IsSome then
let result = z.Value
Some result
else
None
else
None
else
None
152. let example input =
doSomething input
|> bind doSomethingElse
|> bind doAThirdThing
|> bind (fun z -> Some z)
Pyramid of doom: using bind
let bind f opt =
match opt with
| Some v -> f v
| None -> None
No pyramids!
Code is linear and clear.
This pattern is called “monadic bind”
155. Pyramid of doom: using bind for tasks
let taskBind f task =
task.WhenFinished (fun taskResult ->
f taskResult)
let taskExample input =
startTask input
|> taskBind startAnotherTask
|> taskBind startThirdTask
|> taskBind (fun z -> z)
a.k.a “promise” “future”
This pattern is also a “monadic bind”
156. Computation expressions
let example input =
maybe {
let! x = doSomething input
let! y = doSomethingElse x
let! z = doAThirdThing y
return z
}
let taskExample input =
task { let! x = startTask input
let! y = startAnotherTask x
let! z = startThirdTask z
return z
}
Computation expression
Computation expression
158. Example use case
Name is blank Email not valid
Receive request
Validate and canonicalize request
Update existing user record
Send verification email
Return result to user
User not found Db error
Authorization error Timeout
"As a user I want to update my name and email address"
type Request = { userId: int; name: string; email: string }
- and see sensible error messages when something goes wrong!
159. Use case without error handling
string UpdateCustomerWithErrorHandling()
{
var request = receiveRequest();
validateRequest(request);
canonicalizeEmail(request);
db.updateDbFromRequest(request);
smtpServer.sendEmail(request.Email)
return "OK";
}
160. Use case with error handling
string UpdateCustomerWithErrorHandling()
{
var request = receiveRequest();
var isValidated = validateRequest(request);
if (!isValidated) {
return "Request is not valid"
}
canonicalizeEmail(request);
db.updateDbFromRequest(request);
smtpServer.sendEmail(request.Email)
return "OK";
}
161. Use case with error handling
string UpdateCustomerWithErrorHandling()
{
var request = receiveRequest();
var isValidated = validateRequest(request);
if (!isValidated) {
return "Request is not valid"
}
canonicalizeEmail(request);
var result = db.updateDbFromRequest(request);
if (!result) {
return "Customer record not found"
}
smtpServer.sendEmail(request.Email)
return "OK";
}
162. Use case with error handling
string UpdateCustomerWithErrorHandling()
{
var request = receiveRequest();
var isValidated = validateRequest(request);
if (!isValidated) {
return "Request is not valid"
}
canonicalizeEmail(request);
try {
var result = db.updateDbFromRequest(request);
if (!result) {
return "Customer record not found"
}
} catch {
return "DB error: Customer record not updated"
}
smtpServer.sendEmail(request.Email)
return "OK";
}
163. Use case with error handling
string UpdateCustomerWithErrorHandling()
{
var request = receiveRequest();
var isValidated = validateRequest(request);
if (!isValidated) {
return "Request is not valid"
}
canonicalizeEmail(request);
try {
var result = db.updateDbFromRequest(request);
if (!result) {
return "Customer record not found"
}
} catch {
return "DB error: Customer record not updated"
}
if (!smtpServer.sendEmail(request.Email)) {
log.Error "Customer email not sent"
}
return "OK";
}
164. Use case with error handling
string UpdateCustomerWithErrorHandling()
{
var request = receiveRequest();
var isValidated = validateRequest(request);
if (!isValidated) {
return "Request is not valid"
}
canonicalizeEmail(request);
try {
var result = db.updateDbFromRequest(request);
if (!result) {
return "Customer record not found"
}
} catch {
return "DB error: Customer record not updated"
}
if (!smtpServer.sendEmail(request.Email)) {
log.Error "Customer email not sent"
}
return "OK";
}
165. A structure for managing errors
Request
Success
Validate
Failure
let validateInput input =
if input.name = "" then
Failure "Name must not be blank"
else if input.email = "" then
Failure "Email must not be blank"
else
Success input // happy path
type TwoTrack<'TEntity> =
| Success of 'TEntity
| Failure of string
166. name50
Bind example
let nameNotBlank input =
if input.name = "" then
Failure "Name must not be blank"
else Success input
let name50 input =
if input.name.Length > 50 then
Failure "Name must not be longer than 50 chars"
else Success input
let emailNotBlank input =
if input.email = "" then
Failure "Email must not be blank"
else Success input
nameNotBlank
emailNotBlank
172. Functional flow without error handling
let updateCustomer =
receiveRequest
|> validateRequest
|> canonicalizeEmail
|> updateDbFromRequest
|> sendEmail
|> returnMessage
Before
One track
173. Functional flow with error handling
let updateCustomerWithErrorHandling =
receiveRequest
|> validateRequest
|> canonicalizeEmail
|> updateDbFromRequest
|> sendEmail
|> returnMessage
After
See fsharpforfunandprofit.com/rop
Two track
175. World of normal values
int string bool
World of options
int option string option bool option
176. World of options
World of normal values
int string bool
int option string option bool option
177. World of options
World of normal values
int string bool
int option string option bool option
178. How not to code with options
Let’s say you have an int wrapped in an Option, and you want to add 42 to it:
let add42 x = x + 42
let add42ToOption opt =
if opt.IsSome then
let newVal = add42 opt.Value
Some newVal
else
None
181. Lifting
World of options
World of normal values
'a -> 'b
'a option -> 'b option
Option.map
182. The right way to code with options
Let’s say you have an int wrapped in an Option, and you want to add 42 to it:
let add42 x = x + 42
let add42ToOption = Option.map add42
Some 1 |> add42ToOption
Some 1 |> Option.map add42
184. Lifting to lists
World of lists
World of normal values
'a -> 'b
'a list-> 'b list
List.map
185. Lifting to async
World of async
World of normal values
'a -> 'b
'a async > 'b async
Async.map
186. The right way to code with wrapped types
Most wrapped types provide a “map”
let add42 x = x + 42
Some 1 |> Option.map add42
[1;2;3] |> List.map add42
187. Guideline: If you create a wrapped generic type, create a “map” for it.
188. Maps
type TwoTrack<'TEntity> =
| Success of 'TEntity
| Failure of string
let mapTT f x =
match x with
| Success entity -> Success (f entity)
| Failure s -> Failure s
190. Series validation
name50
emailNotBlank
Problem: Validation done in series.
So only one error at a time is returned
191. Parallel validation
name50
emailNotBlank
Split input
Combine output
Now we do get all errors at once!
But how to combine?
192. Creating a valid data structure
type Request= {
UserId: UserId;
Name: String50;
Email: EmailAddress}
type RequestDTO= {
UserId: int;
Name: string;
Email: string}
193. How not to do validation
// do the validation of the DTO
let userIdOrError = validateUserId dto.userId
let nameOrError = validateName dto.name
let emailOrError = validateEmail dto.email
if userIdOrError.IsSuccess
&& nameOrError.IsSuccess
&& emailOrError.IsSuccess then
{
userId = userIdOrError.SuccessValue
name = nameOrError.SuccessValue
email = emailOrError.SuccessValue
}
else if userIdOrError.IsFailure
&& nameOrError.IsSuccess
&& emailOrError.IsSuccess then
userIdOrError.Errors
else ...
194. Lifting to TwoTracks
World of two-tracks
World of normal values
createRequest userId name email
createRequestTT userIdOrError nameOrError emailOrError
lift 3 parameter function
195. The right way
let createRequest userId name email =
{
userId = userIdOrError.SuccessValue
name = nameOrError.SuccessValue
email = emailOrError.SuccessValue
}
let createRequestTT = lift3 createRequest
196. The right way
let createRequestTT = lift3 createRequest
let userIdOrError = validateUserId dto.userId
let nameOrError = validateName dto.name
let emailOrError = validateEmail dto.email
let requestOrError =
createRequestTT userIdOrError nameOrError emailOrError
197. The right way
let userIdOrError = validateUserId dto.userId
let nameOrError = validateName dto.name
let emailOrError = validateEmail dto.email
let requestOrError =
createRequest
<!> userIdOrError
<*> nameOrError
<*> emailOrError
198. Guideline: If you use a wrapped generic type, look for a set of “lifts” associated with it
199. Guideline: If you create a wrapped generic type, also create a set of “lifts” for clients to use with it
But I’m not going explain how right now!
214. The generalization
•You start with a bunch of things, and some way of combining them two at a time.
•Rule 1 (Closure): The result of combining two things is always another one of the things.
•Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn't matter.
•Rule 3 (Identity element): There is a special thing called "zero" such that when you combine any thing with "zero" you get the original thing back.
A monoid!
215. •Rule 1 (Closure): The result of combining two things is always another one of the things.
•Benefit: converts pairwise operations into operations that work on lists.
1 + 2 + 3 + 4
[ 1; 2; 3; 4 ] |> List.reduce (+)
216. 1 * 2 * 3 * 4
[ 1; 2; 3; 4 ] |> List.reduce (*)
•Rule 1 (Closure): The result of combining two things is always another one of the things.
•Benefit: converts pairwise operations into operations that work on lists.
217. "a" + "b" + "c" + "d"
[ "a"; "b"; "c"; "d" ] |> List.reduce (+)
•Rule 1 (Closure): The result of combining two things is always another one of the things.
•Benefit: converts pairwise operations into operations that work on lists.
218. •Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn't matter.
•Benefit: Divide and conquer, parallelization, and incremental accumulation.
1 + 2 + 3 + 4
219. •Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn't matter.
•Benefit: Divide and conquer, parallelization, and incremental accumulation.
(1 + 2) (3 + 4)
3 + 7
220. •Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn't matter.
•Benefit: Divide and conquer, parallelization, and incremental accumulation.
(1 + 2 + 3)
221. •Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn't matter.
•Benefit: Divide and conquer, parallelization, and incremental accumulation.
(1 + 2 + 3) + 4
222. •Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn't matter.
•Benefit: Divide and conquer, parallelization, and incremental accumulation.
(6) + 4
223. Issues with reduce
•How can I use reduce on an empty list?
•In a divide and conquer algorithm, what should I do if one of the "divide" steps has nothing in it?
•When using an incremental algorithm, what value should I start with when I have no data?
224. •Rule 3 (Identity element): There is a special thing called "zero" such that when you combine any thing with "zero" you get the original thing back.
•Benefit: Initial value for empty or missing data
226. type OrderLine = {Qty:int; Total:float}
let orderLines = [
{Qty=2; Total=19.98}
{Qty=1; Total= 1.99}
{Qty=3; Total= 3.99} ]
let addLine line1 line2 =
let newQty = line1.Qty + line2.Qty
let newTotal = line1.Total + line2.Total
{Qty=newQty; Total=newTotal}
orderLines |> List.reduce addLine
Any combination of monoids is also a monoid
233. Monoids in the real world
Metrics guideline: Use counters rather than rates
Alternative metrics guideline: Make sure your metrics are monoids
• incremental updates
• can handle missing data
234. Is function composition a monoid?
>>
Function 1 apple -> banana
Function 2 banana -> cherry
New Function apple -> cherry
Not the same thing.
Not a monoid
235. Is function composition a monoid?
>>
Function 1 apple -> apple
Same thing
Function 2 apple -> apple
Function 3 apple -> apple
A monoid!
236. Is function composition a monoid?
“Functions with same type of input and output”
Functions where the input and output are the same type are monoids! What shall we call these kinds of functions?
237. Is function composition a monoid?
“Functions with same type of input and output”
“Endomorphisms”
Functions where the input and output are the same type are monoids! What shall we call these kinds of functions?
All endomorphisms are monoids
238. Endomorphism example
let plus1 x = x + 1 // int->int
let times2 x = x * 2 // int->int
let subtract42 x = x – 42 // int->int
let functions = [
plus1
times2
subtract42 ]
let newFunction = // int->int
functions |> List.reduce (>>)
newFunction 20 // => 0
Endomorphisms
Put them in a list
Reduce them
Another endomorphism
239. Event sourcing
Any function containing an endomorphism can be converted into a monoid.
For example: Event sourcing
Is an endomorphism
Event
-> State
-> State
240. Event sourcing example
let applyFns = [
apply event1 // State -> State
apply event2 // State -> State
apply event3] // State -> State
let applyAll = // State -> State
applyFns |> List.reduce (>>)
let newState = applyAll oldState
• incremental updates
• can handle missing events
Partial application of event
A function that can apply all the events in one step
241. Bind
Any function containing an endomorphism can be converted into a monoid.
For example: Option.Bind
Is an endomorphism
(fn param)
-> Option
-> Option
242. Event sourcing example
let bindFns = [
Option.bind (fun x->
if x > 1 then Some (x*2) else None)
Option.bind (fun x->
if x < 10 then Some x else None)
]
let bindAll = // Option->Option
bindFns |> List.reduce (>>)
Some 4 |> bindAll // Some 8
Some 5 |> bindAll // None
Partial application of Bind
243. Predicates as monoids
type Predicate<'A> = 'A -> bool
let predAnd pred1 pred2 x =
if pred1 x
then pred2 x
else false
let predicates = [
isMoreThan10Chars // string -> bool
isMixedCase // string -> bool
isNotDictionaryWord // string -> bool
]
let combinedPredicate = // string -> bool
predicates |> List.reduce (predAnd)
Not an endomorphism
But can still be combined
245. Series combination
=
>>
Result is same kind of thing (Closure)
Order not important (Associative)
Monoid!
246. Parallel combination
=
+
Same thing (Closure)
Order not important (Associative)
Monoid!
247. Monad laws
•The Monad laws are just the monoid definitions in diguise
–Closure, Associativity, Identity
•What happens if you break the monad laws?
–You lose monoid benefits such as aggregation
248. A monad is just a monoid in the category of endofunctors!