{"id":13681723,"url":"https://github.com/thma/LtuPatternFactory","last_synced_at":"2025-04-30T06:32:02.021Z","repository":{"id":41413351,"uuid":"151768755","full_name":"thma/LtuPatternFactory","owner":"thma","description":"Lambda the ultimate Pattern Factory: FP, Haskell, Typeclassopedia vs Software Design Patterns","archived":false,"fork":false,"pushed_at":"2024-01-17T23:42:42.000Z","size":602,"stargazers_count":990,"open_issues_count":11,"forks_count":39,"subscribers_count":27,"default_branch":"master","last_synced_at":"2024-10-29T22:32:33.177Z","etag":null,"topics":["builder-pattern","category-theory","design-patterns","factory-pattern","function-composition","functional-languages","functor","functors","gof-patterns","haskell","iterator-pattern","monad","monad-transformers","monoids","pattern-language","reader-monad","strategy-pattern","traversable","typeclasses","typeclassopedia"],"latest_commit_sha":null,"homepage":null,"language":"Haskell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thma.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-05T19:32:13.000Z","updated_at":"2024-10-21T13:48:48.000Z","dependencies_parsed_at":"2022-08-25T08:11:08.305Z","dependency_job_id":"2676b403-51bf-424c-8bad-72732299a913","html_url":"https://github.com/thma/LtuPatternFactory","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thma%2FLtuPatternFactory","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thma%2FLtuPatternFactory/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thma%2FLtuPatternFactory/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thma%2FLtuPatternFactory/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thma","download_url":"https://codeload.github.com/thma/LtuPatternFactory/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224201721,"owners_count":17272627,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["builder-pattern","category-theory","design-patterns","factory-pattern","function-composition","functional-languages","functor","functors","gof-patterns","haskell","iterator-pattern","monad","monad-transformers","monoids","pattern-language","reader-monad","strategy-pattern","traversable","typeclasses","typeclassopedia"],"created_at":"2024-08-02T13:01:34.949Z","updated_at":"2024-11-12T01:30:29.437Z","avatar_url":"https://github.com/thma.png","language":"Haskell","funding_links":[],"categories":["Haskell"],"sub_categories":[],"readme":"# Lambda the Ultimate Pattern Factory\n\n[![Actions Status](https://github.com/thma/LtuPatternFactory/workflows/Haskell%20CI/badge.svg)](https://github.com/thma/LtuPatternFactory/actions)\n\nMy first programming languages were Lisp, Scheme, and ML. When I later started to work in OO languages like C++ and Java I noticed that idioms that are standard vocabulary in functional programming (fp) were not so easy to achieve and required sophisticated structures. Books like [Design Patterns: Elements of Reusable Object-Oriented Software](https://en.wikipedia.org/wiki/Design_Patterns) were a great starting point to reason about those structures. One of my earliest findings was that several of the GoF-Patterns had a stark resemblance of structures that are built into in functional languages: for instance the strategy pattern corresponds to higher order functions in fp (more details see [below](#strategy)).\n\nRecently, while re-reading through the [Typeclassopedia](https://wiki.haskell.org/Typeclassopedia) I thought it would be a good exercise to map the structure of software [design-patterns](https://en.wikipedia.org/wiki/Software_design_pattern#Classification_and_list) to the concepts found in the Haskell type class library and in functional programming in general.\n\nBy searching the web I found some blog entries studying specific patterns, but I did not come across any comprehensive study. As it seemed that nobody did this kind of work yet I found it worthy to spend some time on it and write down all my findings on the subject.\n\nI think this kind of exposition could be helpful if you are:\n\n* a programmer with an OO background who wants to get a better grip on how to implement more complex designs in functional programming\n* a functional programmer who wants to get a deeper intuition for type classes.\n* studying the [Typeclassopedia](https://wiki.haskell.org/Typeclassopedia) and are looking for an accompanying reading providing example use cases and working code.\n\n\u003eThis project is work in progress, so please feel free to contact me with any corrections, adjustments, comments, suggestions and additional ideas you might have.\n\u003e Please use the [Issue Tracker](https://github.com/thma/LtuPatternFactory/issues) to enter your requests.\n\n## Table of contents\n\n* [Lambda the ultimate pattern factory](#lambda-the-ultimate-pattern-factory)\n* [The Patternopedia](#the-patternopedia)\n  * [Data Transfer Object → Functor](#data-transfer-object--functor)\n  * [Singleton → Applicative](#singleton--applicative)\n  * [Pipeline → Monad](#pipeline--monad)\n  * [NullObject → Maybe Monad](#nullobject--maybe-monad)\n  * [Interpreter → Reader Monad](#interpreter--reader-monad)\n  \u003c!--  * [? → MonadFail](#--monadfail)--\u003e\n  * [Aspect Weaving → Monad Transformers](#aspect-weaving--monad-transformers)\n  \u003c!--* [? → MonadFix](#--monadfix) --\u003e\n  * [Composite → SemiGroup → Monoid](#composite--semigroup--monoid)\n  \u003c!--* [? → Alternative, MonadPlus, ArrowPlus](--alternative-monadplus-arrowplus) --\u003e\n  * [Visitor → Foldable](#visitor--foldable)\n  * [Iterator → Traversable](#iterator--traversable)\n  \u003c!-- * [? → Bifunctor](#--bifunctor) --\u003e\n  * [The Pattern behind the Patterns → Category](#the-pattern-behind-the-patterns--category)\n  \u003c!--* [? → Arrow](#--arrow) --\u003e\n  * [Fluent Api → Comonad](#fluent-api--comonad)\n* [Beyond type class patterns](#beyond-type-class-patterns)\n  * [Dependency Injection → Parameter Binding, Partial Application](#dependency-injection--parameter-binding-partial-application)\n  * [Command → Functions as First Class Citizens](#command--functions-as-first-class-citizens)\n  * [Adapter → Function Composition](#adapter--function-composition)\n  * [Template Method → type class default functions](#template-method--type-class-default-functions)\n  * [Creational Patterns](#creational-patterns)\n    * [Abstract Factory → functions as data type values](#abstract-factory--functions-as-data-type-values)\n    * [Builder → record syntax, smart constructor](#builder--record-syntax-smart-constructor)\n* [Functional Programming Patterns](#functional-programming-patterns)\n  * [Higher Order Functions](#higher-order-functions)\n  * [Map Reduce](#map-reduce)\n  \u003c!-- * [Continuation Passing](#continuation-passing) --\u003e\n  * [Lazy Evaluation](#lazy-evaluation)\n  \u003c!-- * [Functional Reactive Programming](#functional-reactive-programming) --\u003e\n  * [Reflection](#reflection)\n* [Conclusions](#conclusions)\n* [Some related links](#some-interesting-links)\n\n## The Patternopedia\n\nThe [Typeclassopedia](https://wiki.haskell.org/wikiupload/8/85/TMR-Issue13.pdf) is a now classic paper that introduces the Haskell type classes by clarifying their algebraic and category-theoretic background. In particular it explains the relationships among those type classes.\n\nIn this chapter I'm taking a tour through the Typeclassopedia from a design pattern perspective.\nFor each of the Typeclassopedia type classes I try to explain how it corresponds to structures applied in software design patterns.\n\nAs a reference map I have included the following chart that depicts the Relationships between type classes covered in the Typeclassopedia:\n\n![The Haskell type classes covered by the Typeclassopedia](https://wiki.haskell.org/wikiupload/c/c7/Typeclassopedia-diagram.svg)\n\n* Solid arrows point from the general to the specific; that is, if there is an arrow from Foo to Bar it means that every Bar is (or should be, or can be made into) a Foo.\n* Dotted lines indicate some other sort of relationship.\n* Monad and ArrowApply are equivalent.\n* Apply and Comonad are greyed out since they are not actually (yet?) in the standard Haskell libraries ∗.\n\n### Data Transfer Object → Functor\n\n\u003e In the field of programming a data transfer object (DTO) is an object that carries data between processes. \n\u003e The motivation for its use is that communication between processes is usually done resorting to remote interfaces \n\u003e (e.g., web services), where each call is an expensive operation.\n\u003e Because the majority of the cost of each call is related to the round-trip time between the client and the server, \n\u003e one way of reducing the number of calls is to use an object (the DTO) that aggregates the data that would have been \n\u003e transferred by the several calls, but that is served by one call only.\n\u003e (quoted from [Wikipedia](https://en.wikipedia.org/wiki/Data_transfer_object)\n\nData Transfer Object is a pattern from Martin Fowler's [Patterns of Enterprise Application Architecture](https://martinfowler.com/eaaCatalog/dataTransferObject.html).\nIt is typically used in multi-layered applications where data is transferred between backends and frontends.\n\nThe aggregation of data usually also involves a denormalization of data structures. As an example, please refer to the following\ndiagram where two entities from the backend (`Album` and `Artist`) are assembled to a compound denormalized DTO `AlbumDTO`:\n\n![DTO](https://martinfowler.com/eaaCatalog/dtoSketch.gif)\n\nOf course, there is also an inverse mapping from `AlbumDTO` to `Album` which is not shown in this diagram.\n\nIn Haskell `Album`, `Artist` and `AlbumDTO` can be represented as data types with record notation:\n\n```haskell\ndata Album = Album {\n    title       :: String\n  , publishDate :: Int\n  , labelName   :: String\n  , artist      :: Artist\n} deriving (Show)\n\ndata Artist = Artist {\n    publicName :: String\n  , realName   :: Maybe String\n} deriving (Show)\n\ndata AlbumDTO = AlbumDTO {\n    albumTitle  :: String\n  , published   :: Int\n  , label       :: String\n  , artistName  :: String\n} deriving (Show, Read)\n```\n\nThe transfer from an `Album` to an `AlbumDTO` and vice versa can be achieved by two simple functions, that perfom the\nintended field wise mappings:\n\n```haskell\ntoAlbumDTO :: Album -\u003e AlbumDTO\ntoAlbumDTO Album {title = t, publishDate = d, labelName = l, artist = a} =\n  AlbumDTO {albumTitle = t, published = d, label = l, artistName = (publicName a)}\n\ntoAlbum :: AlbumDTO -\u003e Album\ntoAlbum AlbumDTO {albumTitle = t, published = d, label = l, artistName = n} =\n  Album {title = t, publishDate = d, labelName = l, artist = Artist {publicName = n, realName = Nothing}}\n```\n\nIn this few lines we have covered the basic idea of the DTO pattern.\n\nNow, let's consider the typical situation that you don't have to transfer only a *single* `Album` instance but a whole \nlist of `Album` instances, e.g.:\n\n```haskell\nalbums :: [Album]\nalbums =\n    [\n      Album {title = \"Microgravity\",\n             publishDate = 1991,\n             labelName = \"Origo Sound\",\n             artist = Artist {publicName = \"Biosphere\", realName = Just \"Geir Jenssen\"}}\n    , Album {title = \"Apollo - Atmospheres \u0026 Soundtracks\",\n             publishDate = 1983,\n             labelName = \"Editions EG\",\n             artist = Artist {publicName = \"Brian Eno\", realName = Just \"Brian Peter George St. John le Baptiste de la Salle Eno\"}}\n    ]\n```\n\nIn this case we have to apply the `toAlbumDTO` function to all elements of the list. \nIn Haskell this *higher order* operation is called `map`:\n\n```haskell\nmap :: (a -\u003e b) -\u003e [a] -\u003e [b]\nmap _f []    = []\nmap f (x:xs) = f x : map f xs\n```\n\n`map` takes a function `f :: (a -\u003e b)` (a function from type `a` to type `b`) and an `[a]` list and returns a `[b]` list.\nThe `b` elements are produced by applying the function `f` to each element of the input list.\nApplying `toAlbumDTO` to a list of albums can thus be done in the Haskell REPL GHCi as follows:\n\n```haskell\nλ\u003e map toAlbumDTO albums\n[AlbumDTO {albumTitle = \"Microgravity\", published = 1991, label = \"Origo Sound\", artistName = \"Biosphere\"},\n AlbumDTO {albumTitle = \"Apollo - Atmospheres \u0026 Soundtracks\", published = 1983, label = \"Editions EG\", artistName = \"Brian Eno\"}]\n```\n\nThis mapping of functions over lists is a basic technique known in many functional languages.\nIn Haskell further generalises this technique with the concept of the `Functor` type class. \n\n\u003e The `Functor` class is the most basic and ubiquitous type class in the Haskell libraries. \n\u003e A simple intuition is that a `Functor` represents a “container” of some sort, along with the ability to apply a \n\u003e function uniformly to every element in the container. For example, a list is a container of elements, \n\u003e and we can apply a function to every element of a list, using `map`. \n\u003e As another example, a binary tree is also a container of elements, and it’s not hard to come up with a way to \n\u003e recursively apply a function to every element in a tree.\n\u003e\n\u003e Another intuition is that a Functor represents some sort of “computational context”. \n\u003e This intuition is generally more useful, but is more difficult to explain, precisely because it is so general. \n\u003e\n\u003e Quoted from [Typeclassopedia](https://wiki.haskell.org/Typeclassopedia#Functor)\n\nBasically, all instances of the `Functor` type class must provide a function `fmap`:\n\n```haskell\nclass  Functor f  where\n    fmap :: (a -\u003e b) -\u003e f a -\u003e f b\n```\n\nFor Lists the implementation is simply the `map` function that we already have seen above:\n```haskell\ninstance Functor [] where\n    fmap = map\n```\n\nFunctors have interesting properties, they fulfill the two so called *functor laws*, \nwhich are part of the definition of a mathematical functor:\n\n```haskell\nfmap id = id                        -- (1)\nfmap (g . h) = (fmap g) . (fmap h)  -- (2)\n```\n\nThe first law `(1)` states that mapping the identity function over every item in a container has no effect. \n\nThe second `(2)` says that mapping a composition of two functions over every item in a container is the same as first \nmapping one function, and then mapping the other.\n\nThese laws are very useful when we consider composing complex mappings from simpler operations.\n\nSay we want to extend our DTO mapping functionality by also providing some kind of marshalling. For a single album instance, \nwe can use function composition `(f . g) x == f (g x)`, which is defined in Haskell as:\n\n```haskell\n(.) :: (b -\u003e c) -\u003e (a -\u003e b) -\u003e a -\u003e c\n(.) f g x = f (g x)\n```\n\nIn the following GHCi session we are using `(.)` to first convert an `Album` to its `AlbumDTO` representation and then \nturn that into a `String` by using the `show` function:\n\n```haskell\nλ\u003e album1 = albums !! 0\nλ\u003e print album1\nAlbum {title = \"Microgravity\", publishDate = 1991, labelName = \"Origo Sound\", artist = Artist {publicName = \"Biosphere\", realName = Just \"Geir Jenssen\"}}\nλ\u003e marshalled = (show . toAlbumDTO) album1\nλ\u003e :t marshalled\nmarshalled :: String\nλ\u003e print marshalled\n\"AlbumDTO {albumTitle = \\\"Microgravity\\\", published = 1991, label = \\\"Origo Sound\\\", artistName = \\\"Biosphere\\\"}\"\n```\n\nAs we can rely on the functor law `fmap (g . h) = (fmap g) . (fmap h)` we can use fmap to use the same composed\nfunction on any functor, for example our list of albums:\n\n```haskell\nλ\u003e fmap (show . toAlbumDTO) albums\n[\"AlbumDTO {albumTitle = \\\"Microgravity\\\", published = 1991, label = \\\"Origo Sound\\\", artistName = \\\"Biosphere\\\"}\",\n \"AlbumDTO {albumTitle = \\\"Apollo - Atmospheres \u0026 Soundtracks\\\", published = 1983, label = \\\"Editions EG\\\", artistName = \\\"Brian Eno\\\"}\"]\n```\n\nWe can build more complex mappings by chaining multiple functions, to produce for example a gzipped byte string output:\n\n```haskell\nλ\u003e gzipped = (compress . pack . show . toAlbumDTO) album1\n```\n\nAs the sequence of operation must be read from right to left for the `(.)` operator this becomes quite unintuitive for longer sequences.\nThus, Haskellers often use the flipped version of `(.)`, `(\u003e\u003e\u003e)` which is defined as:\n\n```haskell\nf \u003e\u003e\u003e g = g . f\n```\n\nUsing `(\u003e\u003e\u003e)` the intent of our composition chain becomes much clearer (at least when you are trained to read from left to right):\n\n```haskell\nλ\u003e gzipped = (toAlbumDTO \u003e\u003e\u003e show \u003e\u003e\u003e pack \u003e\u003e\u003e compress) album1\n```\n\nUnmarshalling can be defined using the inverse operations:\n\n```haskell\nλ\u003e unzipped = (decompress \u003e\u003e\u003e unpack \u003e\u003e\u003e read \u003e\u003e\u003e toAlbum) gzipped\nλ\u003e :t unzipped\nunzipped :: Album\nλ\u003e print unzipped\nAlbum {title = \"Microgravity\", publishDate = 1991, labelName = \"Origo Sound\", artist = Artist {publicName = \"Biosphere\", realName = Nothing}}\n```\n\nOf course, we can use `fmap` to apply such composed mapping function to any container type instantiating the `Functor` \ntype class:\n\n```haskell\nλ\u003e marshalled   = fmap (toAlbumDTO \u003e\u003e\u003e show \u003e\u003e\u003e pack \u003e\u003e\u003e compress) albums\nλ\u003e unmarshalled = fmap (decompress \u003e\u003e\u003e unpack \u003e\u003e\u003e read \u003e\u003e\u003e toAlbum) marshalled\nλ\u003e print unmarshalled\n[Album {title = \"Microgravity\", publishDate = 1991, labelName = \"Origo Sound\", artist = Artist {publicName = \"Biosphere\", realName = Nothing}},\n Album {title = \"Apollo - Atmospheres \u0026 Soundtracks\", publishDate = 1983, labelName = \"Editions EG\", artist = Artist {publicName = \"Brian Eno\", realName = Nothing}}]\n```\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/DataTransferObject.hs)\n\n### Singleton → Applicative\n\n\u003e \"The singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.\"\n\u003e (quoted from [Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern)\n\nThe singleton pattern ensures that multiple requests to a given object always return one and the same singleton instance.\nIn functional programming this semantics can be achieved by `let`:\n\n```haskell\nlet singleton = someExpensiveComputation\nin  mainComputation\n\n--or in lambda notation:\n(\\singleton -\u003e mainComputation) someExpensiveComputation\n```\n\nVia the `let`-Binding we can thread the singleton through arbitrary code in the `in` block. All occurences of `singleton` in the `mainComputation`will point to the same instance.\n\nType classes provide several tools to make this kind of threading more convenient or even to avoid explicit threading of instances.\n\n#### Using Applicative Functor for threading of singletons\n\nThe following code defines a simple expression evaluator:\n\n```haskell\ndata Exp e = Var String\n           | Val e\n           | Add (Exp e) (Exp e)\n           | Mul (Exp e) (Exp e)\n\n-- the environment is a list of tuples mapping variable names to values of type e\ntype Env e = [(String, e)]\n\n-- a simple evaluator reducing expression to numbers\neval :: Num e =\u003e Exp e -\u003e Env e -\u003e e\neval (Var x)   env = fetch x env\neval (Val i)   env = i\neval (Add p q) env = eval p env + eval q env  \neval (Mul p q) env = eval p env * eval q env\n```\n\n`eval` is a classic evaluator function that recursively evaluates sub-expression before applying `+` or `*`.\nNote how the explicit `env`parameter is threaded through the recursive eval calls. This is needed to have the\nenvironment avalailable for variable lookup at any recursive call depth.\n\nIf we now bind `env` to a value as in the following snippet it is used as an immutable singleton within the recursive evaluation of `eval exp env`.\n\n```haskell\nmain = do\n  let exp = Mul (Add (Val 3) (Val 1))\n                (Mul (Val 2) (Var \"pi\"))\n      env = [(\"pi\", pi)]\n  print $ eval exp env\n```\n\nExperienced Haskellers will notice the [\"eta-reduction smell\"](https://wiki.haskell.org/Eta_conversion) in `eval (Var x) env = fetch x env` which hints at the possibilty to remove `env` as an explicit parameter. We can not do this right away as the other equations for `eval` do not allow eta-reduction. In order to do so we have to apply the combinators of the `Applicative Functor`:\n\n```haskell\nclass Functor f =\u003e Applicative f where\n    pure  :: a -\u003e f a\n    (\u003c*\u003e) :: f (a -\u003e b) -\u003e f a -\u003e f b\n\ninstance Applicative ((-\u003e) a) where\n    pure        = const\n    (\u003c*\u003e) f g x = f x (g x)\n```\n\nThis `Applicative` allows us to rewrite `eval` as follows:\n\n```haskell\neval :: Num e =\u003e Exp e -\u003e Env e -\u003e e\neval (Var x)   = fetch x\neval (Val i)   = pure i\neval (Add p q) = pure (+) \u003c*\u003e eval p  \u003c*\u003e eval q  \neval (Mul p q) = pure (*) \u003c*\u003e eval p  \u003c*\u003e eval q\n```\n\nAny explicit handling of the variable `env` is now removed.\n(I took this example from the classic paper [Applicative programming with effects](http://www.soi.city.ac.uk/~ross/papers/Applicative.pdf) which details how `pure` and `\u003c*\u003e` correspond to the combinatory logic combinators `K` and `S`.)\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/Singleton.hs)\n\n### Pipeline → Monad\n\n\u003e In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines, functions, etc.), arranged so that the output of each element is the input of the next; the name is by analogy to a physical pipeline.\n\u003e (Quoted from: [Wikipedia](https://en.wikipedia.org/wiki/Pipeline_(software))\n\nThe concept of pipes and filters in Unix shell scripts is a typical example of the pipeline architecture pattern.\n\n```bash\n$ echo \"hello world\" | wc -w | xargs printf \"%d*3\\n\" | bc -l\n6\n```\n\nThis works exactly as stated in the wikipedia definition of the pattern: the output of `echo \"hello world\"` is used as input for the next command `wc -w`. The ouptput of this command is then piped as input into `xargs printf \"%d*3\\n\"` and so on.\nOn the first glance this might look like ordinary function composition. We could for instance come up with the following approximation in Haskell:\n\n```haskell\n((3 *) . length . words) \"hello world\"\n6\n```\n\nBut with this design we missed an important feature of the chain of shell commands: The commands do not work on elementary types like Strings or numbers but on input and output streams that are used to propagate the actual elementary data around. So we can't just send a String into the `wc` command as in `\"hello world\" | wc -w`. Instead we have to use `echo` to place the string into a stream that we can then use as input to the `wc` command:\n\n```bash\n\u003e echo \"hello world\" | wc -w\n```\n\nSo we might say that `echo` *injects* the String `\"hello world\"` into the stream context.\nWe can capture this behaviour in a functional program like this:\n\n```haskell\n-- The Stream type is a wrapper around an arbitrary payload type 'a'\nnewtype Stream a = Stream a deriving (Show)\n\n-- echo injects an item of type 'a' into the Stream context\necho :: a -\u003e Stream a\necho = Stream\n\n-- the 'andThen' operator used for chaining commands\ninfixl 7 |\u003e\n(|\u003e) :: Stream a -\u003e (a -\u003e Stream b) -\u003e Stream b\nStream x |\u003e f = f x\n\n\n-- echo and |\u003e are used to create the actual pipeline\npipeline :: String -\u003e Stream Int\npipeline str =\n  echo str |\u003e echo . length . words |\u003e echo . (3 *)\n-- now executing the program in ghci repl:\nghci\u003e pipeline \"hello world\"\nStream 6  \n```\n\nThe `echo` function injects any input into the `Stream` context:\n\n```haskell\nghci\u003e echo \"hello world\"\nStream \"hello world\"\n```\n\nThe `|\u003e` (pronounced as \"andThen\") does the function chaining:\n\n```haskell\nghci\u003e echo \"hello world\" |\u003e echo . words\nStream [\"hello\",\"world\"]\n```\n\nThe result of `|\u003e` is of type `Stream b` that's why we cannot just write `echo \"hello world\" |\u003e words`. We have to use echo  to create a `Stream` output that can be digested by a subsequent `|\u003e`.\n\nThe interplay of a Context type `Stream a` and the functions `echo` and `|\u003e` is a well known pattern from functional languages: it's the legendary *Monad*. As the [Wikipedia article on the pipeline pattern](https://en.wikipedia.org/wiki/Pipeline_(software)) states:\n\n\u003e Pipes and filters can be viewed as a form of functional programming, using byte streams as data objects; more specifically, they can be seen as a particular form of monad for I/O.\n\nThere is an interesting paper available elaborating on the monadic nature of Unix pipes: [Monadic Shell](http://okmij.org/ftp/Computation/monadic-shell.html).\n\nHere is the definition of the Monad type class in Haskell:\n\n```Haskell\nclass Applicative m =\u003e Monad m where\n    -- | Sequentially compose two actions, passing any value produced\n    -- by the first as an argument to the second.\n    (\u003e\u003e=)  :: m a -\u003e (a -\u003e m b) -\u003e m b\n\n    -- | Inject a value into the monadic type.\n    return :: a -\u003e m a\n    return = pure\n```\n\nBy looking at the types of `\u003e\u003e=` and `return` it's easy to see the direct correspondence to `|\u003e` and `echo` in the pipeline example above:\n\n```haskell\n    (|\u003e)   :: Stream a -\u003e (a -\u003e Stream b) -\u003e Stream b\n    echo   :: a -\u003e Stream a\n```\n\nMhh, this is nice, but still looks a lot like ordinary composition of functions, just with the addition of a wrapper.\nIn this simplified example that's true, because we have designed the `|\u003e` operator to simply unwrap a value from the Stream and bind it to the formal parameter of the subsequent function:\n\n```haskell\nStream x |\u003e f = f x\n```\n\nBut we are free to implement the `andThen` operator in any way that we seem fit as long we maintain the type signature and the [monad laws](https://en.wikipedia.org/wiki/Monad_%28functional_programming%29#Monad_laws).\nSo we could for instance change the semantics of `\u003e\u003e=` to keep a log along the execution pipeline:\n\n```haskell\n-- The DeriveFunctor Language Pragma provides automatic derivation of Functor instances\n{-# LANGUAGE DeriveFunctor #-}\n\n-- a Log is just a list of Strings\ntype Log = [String]\n\n-- the Stream type is extended by a Log that keeps track of any logged messages\nnewtype LoggerStream a = LoggerStream (a, Log) deriving (Show, Functor)\n\ninstance Applicative LoggerStream where\n  pure = return\n  LoggerStream (f, _) \u003c*\u003e r = fmap f r  \n\n-- our definition of the Logging Stream Monad:\ninstance Monad LoggerStream where\n  -- returns a Stream wrapping a tuple of the actual payload and an empty Log\n  return a = LoggerStream (a, [])\n\n  -- we define (\u003e\u003e=) to return a tuple (composed functions, concatenated logs)\n  m1 \u003e\u003e= m2  = let LoggerStream(f1, l1) = m1\n                   LoggerStream(f2, l2) = m2 f1\n               in LoggerStream(f2, l1 ++ l2)\n\n-- compute length of a String and provide a log message\nlogLength :: String -\u003e LoggerStream Int\nlogLength str = let l = length(words str)\n                in LoggerStream (l, [\"length(\" ++ str ++ \") = \" ++ show l])\n\n-- multiply x with 3 and provide a log message\nlogMultiply :: Int -\u003e LoggerStream Int\nlogMultiply x = let z = x * 3\n                in LoggerStream (z, [\"multiply(\" ++ show x ++ \", 3\" ++\") = \" ++ show z])\n\n-- the logging version of the pipeline\nlogPipeline :: String -\u003e LoggerStream Int\nlogPipeline str =\n  return str \u003e\u003e= logLength \u003e\u003e= logMultiply\n\n-- and then in Ghci:\n\u003e logPipeline \"hello logging world\"\nLoggerStream (9,[\"length(hello logging world) = 3\",\"multiply(3, 3) = 9\"])\n```\n\nWhat's noteworthy here is that Monads allow to make the mechanism of chaining functions *explicit*. We can define what `andThen` should mean in our pipeline by choosing a different Monad implementation.\nSo in a sense Monads could be called [programmable semicolons](http://book.realworldhaskell.org/read/monads.html#id642960)\n\nTo make this statement a bit clearer we will have a closer look at the internal workings of the `Maybe` Monad in the next section.\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/Pipeline.hs)\n\n### NullObject → Maybe Monad\n\n\u003e[...] a null object is an object with no referenced value or with defined neutral (\"null\") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof).\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Null_object_pattern)\n\nIn functional programming the null object pattern is typically formalized with option types:\n\u003e [...] an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions which may or may not return a meaningful value when they are applied. It consists of a constructor which either is empty (named None or `Nothing`), or which encapsulates the original data type `A` (written `Just A` or Some A).\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Option_type)\n\n(See also: [Null Object as Identity](http://blog.ploeh.dk/2018/04/23/null-object-as-identity/))\n\nIn Haskell the most simple option type is `Maybe`. Let's directly dive into an example. We define a reverse index, mapping songs to album titles.\nIf we now lookup up a song title we may either be lucky and find the respective album or not so lucky when there is no album matching our song:\n\n```haskell\nimport           Data.Map (Map, fromList)\nimport qualified Data.Map as Map (lookup) -- avoid clash with Prelude.lookup\n\n-- type aliases for Songs and Albums\ntype Song   = String\ntype Album  = String\n\n-- the simplified reverse song index\nsongMap :: Map Song Album\nsongMap = fromList\n    [(\"Baby Satellite\",\"Microgravity\")\n    ,(\"An Ending\", \"Apollo: Atmospheres and Soundtracks\")]\n\n```\n\nWe can lookup this map by using the function `Map.lookup :: Ord k =\u003e k -\u003e Map k a -\u003e Maybe a`.\n\nIf no match is found it will return `Nothing` if a match is found it will return `Just match`:\n\n```haskell\nghci\u003e Map.lookup \"Baby Satellite\" songMap\nJust \"Microgravity\"\nghci\u003e Map.lookup \"The Fairy Tale\" songMap\nNothing\n```\n\nActually the `Maybe` type is defined as:\n\n```haskell\ndata  Maybe a  =  Nothing | Just a\n    deriving (Eq, Ord)\n```\n\nAll code using the `Map.lookup` function will never be confronted with any kind of Exceptions, null pointers or other nasty things. Even in case of errors a lookup will always return a properly typed `Maybe` instance. By pattern matching for `Nothing` or `Just a` client code can react on failing matches or positive results:\n\n```haskell\n    case Map.lookup \"Ancient Campfire\" songMap of\n        Nothing -\u003e print \"sorry, could not find your song\"\n        Just a  -\u003e print a\n```\n\nLet's try to apply this to an extension of our simple song lookup.\nLet's assume that our music database has much more information available. Apart from a reverse index from songs to albums, there might also be an index mapping album titles to artists.\nAnd we might also have an index mapping artist names to their websites:\n\n```haskell\ntype Song   = String\ntype Album  = String\ntype Artist = String\ntype URL    = String\n\nsongMap :: Map Song Album\nsongMap = fromList\n    [(\"Baby Satellite\",\"Microgravity\")\n    ,(\"An Ending\", \"Apollo: Atmospheres and Soundtracks\")]\n\nalbumMap :: Map Album Artist\nalbumMap = fromList\n    [(\"Microgravity\",\"Biosphere\")\n    ,(\"Apollo: Atmospheres and Soundtracks\", \"Brian Eno\")]\n\nartistMap :: Map Artist URL\nartistMap = fromList\n    [(\"Biosphere\",\"http://www.biosphere.no//\")\n    ,(\"Brian Eno\", \"http://www.brian-eno.net\")]\n\nlookup' :: Ord a =\u003e Map a b -\u003e a -\u003e Maybe b\nlookup' = flip Map.lookup\n\nfindAlbum :: Song -\u003e Maybe Album\nfindAlbum = lookup' songMap\n\nfindArtist :: Album -\u003e Maybe Artist\nfindArtist = lookup' albumMap\n\nfindWebSite :: Artist -\u003e Maybe URL\nfindWebSite = lookup' artistMap\n```\n\nWith all this information at hand we want to write a function that has an input parameter of type `Song` and returns a `Maybe URL` by going from song to album to artist to website url:\n\n```haskell\nfindUrlFromSong :: Song -\u003e Maybe URL\nfindUrlFromSong song =\n    case findAlbum song of\n        Nothing    -\u003e Nothing\n        Just album -\u003e\n            case findArtist album of\n                Nothing     -\u003e Nothing\n                Just artist -\u003e\n                    case findWebSite artist of\n                        Nothing  -\u003e Nothing\n                        Just url -\u003e Just url\n```\n\nThis code makes use of the pattern matching logic described before. It's worth to note that there is some nice circuit breaking happening in case of a `Nothing`. In this case `Nothing` is directly returned as result of the function and the rest of the case-ladder is not executed.\nWhat's not so nice is *\"the dreaded ladder of code marching off the right of the screen\"* [(quoted from Real World Haskell)](http://book.realworldhaskell.org/).\n\nFor each find function we have to repeat the same ceremony of pattern matching on the result and either return `Nothing` or proceed with the next nested level.\n\nThe good news is that it is possible to avoid this ladder.\nWe can rewrite our search by applying the `andThen` operator `\u003e\u003e=` as `Maybe` is an instance of `Monad`:\n\n```haskell\nfindUrlFromSong' :: Song -\u003e Maybe URL\nfindUrlFromSong' song =\n    findAlbum song   \u003e\u003e= \\album -\u003e\n    findArtist album \u003e\u003e= \\artist -\u003e\n    findWebSite artist  \n```\n\nor even shorter as we can eliminate the lambda expressions by applying [eta-conversion](https://wiki.haskell.org/Eta_conversion):\n\n```haskell\nfindUrlFromSong'' :: Song -\u003e Maybe URL\nfindUrlFromSong'' song =\n    findAlbum song \u003e\u003e= findArtist \u003e\u003e= findWebSite\n```\n\nUsing it in GHCi:\n\n```haskell\nghci\u003e findUrlFromSong'' \"All you need is love\"\nNothing\nghci\u003e findUrlFromSong'' \"An Ending\"\nJust \"http://www.brian-eno.net\"\n```\n\nThe expression `findAlbum song \u003e\u003e= findArtist \u003e\u003e= findWebSite` and the sequencing of actions in the [pipeline](#pipeline---monad) example `return str \u003e\u003e= return . length . words \u003e\u003e= return . (3 *)` have a similar structure.\n\nBut the behaviour of both chains is quite different: In the Maybe Monad `a \u003e\u003e= b` does not evaluate b if `a == Nothing` but stops the whole chain of actions by simply returning `Nothing`.\n\nThe pattern matching and 'short-circuiting' is directly coded into the definition of `(\u003e\u003e=)` in the Monad implementation of `Maybe`:\n\n```haskell\ninstance  Monad Maybe  where\n    (Just x) \u003e\u003e= k      = k x\n    Nothing  \u003e\u003e= _      = Nothing\n```\n\nThis elegant feature of `(\u003e\u003e=)` in the `Maybe` Monad allows us to avoid ugly and repetetive coding.  \n\n#### Avoiding partial functions by using Maybe\n\nMaybe is often used to avoid the exposure of partial functions to client code. Take for example division by zero or computing the square root of negative numbers which are undefined (at least for real numbers).\nHere come safe \u0026ndash; that is total \u0026ndash; definitions of these functions that return `Nothing` for undefined cases:\n\n```haskell\nsafeRoot :: Double -\u003e Maybe Double\nsafeRoot x\n    | x \u003e= 0    = Just (sqrt x)\n    | otherwise = Nothing\n\nsafeReciprocal :: Double -\u003e Maybe Double\nsafeReciprocal x\n    | x /= 0    = Just (1/x)\n    | otherwise = Nothing\n```\n\nAs we have already learned the monadic `\u003e\u003e=` operator allows to chain such function as in the following example:\n\n```haskell\nsafeRootReciprocal :: Double -\u003e Maybe Double\nsafeRootReciprocal x = return x \u003e\u003e= safeReciprocal \u003e\u003e= safeRoot\n```\n\nThis can be written even more terse as:\n\n```haskell\nsafeRootReciprocal :: Double -\u003e Maybe Double\nsafeRootReciprocal = safeReciprocal \u003e=\u003e safeRoot\n```\n\nThe use of the [Kleisli 'fish' operator `\u003e=\u003e`](https://www.stackage.org/haddock/lts-13.0/base-4.12.0.0/Control-Monad.html#v:-62--61--62-)  makes it more evident that we are actually aiming at a composition of the monadic functions `safeReciprocal` and `safeRoot`.\n\nThere are many predefined Monads available in the Haskell curated libraries and it's also possible to combine their effects by making use of `MonadTransformers`. But that's a [different story...](#aspect-weaving--monad-transformers)\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/NullObject.hs)\n\n### Interpreter → Reader Monad\n\n\u003e In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client.\n\u003e\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Interpreter_pattern)\n\nIn the section [Singleton → Applicative](#singleton--applicative) we have already written a simple expression evaluator. From that section it should be obvious how easy the definition of evaluators and interpreters is in functional programming languages.\n\nThe main ingredients are:\n\n* Algebraic Data Types (ADT) used to define the expression data type which is to be evaluated\n* An evaluator function that uses pattern matching on the expression ADT\n* 'implicit' threading of an environment\n\nIn the section on Singleton we have seen that some kind of 'implicit' threading of the environment can be already achieved with `Applicative Functors.\nWe still had the environment as an explicit parameter of the eval function:\n\n```haskell\neval :: Num e =\u003e Exp e -\u003e Env e -\u003e e\n```\n\nbut we could omit it in the pattern matching equations:\n\n```haskell\neval (Var x)   = fetch x\neval (Val i)   = pure i\neval (Add p q) = pure (+) \u003c*\u003e eval p  \u003c*\u003e eval q  \neval (Mul p q) = pure (*) \u003c*\u003e eval p  \u003c*\u003e eval q\n```\n\nBy using Monads the handling of the environment can be made even more implicit.\n\nI'll demonstrate this with a slightly extended version of the evaluator. In the first step we extend the expression syntax to also provide let expressions and generic support for binary operators:\n\n```haskell\n-- | a simple expression ADT\ndata Exp a =\n      Var String                            -- a variable to be looked up\n    | BinOp (BinOperator a) (Exp a) (Exp a) -- a binary operator applied to two expressions\n    | Let String (Exp a) (Exp a)            -- a let expression\n    | Val a                                 -- an atomic value\n\n-- | a binary operator type\ntype BinOperator a =  a -\u003e a -\u003e a\n\n-- | the environment is just a list of mappings from variable names to values\ntype Env a = [(String, a)]\n```\n\nWith this data type we can encode expressions like:\n\n```haskell\nlet x = 4+5\nin 2*x\n```\n\nas:\n\n```haskell\nLet \"x\" (BinOp (+) (Val 4) (Val 5))\n        (BinOp (*) (Val 2) (Var \"x\"))\n```\n\nIn order to evaluate such expression we must be able to modify the environment at runtime to create a binding for the variable `x` which will be referred to in the `in` part of the expression.\n\nNext we define an evaluator function that pattern matches the above expression ADT:\n\n```haskell\neval :: MonadReader (Env a) m =\u003e Exp a -\u003e m a\neval (Val i)          = return i\neval (Var x)          = asks (fetch x)\neval (BinOp op e1 e2) = liftM2 op (eval e1) (eval e2)\neval (Let x e1 e2)    = eval e1 \u003e\u003e= \\v -\u003e local ((x,v):) (eval e2)\n```\n\nLet's explore this dense code line by line.\n\n```haskell\neval :: MonadReader (Env a) m =\u003e Exp a -\u003e m a\n```\n\nThe most simple instance for `MonadReader` is the partially applied function type `((-\u003e) env)`.\nLet's assume the compiler will choose this type as the `MonadReader` instance. We can then rewrite the function signature as follows:\n\n```haskell\neval :: Exp a -\u003e ((-\u003e) (Env a)) a  -- expanding m to ((-\u003e) (Env a))\neval :: Exp a -\u003e Env a -\u003e a        -- applying infix notation for (-\u003e)\n```\n\nThis is exactly the signature we were using for the `Applicative` eval function which matches our original intent to eval an expression of type `Exp a` in an environment of type `Env a` to a result of type `a`.\n\n```haskell\neval (Val i)          = return i\n```\n\nIn this line we are pattern matching for a `(Val i)`. The atomic value `i` is `return`ed, that is lifted to a value of the type `Env a -\u003e a`.\n\n```haskell\neval (Var x)          = asks (fetch x)\n```\n\n`asks` is a helper function that applies its argument `f :: env -\u003e a` (in our case `(fetch x)` which looks up variable `x`) to the environment. `asks` is thus typically used to handle environment lookups:\n\n```haskell\nasks :: (MonadReader env m) =\u003e (env -\u003e a) -\u003e m a\nasks f = ask \u003e\u003e= return . f\n```\n\nNow to the next line handling the application of a binary operator:\n\n```haskell\neval (BinOp op e1 e2) = liftM2 op (eval e1) (eval e2)\n```\n\n`op` is a binary function of type `a -\u003e a -\u003e a` (typical examples are binary arithmetic functions like `+`, `-`, `*`, `/`).\n\nWe want to apply this operation on the two expressions `(eval e1)` and `(eval e2)`.\nAs these expressions both are to be executed within the same monadic context we have to use `liftM2` to lift `op` into this context:\n\n```haskell\n-- | Promote a function to a monad, scanning the monadic arguments from\n-- left to right.  For example,\n--\n-- \u003e liftM2 (+) [0,1] [0,2] = [0,2,1,3]\n-- \u003e liftM2 (+) (Just 1) Nothing = Nothing\n--\nliftM2  :: (Monad m) =\u003e (a1 -\u003e a2 -\u003e r) -\u003e m a1 -\u003e m a2 -\u003e m r\nliftM2 f m1 m2 = do { x1 \u003c- m1; x2 \u003c- m2; return (f x1 x2) }\n```\n\nThe last step is the evaluation of `Let x e1 e2` expressions like `Let \"x\" (Val 7) (BinOp (+) (Var \"x\") (Val 5))`. To make this work we have to evaluate `e1` and extend the environment by a binding of the variable `x` to the result of that evaluation.\nThen we have to evaluate `e2` in the context of the extended environment:\n\n```haskell\neval (Let x e1 e2)    = eval e1 \u003e\u003e= \\v -\u003e           -- bind the result of (eval e1) to v\n                        local ((x,v):) (eval e2)    -- add (x,v) to the env, eval e2 in the extended env\n```\n\nThe interesting part here is the helper function `local f m` which applies `f` to the environment and then executes `m` against the (locally) changed environment.\nProviding a locally modified environment as the scope of the evaluation of `e2` is exactly what the `let` binding intends:\n\n```haskell\n-- | Executes a computation in a modified environment.\nlocal :: (r -\u003e r) -- ^ The function to modify the environment.\n        -\u003e m a    -- ^ @Reader@ to run in the modified environment.\n        -\u003e m a\n\ninstance MonadReader r ((-\u003e) r) where\n    local f m = m . f\n```\n\nNow we can use `eval` to evaluate our example expression:\n\n```haskell\ninterpreterDemo = do\n    putStrLn \"Interpreter -\u003e Reader Monad + ADTs + pattern matching\"\n    let exp1 = Let \"x\"\n                (BinOp (+) (Val 4) (Val 5))\n                (BinOp (*) (Val 2) (Var \"x\"))\n    print $ runReader (eval exp1) env\n\n-- an then in GHCi:\n\n\u003e interpreterDemo\n18\n```\n\nBy virtue of the `local` function we used `MonadReader` as if it provided modifiable state. So for many use cases that require only *local* state modifications its not required to use the somewhat more tricky `MonadState`.\n\nWriting the interpreter function with a `MonadState` looks like follows:\n\n```haskell\neval1 :: (MonadState (Env a) m) =\u003e Exp a -\u003e m a\neval1 (Val i)          = return i\neval1 (Var x)          = gets (fetch x)\neval1 (BinOp op e1 e2) = liftM2 op (eval1 e1) (eval1 e2)\neval1 (Let x e1 e2)    = eval1 e1        \u003e\u003e= \\v -\u003e\n                         modify ((x,v):) \u003e\u003e\n                         eval1 e2\n```\n\nThis section was inspired by ideas presented in [Quick Interpreters with the Reader Monad](https://donsbot.wordpress.com/2006/12/11/quick-interpreters-with-the-reader-monad/).\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/Interpreter.hs)\n\n\u003c!-- \n### ? → MonadFail\n\ntbd.\n--\u003e\n\n### Aspect Weaving → Monad Transformers\n\n\u003e In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a \"pointcut\" specification, such as \"log all function calls when the function's name begins with 'set'\". This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code, core to the functionality.\n\u003e\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Aspect-oriented_programming)\n\n### Stacking Monads\n\nIn section\n[Interpreter -\u003e Reader Monad](#interpreter--reader-monad)\nwe specified an Interpreter of a simple expression language by defining a monadic `eval` function:\n\n```haskell\neval :: Exp a -\u003e Reader (Env a) a  \neval (Var x)          = asks (fetch x)\neval (Val i)          = return i\neval (BinOp op e1 e2) = liftM2 op (eval e1) (eval e2)\neval (Let x e1 e2) = eval e1 \u003e\u003e= \\v -\u003e local ((x,v):) (eval e2)\n```\n\nUsing the `Reader` Monad allows to thread an environment through all recursive calls of `eval`.\n\nA typical extension to such an interpreter would be to provide a log mechanism that allows tracing of the actual sequence of all performed evaluation steps.\n\nIn Haskell the typical way to provide such a log is by means of the `Writer Monad`.\n\nBut how to combine the capabilities of the `Reader` monad code with those of the `Writer` monad?\n\nThe answer is `MonadTransformer`s: specialized types that allow us to stack two monads into a single one that shares the behavior of both.\n\nIn order to stack the `Writer` monad on top of the `Reader` we use the transformer type `WriterT`:\n\n```haskell\n-- adding a logging capability to the expression evaluator\neval :: Show a =\u003e Exp a -\u003e WriterT [String] (Reader (Env a)) a\neval (Var x)          = tell [\"lookup \" ++ x] \u003e\u003e asks (fetch x)\neval (Val i)          = tell [show i] \u003e\u003e return i\neval (BinOp op e1 e2) = tell [\"Op\"] \u003e\u003e liftM2 op (eval e1) (eval e2)\neval (Let x e1 e2)    = do\n    tell [\"let \" ++ x]\n    v \u003c- eval e1\n    tell [\"in\"]\n    local ((x,v):) (eval e2)\n```\n\nThe signature of `eval` has been extended by Wrapping `WriterT [String]` around `(Reader (Env a))`. This denotes a Monad that combines a `Reader (Env a)` with a `Writer [String]`.  `Writer [String]` is a `Writer` that maintains a list of strings as log.\n\nThe resulting Monad supports function of both `MonadReader` and `MonadWriter` typeclasses. As you can see in the equation for `eval (Var x)` we are using `MonadWriter.tell` for logging and `MonadReader.asks` for obtaining the environment and compose both monadic actions by `\u003e\u003e`:\n\n```haskell\neval (Var x)          = tell [\"lookup \" ++ x] \u003e\u003e asks (fetch x)\n```\n\nIn order to execute this stacked up monads we have to apply the `run` functions of `WriterT` and `Reader`:\n\n```haskell\nghci\u003e runReader (runWriterT (eval letExp)) [(\"pi\",pi)]\n(6.283185307179586,[\"let x\",\"let y\",\"Op\",\"5.0\",\"7.0\",\"in\",\"Op\",\"lookup y\",\"6.0\",\"in\",\"Op\",\"lookup pi\",\"lookup x\"])\n````\n\nFor more details on MonadTransformers please have a look at the following tutorials:\n\n[MonadTransformers Wikibook](https://en.wikibooks.org/wiki/Haskell/Monad_transformers)\n\n[Monad Transformers step by step](https://page.mi.fu-berlin.de/scravy/realworldhaskell/materialien/monad-transformers-step-by-step.pdf)\n\n### Specifying AOP semantics with MonadTransformers\n\nWhat we have seen so far is that it possible to form Monad stacks that combine the functionality of the Monads involved: In a way a MonadTransformer adds capabilities that are cross-cutting to those of the underlying Monad.\n\nIn the following lines I want to show how MonadTransformers can be used to specify the formal semantics of Aspect Oriented Programming. I have taken the example from Mark P. Jones paper\n[The Essence of AspectJ](https://pdfs.semanticscholar.org/c4ce/14364d88d533fac6aa53481b719aa661ce73.pdf).\n\n#### An interpreter for MiniPascal\n\nWe start by defining a simple imperative language \u0026ndash; MiniPascal:\n\n```haskell\n-- | an identifier type\ntype Id = String\n\n-- | Integer expressions\ndata IExp = Lit Int\n    | IExp :+: IExp\n    | IExp :*: IExp\n    | IExp :-: IExp\n    | IExp :/: IExp\n    | IVar Id deriving (Show)\n\n-- | Boolean expressions\ndata BExp = T\n    | F\n    | Not BExp\n    | BExp :\u0026: BExp\n    | BExp :|: BExp\n    | IExp :=: IExp\n    | IExp :\u003c: IExp deriving (Show)\n\n-- | Staments\ndata Stmt = Skip        -- no op\n    | Id := IExp        -- variable assignment\n    | Begin [Stmt]      -- a sequence of statements\n    | If BExp Stmt Stmt -- an if statement\n    | While BExp Stmt   -- a while loop\n    deriving (Show)\n```\n\nWith this igredients its possible to write imperative programs like the following `while` loop that sums up the natural numbers from 1 to 10:\n\n```haskell\n-- an example program: the MiniPascal equivalent of `sum [1..10]`\nprogram :: Stmt\nprogram =\n    Begin [\n        \"total\" := Lit 0,\n        \"count\" := Lit 0,\n        While (IVar \"count\" :\u003c: Lit 10)\n            (Begin [\n                \"count\" := (IVar \"count\" :+: Lit 1),\n                \"total\" := (IVar \"total\" :+: IVar \"count\")\n            ])\n    ]\n```\n\nWe define the semantics of this language with an interpreter:\n\n```haskell\n-- | the store used for variable assignments\ntype Store = Map Id Int\n\n-- | evaluate numeric expression.\niexp :: MonadState Store m =\u003e IExp -\u003e m Int\niexp (Lit n) = return n\niexp (e1 :+: e2) = liftM2 (+) (iexp e1) (iexp e2)\niexp (e1 :*: e2) = liftM2 (*) (iexp e1) (iexp e2)\niexp (e1 :-: e2) = liftM2 (-) (iexp e1) (iexp e2)\niexp (e1 :/: e2) = liftM2 div (iexp e1) (iexp e2)\niexp (IVar i)    = getVar i\n\n-- | evaluate logic expressions\nbexp :: MonadState Store m =\u003e BExp -\u003e m Bool\nbexp T           = return True\nbexp F           = return False\nbexp (Not b)     = fmap not (bexp b)\nbexp (b1 :\u0026: b2) = liftM2 (\u0026\u0026) (bexp b1) (bexp b2)\nbexp (b1 :|: b2) = liftM2 (||) (bexp b1) (bexp b2)\nbexp (e1 :=: e2) = liftM2 (==) (iexp e1) (iexp e2)\nbexp (e1 :\u003c: e2) = liftM2 (\u003c)  (iexp e1) (iexp e2)\n\n-- | evaluate statements\nstmt :: MonadState Store m =\u003e Stmt -\u003e m ()\nstmt Skip       = return ()\nstmt (i := e)   = do x \u003c- iexp e; setVar i x\nstmt (Begin ss) = mapM_ stmt ss\nstmt (If b t e) = do\n    x \u003c- bexp b\n    if x then stmt t\n         else stmt e\nstmt (While b t) = loop\n    where loop = do\n            x \u003c- bexp b\n            when x $ stmt t \u003e\u003e loop\n\n-- | a variable assignments updates the store (which is maintained in the state)\nsetVar :: (MonadState (Map k a) m, Ord k) =\u003e k -\u003e a -\u003e m ()\nsetVar i x = do\n    store \u003c- get\n    put (Map.insert i x store)\n\n-- | lookup a variable in the store. return 0 if no value is found\ngetVar :: MonadState Store m =\u003e Id -\u003e m Int\ngetVar i = do\n    s \u003c- get\n    case Map.lookup i s of\n        Nothing  -\u003e return 0\n        (Just v) -\u003e return v\n\n-- | evaluate a statement\nrun :: Stmt -\u003e Store\nrun s = execState (stmt s) (Map.fromList [])\n\n-- and then in GHCi:\nghci\u003e run program\nfromList [(\"count\",10),(\"total\",55)]\n```\n\nSo far this is nothing special, just a minimal interpreter for an imperative language. Side effects in form of variable assignments are modelled with an environment that is maintained in a state monad.\n\nIn the next step we want to extend this language with features of aspect oriented programming in the style of *AspectJ*: join points, point cuts, and advices.\n\n#### An Interpreter for AspectPascal\n\nTo keep things simple we will specify only two types of joint points: variable assignment and variable reading:\n\n```haskell\ndata JoinPointDesc = Get Id | Set Id\n```\n\n`Get i` describes a join point at which the variable `i` is read, while `Set i` described a join point at which\na value is assigned to the variable `i`.\n\nFollowing the concepts of ApectJ pointcut expressions are used to describe sets of join points.\nThe abstract syntax for pointcuts is as follows:\n\n```haskell\ndata PointCut = Setter                  -- the pointcut of all join points at which a variable is being set\n              | Getter                  -- the pointcut of all join points at which a variable is being read\n              | AtVar Id                -- the point cut of all join points at which a the variable is being set or read\n              | NotAt PointCut          -- not a\n              | PointCut :||: PointCut  -- a or b\n              | PointCut :\u0026\u0026: PointCut  -- a and b\n```\n\nFor example this syntax can be used to specify the pointcut of\nall join points at which the variable `x` is set:\n\n```haskell\n(Setter :\u0026\u0026: AtVar \"x\")\n```\n\nThe following function computes whether a `PointCut` contains a given `JoinPoint`:\n\n```haskell\nincludes :: PointCut -\u003e (JoinPointDesc -\u003e Bool)\nincludes Setter     (Set i) = True\nincludes Getter     (Get i) = True\nincludes (AtVar i)  (Get j) = i == j\nincludes (AtVar i)  (Set j) = i == j\nincludes (NotAt p)  d       = not (includes p d)\nincludes (p :||: q) d       = includes p d || includes q d\nincludes (p :\u0026\u0026: q) d       = includes p d \u0026\u0026 includes q d\nincludes _ _                = False\n```\n\nIn AspectJ aspect oriented extensions to a program are described using the notion of advices.\nWe follow the same design here: each advice includes a pointcut to specify the join points at which the\nadvice should be used, and a statement (in MiniPascal syntax) to specify the action that should be performed at each matching join point.\n\nIn AspectPascal we only support two kinds of advice: `Before`, which will be executed on entry to a join point, and\n`After` which will be executed on the exit from a join point:\n\n```haskell\ndata Advice = Before PointCut Stmt\n            | After  PointCut Stmt\n```\n\nThis allows to define `Advice`s like the following:\n\n```haskell\n-- the countSets Advice traces each setting of a variable and increments the counter \"countSet\"\ncountSets = After (Setter :\u0026\u0026: NotAt (AtVar \"countSet\") :\u0026\u0026: NotAt (AtVar \"countGet\"))\n                  (\"countSet\" := (IVar \"countSet\" :+: Lit 1))\n\n-- the countGets Advice traces each lookup of a variable and increments the counter \"countGet\"\ncountGets = After (Getter :\u0026\u0026: NotAt (AtVar \"countSet\") :\u0026\u0026: NotAt (AtVar \"countGet\"))\n                  (\"countGet\" := (IVar \"countGet\" :+: Lit 1))\n```\n\nThe rather laborious PointCut definition is used to select access to all variable apart from `countGet` and `countSet`.\nThis is required as the action part of the `Advices` are normal MiniPascal statements that are executed by the same interpreter as the main program which is to be extended by advices. If those filters were not present execution of those advices would result in non-terminating loops, as the action statements also access variables.\n\nA complete AspectPascal program will now consist of a `stmt` (the original program) plus a list of `advices` that should be executed to implement the cross-cutting aspects:\n\n```haskell\n-- | Aspects are just a list of Advices\ntype Aspects = [Advice]\n```\n\nIn order to extend our interpreter to execute additional behaviour decribed in `advices` we will have to provide all evaluating functions with access to the `Aspects`.\nAs the `Aspects` will not be modified at runtime the typical solution would be to provide them by a `Reader Aspects` monad.\nWe already have learnt that we can use a MonadTransformer to stack our existing `State` monad with a `Reader` monad. The respective Transformer is `ReaderT`.\nWe thus extend the signature of the evaluation functions accordingly, eg:\n\n```haskell\n-- from:\niexp :: MonadState Store m =\u003e IExp -\u003e m Int\n\n-- to:\niexp :: MonadState Store m =\u003e IExp -\u003e ReaderT Aspects m Int\n```\n\nApart from extendig the signatures we have to modify all places where variables are accessed to apply the matching advices.\nSo for instance in the equation for `iexp (IVar i)` we specify that `(getVar i)` should be executed with applying all advices that match the read access to variable `i` \u0026ndash; that is `(Get i)` by writing:\n\n```haskell\niexp (IVar i)    = withAdvice (Get i) (getVar i)\n```\n\nSo the complete definition of `iexp` is:\n\n```haskell\niexp :: MonadState Store m =\u003e IExp -\u003e ReaderT Aspects m Int\niexp (Lit n) = return n\niexp (e1 :+: e2) = liftM2 (+) (iexp e1) (iexp e2)\niexp (e1 :*: e2) = liftM2 (*) (iexp e1) (iexp e2)\niexp (e1 :-: e2) = liftM2 (-) (iexp e1) (iexp e2)\niexp (e1 :/: e2) = liftM2 div (iexp e1) (iexp e2)\niexp (IVar i)    = withAdvice (Get i) (getVar i)\n```\n\n\u003e [...] if `c` is a computation corresponding to some join point with description `d`, then `withAdvice d c` wraps the\nexecution of `c` with the execution of the appropriate Before and After advice, if any:\n\n```haskell\nwithAdvice :: MonadState Store m =\u003e JoinPointDesc -\u003e ReaderT Aspects m a -\u003e ReaderT Aspects m a\nwithAdvice d c = do\n    aspects \u003c- ask                -- obtaining the Aspects from the Reader monad\n    mapM_ stmt (before d aspects) -- execute the statements of all Before advices\n    x \u003c- c                        -- execute the actual business logic\n    mapM_ stmt (after d aspects)  -- execute the statements of all After advices\n    return x\n\n-- collect the statements of Before and After advices matching the join point\nbefore, after :: JoinPointDesc -\u003e Aspects -\u003e [Stmt]\nbefore d as = [s | Before c s \u003c- as, includes c d]\nafter  d as = [s | After  c s \u003c- as, includes c d]\n```\n\nIn the same way the equation for variable assignment `stmt (i := e)` we specify that `(setVar i x)` should be executed with applying all advices that match the write access to variable `i` \u0026ndash; that is `(Set i)` by noting:\n\n```haskell\nstmt (i := e)   = do x \u003c- iexp e; withAdvice (Set i) (setVar i x)\n```\n\nThe complete implementation for `stmt` then looks like follows:\n\n```haskell\nstmt :: MonadState Store m =\u003e Stmt -\u003e ReaderT Aspects m ()\nstmt Skip       = return ()\nstmt (i := e)   = do x \u003c- iexp e; withAdvice (Set i) (setVar i x)\nstmt (Begin ss) = mapM_ stmt ss\nstmt (If b t e) = do\n    x \u003c- bexp b\n    if x then stmt t\n         else stmt e\nstmt (While b t) = loop\n    where loop = do\n            x \u003c- bexp b\n            when x $ stmt t \u003e\u003e loop\n```\n\nFinally we have to extend `run` function to properly handle the monad stack:\n\n```haskell\nrun :: Aspects -\u003e Stmt -\u003e Store\nrun a s = execState (runReaderT (stmt s) a) (Map.fromList [])\n\n-- and then in GHCi:\nghci\u003e run [] program\nfromList [(\"count\",10),(\"total\",55)]\n\nghci\u003e run [countSets] program\nfromList [(\"count\",10),(\"countSet\",22),(\"total\",55)]\n\nghci\u003e run [countSets, countGets] program\nfromList [(\"count\",10),(\"countGet\",41),(\"countSet\",22),(\"total\",55)]\n```\n\nSo executing the program with an empty list of advices yields the same result as executing the program with initial interpreter. Once we execute the program with the advices `countGets` and `countSets` the resulting map contains values for the variables `countGet` and `countSet` which have been incremented by the statements of both advices.\n\nWe have utilized Monad Transformers to extend our original interpreter in a minamally invasive way, to provide a formal and executable semantics for a simple aspect-oriented language in the style of AspectJ.\n\n\u003c!-- \n### ? → MonadFix\n\ntbd.\n--\u003e\n\n### Composite → SemiGroup → Monoid\n\n\u003eIn software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that is treated the same way as a single instance of the same type of object. The intent of a composite is to \"compose\" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.\n\u003e (Quoted from [Wikipedia](https://en.wikipedia.org/wiki/Composite_pattern))\n\nA typical example for the composite pattern is the hierarchical grouping of test cases to TestSuites in a testing framework. Take for instance the following class diagram from the [JUnit cooks tour](http://junit.sourceforge.net/doc/cookstour/cookstour.htm) which shows how JUnit applies the Composite pattern to group `TestCases` to `TestSuites` while both of them implement the `Test` interface:\n\n![Composite Pattern used in Junit](http://junit.sourceforge.net/doc/cookstour/Image5.gif)\n\nIn Haskell we could model this kind of hierachy with an algebraic data type (ADT):\n\n```haskell\n-- the composite data structure: a Test can be either a single TestCase\n-- or a TestSuite holding a list of Tests\ndata Test = TestCase TestCase\n          | TestSuite [Test]\n\n-- a test case produces a boolean when executed\ntype TestCase = () -\u003e Bool\n```\n\nThe function `run` as defined below can either execute a single TestCase or a composite TestSuite:\n\n```haskell\n-- execution of a Test.\nrun :: Test -\u003e Bool\nrun (TestCase t)  = t () -- evaluating the TestCase by applying t to ()\nrun (TestSuite l) = all (True ==) (map run l) -- running all tests in l and return True if all tests pass\n\n-- a few most simple test cases\nt1 :: Test\nt1 = TestCase (\\() -\u003e True)\nt2 :: Test\nt2 = TestCase (\\() -\u003e True)\nt3 :: Test\nt3 = TestCase (\\() -\u003e False)\n-- collecting all test cases in a TestSuite\nts = TestSuite [t1,t2,t3]\n```\n\nAs run is of type `run :: Test -\u003e Bool` we can use it to execute single `TestCases` or complete `TestSuites`.\nLet's try it in GHCI:\n\n```haskell\nghci\u003e run t1\nTrue\nghci\u003e run ts\nFalse\n```\n\nIn order to aggregate TestComponents we follow the design of JUnit and define a function `addTest`. Adding two atomic Tests will result in a TestSuite holding a list with the two Tests. If a Test is added to a TestSuite, the test is added to the list of tests of the suite. Adding TestSuites will merge them.\n\n```haskell\n-- adding Tests\naddTest :: Test -\u003e Test -\u003e Test\naddTest t1@(TestCase _) t2@(TestCase _)   = TestSuite [t1,t2]\naddTest t1@(TestCase _) (TestSuite list)  = TestSuite ([t1] ++ list)\naddTest (TestSuite list) t2@(TestCase _)  = TestSuite (list ++ [t2])\naddTest (TestSuite l1) (TestSuite l2)     = TestSuite (l1 ++ l2)\n```\n\nIf we take a closer look at `addTest` we will see that it is a associative binary operation on the set of `Test`s.\n\nIn mathemathics a set with an associative binary operation is a [Semigroup](https://en.wikipedia.org/wiki/Semigroup).\n\nWe can thus make our type `Test` an instance of the type class `Semigroup` with the following declaration:\n\n```haskell\ninstance Semigroup Test where\n    (\u003c\u003e)   = addTest\n```\n\nWhat's not visible from the JUnit class diagram is how typical object oriented implementations will have to deal with null-references. That is the implementations would have to make sure that the methods `run` and `addTest` will handle empty references correctly.\nWith Haskells algebraic data types we would rather make this explicit with a dedicated `Empty` element.\nHere are the changes we have to add to our code:\n\n```haskell\n-- the composite data structure: a Test can be Empty, a single TestCase\n-- or a TestSuite holding a list of Tests\ndata Test = Empty\n          | TestCase TestCase\n          | TestSuite [Test]\n\n-- execution of a Test.\nrun :: Test -\u003e Bool\nrun Empty         = True -- empty tests will pass\nrun (TestCase t)  = t () -- evaluating the TestCase by applying t to ()\n--run (TestSuite l) = foldr ((\u0026\u0026) . run) True l\nrun (TestSuite l) = all (True ==) (map run l) -- running all tests in l and return True if all tests pass\n\n-- addTesting Tests\naddTest :: Test -\u003e Test -\u003e Test\naddTest Empty t                           = t\naddTest t Empty                           = t\naddTest t1@(TestCase _) t2@(TestCase _)   = TestSuite [t1,t2]\naddTest t1@(TestCase _) (TestSuite list)  = TestSuite ([t1] ++ list)\naddTest (TestSuite list) t2@(TestCase _)  = TestSuite (list ++ [t2])\naddTest (TestSuite l1) (TestSuite l2)     = TestSuite (l1 ++ l2)\n```\n\nFrom our additions it's obvious that `Empty` is the identity element of the `addTest` function. In Algebra a Semigroup with an identity element is called *Monoid*:\n\n\u003e In abstract algebra, [...] a monoid is an algebraic structure with a single associative binary operation and an identity element.\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Monoid)\n\nWith haskell we can declare `Test` as an instance of the `Monoid` type class by defining:\n\n```haskell\ninstance Monoid Test where\n    mempty = Empty\n```\n\nWe can now use all functions provided by the `Monoid` type class to work with our `Test`:\n\n```haskell\ncompositeDemo = do\n    print $ run $ t1 \u003c\u003e t2\n    print $ run $ t1 \u003c\u003e t2 \u003c\u003e t3\n```\n\nWe can also use the function `mconcat :: Monoid a =\u003e [a] -\u003e a` on a list of `Tests`: mconcat composes a list of Tests into a single Test. That's exactly the mechanism of forming a TestSuite from atomic TestCases.\n\n```haskell\ncompositeDemo = do\n    print $ run $ mconcat [t1,t2]\n    print $ run $ mconcat [t1,t2,t3]\n```\n\nThis particular feature of `mconcat :: Monoid a =\u003e [a] -\u003e a` to condense a list of Monoids to a single Monoid can be used to drastically simplify the design of our test framework.\n\nWe need just one more hint from our mathematician friends:\n\n\u003e Functions are monoids if they return monoids\n\u003e [Quoted from blog.ploeh.dk](http://blog.ploeh.dk/2018/05/17/composite-as-a-monoid-a-business-rules-example/)\n\nCurrently our `TestCases` are defined as functions yielding boolean values:\n\n```haskell\ntype TestCase = () -\u003e Bool\n```\n\nIf `Bool` was a `Monoid` we could use `mconcat` to form test suite aggregates. `Bool` in itself is not a Monoid; but together with a binary associative operation like `(\u0026\u0026)` or `(||)` it will form a Monoid.\n\nThe intuitive semantics of a TestSuite is that a whole Suite is \"green\" only when all enclosed TestCases succeed. That is the conjunction of all TestCases must return `True`.\n\n So we are looking for the Monoid of boolean values under conjunction `(\u0026\u0026)`. In Haskell this Monoid is called `All`):\n\n```haskell\n-- | Boolean monoid under conjunction ('\u0026\u0026').\n-- \u003e\u003e\u003e getAll (All True \u003c\u003e mempty \u003c\u003e All False)\n-- False\n-- \u003e\u003e\u003e getAll (mconcat (map (\\x -\u003e All (even x)) [2,4,6,7,8]))\n-- False\nnewtype All = All { getAll :: Bool }\n\ninstance Semigroup All where\n        (\u003c\u003e) = coerce (\u0026\u0026)\n\ninstance Monoid All where\n        mempty = All True\n```\n\nMaking use of `All` our improved definition of TestCases is as follows:\n\n```haskell\ntype SmartTestCase = () -\u003e All\n```\n\nNow our test cases do not directly return a boolean value but an `All` wrapper, which allows automatic conjunction of test results to a single value.\nHere are our redefined TestCases:\n\n```haskell\ntc1 :: SmartTestCase\ntc1 () = All True\ntc2 :: SmartTestCase\ntc2 () = All True\ntc3 :: SmartTestCase\ntc3 () = All False\n```\n\nWe now implement a new evaluation function `run'` which evaluates a `SmartTestCase` (which may be either an atomic TestCase or a TestSuite assembled by `mconcat`) to a single boolean result.\n\n```haskell\nrun' :: SmartTestCase -\u003e Bool\nrun' tc = getAll $ tc ()  \n```\n\nThis version of `run` is much simpler than the original and we can completely avoid the rather laborious `addTest` function. We also don't need any composite type `Test`.\nBy just sticking to the Haskell built-in type classes we achieve cleanly designed functionality with just a few lines of code.\n\n```haskell\ncompositeDemo = do\n    -- execute a single test case\n    print $ run' tc1\n\n    --- execute a complex test suite\n    print $ run' $ mconcat [tc1,tc2]\n    print $ run' $ mconcat [tc1,tc2,tc3]\n```\n\nFor more details on Composite as a Monoid please refer to the following blog:\n[Composite as Monoid](http://blog.ploeh.dk/2018/03/12/composite-as-a-monoid/)\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/Composite.hs)\n\n\u003c!-- \n### ? → Alternative, MonadPlus, ArrowPlus\n--\u003e\n\n### Visitor → Foldable\n\n\u003e [...] the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existent object structures without modifying the structures. It is one way to follow the open/closed principle.\n\u003e (Quoted from [Wikipedia](https://en.wikipedia.org/wiki/Visitor_pattern))\n\nIn functional languages - and Haskell in particular - we have a whole armada of tools serving this purpose:\n\n* higher order functions like map, fold, filter and all their variants allow to \"visit\" lists\n* The Haskell type classes `Functor`, `Foldable`, `Traversable`, etc. provide a generic framework to allow visiting any algebraic datatype by just deriving one of these type classes.\n\n#### Using Foldable\n\n```haskell\n-- we are re-using the Exp data type from the Singleton example\n-- and transform it into a Foldable type:\ninstance Foldable Exp where\n    foldMap f (Val x)   = f x\n    foldMap f (Add x y) = foldMap f x `mappend` foldMap f y\n    foldMap f (Mul x y) = foldMap f x `mappend` foldMap f y\n\nfilterF :: Foldable f =\u003e (a -\u003e Bool) -\u003e f a -\u003e [a]\nfilterF p = foldMap (\\a -\u003e if p a then [a] else [])\n\nvisitorDemo = do\n    let exp = Mul (Add (Val 3) (Val 2))\n                  (Mul (Val 4) (Val 6))\n    putStr \"size of exp: \"\n    print $ length exp\n    putStrLn \"filter even numbers from tree\"\n    print $ filterF even exp\n```\n\nBy virtue of the instance declaration Exp becomes a Foldable instance an can be used with arbitrary functions defined on Foldable like `length` in the example.\n\n`foldMap` can for example be used to write a filtering function `filterF`that collects all elements matching a predicate into a list.\n\n##### Alternative approaches\n\n[Visitory as Sum type](http://blog.ploeh.dk/2018/06/25/visitor-as-a-sum-type/)\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/Visitor.hs)\n\n### Iterator → Traversable\n\n\u003e [...] the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Iterator_pattern)\n\n#### Iterating over a Tree\n\nThe most generic type class enabling iteration over algebraic data types is `Traversable` as it allows combinations of `map` and `fold` operations.\nWe are re-using the `Exp` type from earlier examples to show what's needed for enabling iteration in functional languages.\n\n```haskell\ninstance Functor Exp where\n    fmap f (Var x)       = Var x\n    fmap f (Val a)       = Val $ f a\n    fmap f (Add x y)     = Add (fmap f x) (fmap f y)\n    fmap f (Mul x y)     = Mul (fmap f x) (fmap f y)\n\ninstance Traversable Exp where\n    traverse g (Var x)   = pure $ Var x\n    traverse g (Val x)   = Val \u003c$\u003e g x\n    traverse g (Add x y) = Add \u003c$\u003e traverse g x \u003c*\u003e traverse g y\n    traverse g (Mul x y) = Mul \u003c$\u003e traverse g x \u003c*\u003e traverse g y\n```\n\nWith this declaration we can traverse an `Exp` tree:\n\n```haskell\niteratorDemo = do\n    putStrLn \"Iterator -\u003e Traversable\"\n    let exp = Mul (Add (Val 3) (Val 1))\n                (Mul (Val 2) (Var \"pi\"))\n        env = [(\"pi\", pi)]\n    print $ traverse (\\x c -\u003e if even x then [x] else [2*x]) exp 0\n```\n\nIn this example we are touching all (nested) `Val` elements and multiply all odd values by 2.\n\n#### Combining traversal operations\n\nCompared with `Foldable` or `Functor` the declaration of a `Traversable` instance looks a bit intimidating. In particular the type signature of `traverse`:\n\n```haskell\ntraverse :: (Traversable t, Applicative f) =\u003e (a -\u003e f b) -\u003e t a -\u003e f (t b)\n```\n\nlooks like quite a bit of over-engineering for simple traversals as in the above example.\n\nIn oder to explain the real power of the `Traversable` type class we will look at a more sophisticated example in this section. This example was taken from the paper\n[The Essence of the Iterator Pattern](https://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf).\n\nThe Unix utility `wc` is a good example for a traversal operation that performs several different tasks while traversing its input:\n\n```bash\necho \"counting lines, words and characters in one traversal\" | wc\n      1       8      54\n```\n\nThe output simply means that our input has 1 line, 8 words and a total of 54 characters.\nObviously an efficients implementation of `wc` will accumulate the three counters for lines, words and characters in a single pass of the input and will not run three iterations to compute the three counters separately.\n\nHere is a Java implementation:\n\n```java\nprivate static int[] wordCount(String str) {\n    int nl=0, nw=0, nc=0;         // number of lines, number of words, number of characters\n    boolean readingWord = false;  // state information for \"parsing\" words\n    for (Character c : asList(str)) {\n        nc++;                     // count just any character\n        if (c == '\\n') {\n            nl++;                 // count only newlines\n        }\n        if (c == ' ' || c == '\\n' || c == '\\t') {\n            readingWord = false;  // when detecting white space, signal end of word\n        } else if (readingWord == false) {\n            readingWord = true;   // when switching from white space to characters, signal new word\n            nw++;                 // increase the word counter only once while in a word\n        }\n    }\n    return new int[]{nl,nw,nc};\n}\n\nprivate static List\u003cCharacter\u003e asList(String str) {\n    return str.chars().mapToObj(c -\u003e (char) c).collect(Collectors.toList());\n}\n```\n\nPlease note that the `for (Character c : asList(str)) {...}` notation is just syntactic sugar for\n\n```java\nfor (Iterator\u003cCharacter\u003e iter = asList(str).iterator(); iter.hasNext();) {\n    Character c = iter.next();\n    ...\n}\n```\n\nFor efficiency reasons this solution may be okay, but from a design perspective the solution lacks clarity as the required logic for accumulating the three counters is heavily entangled within one code block. Just imagine how the complexity of the for-loop will increase once we have to add new features like counting bytes, counting white space or counting maximum line width.\n\nSo we would like to be able to isolate the different counting algorithms (*separation of concerns*) and be able to combine them in a way that provides efficient one-time traversal.\n\nWe start with the simple task of character counting:\n\n```haskell\ntype Count = Const (Sum Integer)\n\ncount :: a -\u003e Count b\ncount _ = Const 1\n\ncciBody :: Char -\u003e Count a\ncciBody = count\n\ncci :: String -\u003e Count [a]\ncci = traverse cciBody\n\n-- and then in ghci:\n\u003e cci \"hello world\"\nConst (Sum {getSum = 11})\n```\n\nFor each character we just emit a `Const 1` which are elements of type `Const (Sum Integer)`.\nAs `(Sum Integer)` is the monoid of Integers under addition, this design allows automatic summation over all collected `Const` values.\n\nThe next step of counting newlines looks similar:\n\n```haskell\n-- return (Sum 1) if true, else (Sum 0)\ntest :: Bool -\u003e Sum Integer\ntest b = Sum $ if b then 1 else 0\n\n-- use the test function to emit (Sum 1) only when a newline char is detected\nlciBody :: Char -\u003e Count a\nlciBody c = Const $ test (c == '\\n')\n\n-- define the linecount using traverse\nlci :: String -\u003e Count [a]\nlci = traverse lciBody\n\n-- and the in ghci:\n\u003e lci \"hello \\n world\"\nConst (Sum {getSum = 1})\n```\n\nNow let's try to combine character counting and line counting.\nIn order to match the type declaration for `traverse`:\n\n```haskell\ntraverse :: (Traversable t, Applicative f) =\u003e (a -\u003e f b) -\u003e t a -\u003e f (t b)\n```\n\nWe had to define `cciBody` and `lciBody` so that their return types are `Applicative Functors`.\nThe good news is that the product of two `Applicatives` is again an `Applicative` (the same holds true for Composition of `Applicatives`).\nWith this knowledge we can now use `traverse` to use the product of `cciBody` and `lciBody`:\n\n```haskell\nimport Data.Functor.Product             -- Product of Functors\n\n-- define infix operator for building a Functor Product\n(\u003c#\u003e) :: (Functor m, Functor n) =\u003e (a -\u003e m b) -\u003e (a -\u003e n b) -\u003e (a -\u003e Product m n b)\n(f \u003c#\u003e g) y = Pair (f y) (g y)\n\n-- use a single traverse to apply the Product of cciBody and lciBody\nclci :: String -\u003e Product Count Count [a]\nclci = traverse (cciBody \u003c#\u003e lciBody)\n\n-- and then in ghci:\n\u003e clci \"hello \\n world\"\nPair (Const (Sum {getSum = 13})) (Const (Sum {getSum = 1}))\n```\n\nSo we have achieved our aim of separating line counting and character counting in separate functions while still being able to apply them in only one traversal.\n\nThe only piece missing is the word counting. This is a bit tricky as we can not just increase a counter by looking at each single character but we have to take into account the status of the previously read character as well: \n- If the previous character was non-whitespace and the current is also non-whitespace we are still reading the same word and don't increment the word count.\n- If the previous character was non-whitespace and the current is a whitespace character the last word was ended but we don't increment the word count.\n- If the previous character was whitespace and the current is also whitespace we are still reading whitespace between words and don't increment the word count.\n- If the previous character was whitespace and the current is a non-whitespace character the next word has started and we increment the word count.\n\nKeeping track of the state of the last character could be achieved by using a state monad (and wrapping it as an Applicative Functor to make it compatible with `traverse`). The actual code for this solution is kept in the sourcecode for this section (functions `wciBody'` and `wci'` in particular). But as this approach is a bit noisy I'm presenting a simpler solution suggested by [Noughtmare](https://www.reddit.com/r/haskell/comments/cfjnyu/type_classes_and_software_design_patterns/eub06p5?utm_source=share\u0026utm_medium=web2x).\n\nIn his approach we'll define a data structure that will keep track of the changes between whitespace and non-whitespace:\n\n```haskell\ndata SepCount = SC Bool Bool Integer\n  deriving Show\n\nmkSepCount :: (a -\u003e Bool) -\u003e a -\u003e SepCount\nmkSepCount pred x = SC p p (if p then 0 else 1)\n  where\n    p = pred x\n\ngetSepCount :: SepCount -\u003e Integer\ngetSepCount (SC _ _ n) = n    \n```\n\nWe then define the semantics for `(\u003c\u003e)` which implements the actual bookkeeping needed when `mappend`ing two `SepCount` items:\n\n```haskell\ninstance Semigroup SepCount where\n  (SC l0 r0 n) \u003c\u003e (SC l1 r1 m) = SC l0 r1 x where\n    x | not r0 \u0026\u0026 not l1 = n + m - 1\n      | otherwise = n + m\n```\n\nBased on these definitions we can then implement the wordcounting as follows:\n\n```haskell\nwciBody :: Char -\u003e Const (Maybe SepCount) Integer\nwciBody = Const . Just . mkSepCount isSpace where\n    isSpace :: Char -\u003e Bool\n    isSpace c = c == ' ' || c == '\\n' || c == '\\t'\n\n-- using traverse to count words in a String\nwci :: String -\u003e Const (Maybe SepCount) [Integer]\nwci = traverse wciBody \n\n-- Forming the Product of character counting, line counting and word counting\n-- and performing a one go traversal using this Functor product\nclwci :: String -\u003e (Product (Product Count Count) (Const (Maybe SepCount))) [Integer]\nclwci = traverse (cciBody \u003c#\u003e lciBody \u003c#\u003e wciBody)  \n\n-- extracting the actual Integer value from a `Const (Maybe SepCount) a` expression \nextractCount :: Const (Maybe SepCount) a -\u003e Integer\nextractCount (Const (Just sepCount)) =  getSepCount sepCount  \n\n-- the actual wordcount implementation.\n-- for any String a triple of linecount, wordcount, charactercount is returned\nwc :: String -\u003e (Integer, Integer, Integer)\nwc str =\n    let raw = clwci str\n        cc  = coerce $ pfst (pfst raw)\n        lc  = coerce $ psnd (pfst raw)\n        wc  = extractCount  (psnd raw)\n    in (lc,wc,cc)\n```\n\nThis sections was meant to motivate the usage of the `Traversable` type. Of course the word count example could be solved in much simpler ways. Here is one solution suggested by [NoughtMare](https://www.reddit.com/r/haskell/comments/cfjnyu/type_classes_and_software_design_patterns/ev4m6u6?utm_source=share\u0026utm_medium=web2x).\n\nWe simply use `foldMap` to perform a map / reduce based on our already defined `cciBody`, `lciBody` and `wciBody` functions. As `clwci''` now returns a simple tuple instead of the more clumsy `Product` type also the final wordcound function `wc''` now looks way simpler:\n\n```haskell \nclwci'' :: Foldable t =\u003e t Char -\u003e (Count [a], Count [a], Const (Maybe SepCount) Integer)\nclwci'' = foldMap (\\x -\u003e (cciBody x,  lciBody x, wciBody x))\n\nwc'' :: String -\u003e (Integer, Integer, Integer)\nwc'' str =\n    let (rawCC, rawLC, rawWC) = clwci'' str\n        cc  = coerce rawCC\n        lc  = coerce rawLC\n        wc  = extractCount rawWC\n    in (lc,wc,cc)    \n```\n\nAs map / reduce with `foldMap` is such a powerful tool I've written a [dedicated section on this topic](#map-reduce) further down in this study.\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/Iterator.hs)\n\n\u003c!-- \n### ? → Bifunctor\n\ntbd.\n--\u003e\n\n### The Pattern behind the Patterns → Category\n\n\u003e If you've ever used Unix pipes, you'll understand the importance and flexibility of composing small reusable programs to get powerful and emergent behaviors. Similarly, if you program functionally, you'll know how cool it is to compose a bunch of small reusable functions into a fully featured program.\n\u003e\n\u003eCategory theory codifies this compositional style into a design pattern, the category.\n\u003e [Quoted from HaskellForAll](http://www.haskellforall.com/2012/08/the-category-design-pattern.html)\n\nIn most of the patterns and type classes discussed so far we have seen a common theme: providing means to\ncompose behaviour and structure is one of the most important tools to design complex software by combining\nsimpler components.\n\n#### Function Composition\n\nFunction composition is a powerful and elegant tool to compose complex functionality out of simpler building blocks. We already have seen several examples of it in the course of this study.\nFunctions can be composed by using the binary `(.)` operator:\n\n```haskell\nghci\u003e :type (.)\n(.) :: (b -\u003e c) -\u003e (a -\u003e b) -\u003e a -\u003e c\n```\n\nIt is defined as:\n\n```haskell\n(f . g) x = f (g x)\n```\n\nThis operator can be used to combine simple functions to awesome one-liners (and of course much more useful stuff):\n\n```haskell\nghci\u003e product . filter odd . map length . words . reverse $ \"function composition is awesome\"\n77\n```\n\nFunction composition is associative `(f . g) . h = f . (g . h)`:\n\n```haskell\nghci\u003e (((^2) . length) . words) \"hello world\"\n4\nghci\u003e ((^2) . (length . words)) \"hello world\"\n4\n```\n\nAnd composition has a neutral (or identity) element `id` so that `f . id = id . f`:\n\n```haskell\nghci\u003e (length . id) [1,2,3]\n3\nghci\u003e (id . length) [1,2,3]\n3\n```\n\nThe definitions of `(.)` and `id` plus the laws of associativity and identity match exactly the definition of a category:\n\n\u003e In mathematics, a category [...] is a collection of \"objects\" that are linked by \"arrows\". A category has two basic properties: the ability to compose the arrows associatively and the existence of an identity arrow for each object.\n\u003e\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Category_(mathematics))\n\nIn Haskell a category is defined as as a type class:\n\n```haskell\nclass Category cat where\n    -- | the identity morphism\n    id :: cat a a\n\n    -- | morphism composition\n    (.) :: cat b c -\u003e cat a b -\u003e cat a c\n```\n\n\u003e Please note: The name `Category` may be a bit misleading, since this type class cannot represent arbitrary categories, but only categories whose objects are objects of [`Hask`, the category of Haskell types](https://wiki.haskell.org/Hask).\n\nInstances of `Category` should satisfy that `(.)` and `id` form a Monoid \u0026ndash; that is `id` should be the identity of `(.)` and `(.)` should be associative:\n\n```haskell\nf  . id      =  f            -- (right identity)\nid . f       =  f            -- (left identity)\nf . (g . h)  =  (f . g) . h  -- (associativity)\n```\n\nAs function composition fulfills these category laws the function type constructor `(-\u003e)` can be defined as an instance of the category type class:\n\n```haskell\ninstance Category (-\u003e) where\n    id  = GHC.Base.id\n    (.) = (GHC.Base..)\n```\n\n#### Monadic Composition\n\nIn the section on the [Maybe Monad](#avoiding-partial-functions-by-using-maybe) we have seen that monadic operations can be chained with the Kleisli operator `\u003e=\u003e`:\n\n```haskell\nsafeRoot           :: Double -\u003e Maybe Double\nsafeRoot x\n    | x \u003e= 0    = Just (sqrt x)\n    | otherwise = Nothing\n\nsafeReciprocal     :: Double -\u003e Maybe Double\nsafeReciprocal x\n    | x /= 0    = Just (1/x)\n    | otherwise = Nothing\n\nsafeRootReciprocal :: Double -\u003e Maybe Double\nsafeRootReciprocal = safeReciprocal \u003e=\u003e safeRoot\n```\n\nThe operator `\u003c=\u003c` just flips the arguments of `\u003e=\u003e` and thus provides right-to-left composition.\nWhen we compare the signature of `\u003c=\u003c` with the signature of `.` we notice the similarity of both concepts:\n\n```haskell\n(.)   ::            (b -\u003e   c) -\u003e (a -\u003e   b) -\u003e a -\u003e   c\n(\u003c=\u003c) :: Monad m =\u003e (b -\u003e m c) -\u003e (a -\u003e m b) -\u003e a -\u003e m c\n```\n\nEven the implementation of `\u003c=\u003c` is quite similar to the definition of `.`\n\n```haskell\n(f  .  g) x = f     (g x)\n(f \u003c=\u003c g) x = f =\u003c\u003c (g x)\n```\n\nThe essential diffenerce is that `\u003c=\u003c` maintains a monadic structure when producing its result.\n\nNext we compare signatures of `id` and its monadic counterpart `return`:\n\n```haskell\nid     ::              (a -\u003e   a)\nreturn :: (Monad m) =\u003e (a -\u003e m a)\n```\n\nHere again `return` always produces a monadic structure.\n\nSo the category for Monads can simply be defined as:\n\n```haskell\n-- | Kleisli arrows of a monad.\nnewtype Kleisli m a b = Kleisli { runKleisli :: a -\u003e m b }\n\ninstance Monad m =\u003e Category (Kleisli m) where\n    id = Kleisli return\n    (Kleisli f) . (Kleisli g) = Kleisli (f \u003c=\u003c g)\n```\n\nSo if monadic actions form a category we expect that the law of identity and associativity hold:\n\n```haskell\nreturn \u003c=\u003c f    = f                -- left identity\n\nf \u003c=\u003c return    = f                -- right identity\n\n(f \u003c=\u003c g) \u003c=\u003c h = f \u003c=\u003c (g \u003c=\u003c h)  -- associativity\n```\n\nLet's try to prove it by applying some equational reasoning.\nFirst we take the definition of `\u003c=\u003c`: `(f \u003c=\u003c g) x = f =\u003c\u003c (g x)`\nto expand the above equations:\n\n```haskell\n-- 1. left identity\nreturn \u003c=\u003c f     = f    -- left identity (to be proven)\n(return \u003c=\u003c f) x = f x  -- eta expand\nreturn =\u003c\u003c (f x) = f x  -- expand \u003c=\u003c by above definition\nreturn =\u003c\u003c f     = f    -- eta reduce\nf \u003e\u003e= return     = f    -- replace =\u003c\u003c with \u003e\u003e= and flip arguments\n\n\n-- 2 right identity\nf \u003c=\u003c return     = f    -- right identity (to be proven)\n(f \u003c=\u003c return) x = f x  -- eta expand\nf =\u003c\u003c (return x) = f x  -- expand \u003c=\u003c by above definition\nreturn x \u003e\u003e= f   = f x  -- replace =\u003c\u003c with \u003e\u003e= and flip arguments\n\n-- 3. associativity\n(f \u003c=\u003c g) \u003c=\u003c h             = f \u003c=\u003c (g \u003c=\u003c h)  -- associativity (to be proven)\n((f \u003c=\u003c g) \u003c=\u003c h) x         = (f \u003c=\u003c (g \u003c=\u003c h)) x -- eta expand\n(f \u003c=\u003c g) =\u003c\u003c (h x)         = f =\u003c\u003c ((g \u003c=\u003c h) x) -- expand outer \u003c=\u003c on both sides\n(\\y -\u003e (f \u003c=\u003c g) y) =\u003c\u003c h x = f =\u003c\u003c ((g \u003c=\u003c h) x) -- eta expand on left hand side\n(\\y -\u003e f =\u003c\u003c (g y)) =\u003c\u003c h x = f =\u003c\u003c ((g \u003c=\u003c h) x) -- expand inner \u003c=\u003c on the lhs\n(\\y -\u003e f =\u003c\u003c (g y)) =\u003c\u003c h x = f =\u003c\u003c (g =\u003c\u003c (h x)) -- expand inner \u003c=\u003c on the rhs\nh x \u003e\u003e= (\\y -\u003e f =\u003c\u003c (g y)) = f =\u003c\u003c (g =\u003c\u003c (h x)) -- replace outer =\u003c\u003c with \u003e\u003e= and flip arguments on lhs\nh x \u003e\u003e= (\\y -\u003e g y \u003e\u003e= f)   = f =\u003c\u003c (g =\u003c\u003c (h x)) -- replace inner =\u003c\u003c with \u003e\u003e= and flip arguments on lhs\nh x \u003e\u003e= (\\y -\u003e g y \u003e\u003e= f)   = (g =\u003c\u003c (h x)) \u003e\u003e= f -- replace outer =\u003c\u003c with \u003e\u003e= and flip arguments on rhs\nh x \u003e\u003e= (\\y -\u003e g y \u003e\u003e= f)   = ((h x) \u003e\u003e= g) \u003e\u003e= f -- replace inner =\u003c\u003c with \u003e\u003e= and flip arguments on rhs\nh \u003e\u003e= (\\y -\u003e g y \u003e\u003e= f)     = (h \u003e\u003e= g) \u003e\u003e= f     -- eta reduce\n```\n\nSo we have transformed our three formulas to the following form:\n\n```haskell\nf \u003e\u003e= return   = f\n\nreturn x \u003e\u003e= f = f x\n\nh \u003e\u003e= (\\y -\u003e g y \u003e\u003e= f)  =  (h \u003e\u003e= g) \u003e\u003e= f\n```\n\nThese three equations are equivalent to the [Monad Laws](https://wiki.haskell.org/Monad_laws), which all Monad instances are required to satisfy:\n\n```haskell\nm \u003e\u003e= return    =  m\n\nreturn a \u003e\u003e= k  =  k a\n\nm \u003e\u003e= (\\x -\u003e k x \u003e\u003e= h)  =  (m \u003e\u003e= k) \u003e\u003e= h\n```\n\nSo by virtue of this equivalence any Monad that satisfies the Monad laws automatically satisfies the Category laws.\n\n\u003e If you have ever wondered where those monad laws came from, now you know! They are just the category laws in disguise.\n\u003e Consequently, every new Monad we define gives us a category for free!\n\u003e  \n\u003e Quoted from [The Category Design Pattern](http://www.haskellforall.com/2012/08/the-category-design-pattern.html)\n\n#### Conclusion\n\n\u003e Category theory codifies [the] compositional style into a design pattern, the category. Moreover, category theory gives us a precise\n\u003e prescription for how to create our own abstractions that follow this design pattern: the category laws. These laws differentiate category\n\u003e theory from other design patterns by providing rigorous criteria for what does and does not qualify as compositional.\n\u003e\n\u003e One could easily dismiss this compositional ideal as just that: an ideal, something unsuitable for \"real-world\" scenarios. However, the\n\u003e theory behind category theory provides the meat that shows that this compositional ideal appears everywhere and can rise to the challenge of \u003e messy problems and complex business logic.\n\u003e\n\u003e Quoted from [The Category Design Pattern](http://www.haskellforall.com/2012/08/the-category-design-pattern.html)\n\n\u003c!-- \n### ? → Arrow\n\ntbd.\n--\u003e\n\n### Fluent Api → Comonad\n\n\u003e In software engineering, a fluent interface [...] is a method for designing object oriented APIs based extensively on method chaining with the goal of making the readability of the source code close to that of ordinary written prose, essentially creating a domain-specific language within the interface.\n\u003e\n\u003e [Quoted from Wikipedia](https://en.wikipedia.org/wiki/Fluent_interface)\n\nThe [Builder Pattern](#builder--record-syntax-smart-constructor) is a typical example for a fluent API. The following short Java snippet show the essential elements:\n\n* creating a builder instance\n* invoking a sequence of mutators `with...` on the builder instance\n* finally calling `build()` to let the Builder create an object\n\n```java\nConfigBuilder builder = new ConfigBuilder();\nConfig config = builder\n        .withProfiling()        // Add profiling\n        .withOptimization()     // Add optimization\n        .build();\n}\n```\n\nThe interesting point is that all the `with...` methods are not implemented as `void` method but instead all return the Builder instance, which thus allows to fluently chain the next `with...` call.\n\nLet's try to recreate this fluent chaining of calls in Haskell.\nWe start with a configuration type `Config` that represents a set of option strings (`Options`):\n\n```haskell\ntype Options = [String]\n\nnewtype Config = Conf Options deriving (Show)\n```\n\nNext we define a function `configBuilder` which takes `Options` as input and returns a `Config` instance:\n\n```haskell\nconfigBuilder :: Options -\u003e Config\nconfigBuilder options = Conf options\n\n-- we can use this to construct a Config instance from a list of Option strings:\nghci\u003e configBuilder [\"-O2\", \"-prof\"]\nConf [\"-O2\",\"-prof\"]\n```\n\nIn order to allow chaining of the `with...` functions they always must return a new `Options -\u003e Config` function. So for example `withProfiling` would have the following signature:\n\n```haskell\nwithProfiling :: (Options -\u003e Config) -\u003e (Options -\u003e Config)\n```\n\nThis signature is straightforward but the implementation needs some thinking: we take a function `builder` of type `Options -\u003e Config` as input and must return a new function of the same type that will use the same builder but will add profiling options to the `Options` parameter `opts`:\n\n```haskell\nwithProfiling builder = \\opts -\u003e builder (opts ++ [\"-prof\", \"-auto-all\"])\n```\n\nHLint tells us that this can be written more terse as:\n\n```haskell\nwithProfiling builder opts = builder (opts ++ [\"-prof\", \"-auto-all\"])\n```\n\nIn order to keep notation dense we introduce a type alias for the function type `Options -\u003e Config`:\n\n```haskell\ntype ConfigBuilder = Options -\u003e Config\n```\n\nWith this shortcut we can implement the other `with...` functions as:\n\n```haskell\nwithWarnings :: ConfigBuilder -\u003e ConfigBuilder\nwithWarnings builder opts = builder (opts ++ [\"-Wall\"])\n\nwithOptimization :: ConfigBuilder -\u003e ConfigBuilder\nwithOptimization builder opts = builder (opts ++ [\"-O2\"])\n\nwithLogging :: ConfigBuilder -\u003e ConfigBuilder\nwithLogging builder opts = builder (opts ++ [\"-logall\"])\n```\n\nThe `build()` function is also quite straightforward. It constructs the actual `Config` instance by invoking a given `ConfigBuilder` on an empty list:\n\n```haskell\nbuild :: ConfigBuilder -\u003e Config\nbuild builder = builder mempty\n\n-- now we can use it in ghci:\nghci\u003e print (build (withOptimization (withProfiling configBuilder)))\nConf [\"-O2\",\"-prof\",\"-auto-all\"]\n```\n\nThis does not yet look quite object oriented but with a tiny tweak we'll get quite close. We introduce a special operator `#` that allows to write functional expression in an object-oriented style:\n\n```haskell\n(#) :: a -\u003e (a -\u003e b) -\u003e b\nx # f = f x\ninfixl 0 #\n```\n\nWith this operator we can write the above example as:\n\n```haskell\nconfig = configBuilder\n    # withProfiling    -- add profiling\n    # withOptimization -- add optimizations\n    # build\n```\n\nSo far so good. But what does this have to do with Comonads?\nIn the following I'll demonstrate how the chaining of functions as shown in our `ConfigBuilder` example follows a pattern that is covered by the `Comonad` type class.\n\nLet's have a second look at the `with*` functions:\n\n```haskell\nwithWarnings :: ConfigBuilder -\u003e ConfigBuilder\nwithWarnings builder opts = builder (opts ++ [\"-Wall\"])\n\nwithProfiling :: ConfigBuilder -\u003e ConfigBuilder\nwithProfiling builder opts = builder (opts ++ [\"-prof\", \"-auto-all\"])\n```\n\nThese functions all are containing code for explicitely concatenating the `opts` argument with additional `Options`.\nIn order to reduce repetitive coding we are looking for a way to factor out the concrete concatenation of `Options`.\nGoing this route the `with*` function could be rewritten as follows:\n\n```haskell\nwithWarnings'' :: ConfigBuilder -\u003e ConfigBuilder\nwithWarnings'' builder = extend' builder [\"-Wall\"]\n\nwithProfiling'' :: ConfigBuilder -\u003e ConfigBuilder\nwithProfiling'' builder = extend' builder [\"-prof\", \"-auto-all\"]\n```\n\nHere `extend'` is a higher order function that takes a `ConfigBuilder` and an `Options` argument (`opts2`) and returns a new function that returns a new `ConfigBuilder` that concatenates its input `opts1` with the original `opts2` arguments:\n\n```haskell\nextend' :: ConfigBuilder -\u003e Options -\u003e ConfigBuilder\nextend' builder opts2 = \\opts1 -\u003e builder (opts1 ++ opts2)\n-- or even denser without explicit lambda:\nextend' builder opts2 opts1 = builder (opts1 ++ opts2)\n```\n\nWe could carry this idea of refactoring repetitive code even further by eliminating the `extend'` from the `with*` functions. Of course this will change the signature of the functions:\n\n```haskell\nwithWarnings' :: ConfigBuilder -\u003e Config\nwithWarnings' builder = builder [\"-Wall\"]\n\nwithProfiling' :: ConfigBuilder -\u003e Config\nwithProfiling' builder = builder [\"-prof\", \"-auto-all\"]\n```\n\nIn order to form fluent sequences of such function calls we need an improved version of the `extend` function  which transparently handles the concatenation of `Option` arguments and also keeps the chain of `with*` functions open for the next `with*` function being applied:\n\n```haskell\nextend'' :: (ConfigBuilder -\u003e Config) -\u003e ConfigBuilder -\u003e ConfigBuilder\nextend'' withFun builder opt2 = withFun (\\opt1 -\u003e builder (opt1 ++ opt2))\n```\n\nIn order to use `extend''` efficiently in user code we have to modify our `#` operator slightly to transparently handle the extending of `ConfigBuilder` instances when chaining functions of type `ConfigBuilder -\u003e Config`:\n\n```haskell\n(#\u003e\u003e) :: ConfigBuilder -\u003e (ConfigBuilder -\u003e Config) -\u003e ConfigBuilder\nx #\u003e\u003e f = extend'' f x\ninfixl 0 #\u003e\u003e\n```\n\nUser code would then look like follows:\n\n```haskell\nconfigBuilder\n    #\u003e\u003e withProfiling'\n    #\u003e\u003e withOptimization'\n    #\u003e\u003e withLogging'\n    # build\n    # print\n```\n\nNow let's have a look at the definition of the `Comonad` type class. Being the dual of `Monad` it defines two functions `extract` and `extend` which are the duals of `return` and `(\u003e\u003e=)`:\n\n```haskell\nclass Functor w =\u003e Comonad w where\n    extract :: w a -\u003e a\n    extend  :: (w a -\u003e b) -\u003e w a -\u003e w b\n```\n\nWith the knowledge that `((-\u003e) a)` is an instance of `Functor` we can define a `Comonad` instance for `((-\u003e) Options)`:\n\n```haskell\ninstance {-# OVERLAPPING #-} Comonad ((-\u003e) Options) where\n    extract :: (Options -\u003e config) -\u003e config\n    extract builder = builder mempty\n    extend :: ((Options -\u003e config) -\u003e config') -\u003e  (Options -\u003e config) -\u003e (Options -\u003e config')\n    extend withFun builder opt2 = withFun (\\opt1 -\u003e builder (opt1 ++ opt2))\n```\n\nNow let's again look at the functions `build` and `extend''`:\n\n```haskell\nbuild :: (Options -\u003e Config) -\u003e Config\nbuild builder = builder mempty\n\nextend'' :: ((Options -\u003e Config) -\u003e Config) -\u003e (Options -\u003e Config) -\u003e (Options -\u003e Config)\nextend'' withFun builder opt2 = withFun (\\opt1 -\u003e builder (opt1 ++ opt2))\n```\n\nIt's obvious that `build` and `extract` are equivalent as well as `extend''` and `extend`. So we have been inventing a `Comonad` without knowing about it.\n\nBut we are even more lucky! Our `Options` type (being just a synonym for `[String]`) together with the concatenation operator `(++)` forms a `Monoid`.\nAnd for any `Monoid m` `((-\u003e) m)` is a Comonad:\n\n```haskell\ninstance Monoid m =\u003e Comonad ((-\u003e) m)  -- as defined in Control.Comonad\n```\n\nSo we don't have to define our own instance of Comonad but can rely on the predefined and more generic `((-\u003e) m)`.\n\nEquipped with this knowledge we define a more generic version of our `#\u003e\u003e` chaining operator:\n\n```haskell\n(#\u003e) :: Comonad w =\u003e w a -\u003e (w a -\u003e b) -\u003e w b\nx #\u003e f = extend f x\ninfixl 0 #\u003e\n```\n\nBased on this definition we can finally rewrite the user code as follows\n\n```haskell\n    configBuilder\n        #\u003e withProfiling'\n        #\u003e withOptimization'\n        #\u003e withLogging'\n        # extract  -- # build would be fine as well\n        # print\n```\n\nThis section is based on examples from [You could have invented Comonads](http://www.haskellforall.com/2013/02/you-could-have-invented-comonads.html). Please also check this [blogpost](http://gelisam.blogspot.com/2013/07/comonads-are-neighbourhoods-not-objects.html) which comments on the notion of *comonads as objects* in Gabriel Gonzales original posting.\n\n[Sourcecode for this section](https://github.com/thma/LtuPatternFactory/blob/master/src/FluentApi.hs).\n\n## Beyond type class patterns\n\nThe patterns presented in this chapter don't have a direct correspondence to specific type classes. They rather map to more general concepts of functional programming.\n\n### Dependency Injection → Parameter Binding, Partial Application\n\n\u003e [...] Dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.\n\u003e\n\u003e This fundamental requirement means that using values (services) produced within the class from new or static methods is prohibited. The client should accept values passed in from outside. This allows the client to make acquiring dependencies someone else's problem.\n\u003e (Quoted from [Wikipedia](https://en.wikipedia.org/wiki/Dependency_injection))\n\nIn functional languages this is achieved by binding the formal parameters of a function to values.\n\nLet's see how this works in a real world example. Say we have been building a renderer that allows to produce a markdown representation of a data type that represents the table of contents of a document:\n\n```haskell\n-- | a table of contents consists of a heading and a list of entries\ndata TableOfContents = Section Heading [TocEntry]\n\n-- | a ToC entry can be a heading or a sub-table of contents\ndata TocEntry = Head Heading | Sub TableOfContents\n\n-- | a heading can be just a title string or an url with a title and the actual link\ndata Heading = Title String | Url String String\n\n-- | render a ToC entry as a Markdown String with the proper indentation\nteToMd :: Int -\u003e TocEntry -\u003e String\nteToMd depth (Head head) = headToMd depth head\nteToMd depth (Sub toc)   = tocToMd  depth toc\n\n-- | render a heading as a Markdown String with the proper indentation\nheadToMd :: Int -\u003e Heading -\u003e String\nheadToMd depth (Title str)     = indent depth ++ \"* \" ++ str ++ \"\\n\"\nheadToMd depth (Url title url) = indent depth ++ \"* [\" ++ title ++ \"](\" ++ url ++ \")\\n\"\n\n-- | convert a ToC to Markdown String. The parameter depth is used for proper indentation.\ntocToMd :: Int -\u003e TableOfContents -\u003e String\ntocToMd depth (Section heading entries) = headToMd depth heading ++ concatMap (teToMd (depth+2)) entries\n\n-- | produce a String of length n, consisting only of blanks\nindent :: Int -\u003e String\nindent n = replicate n ' '\n\n-- | render a ToC as a Text (consisting of properly indented Markdown)\ntocToMDText :: TableOfContents -\u003e T.Text\ntocToMDText = T.pack . tocToMd 0\n```\n\nWe can use these definitions to create a table of contents data structure and to render it to markdown syntax:\n\n```haskell\ndemoDI = do\n    let toc = Section (Title \"Chapter 1\")\n                [ Sub $ Section (Title \"Section a\")\n                    [Head $ Title \"First Heading\",\n                     Head $ Url \"Second Heading\" \"http://the.url\"]\n                , Sub $ Section (Url \"Section b\" \"http://the.section.b.url\")\n                    [ Sub $ Section (Title \"UnderSection b1\")\n                        [Head $ Title \"First\", Head $ Title \"Second\"]]]\n    putStrLn $ T.unpack $ tocToMDText toc\n\n-- and the in ghci:\nghci \u003e demoDI\n* Chapter 1\n  * Section a\n    * First Heading\n    * [Second Heading](http://the.url)\n  * [Section b](http://the.section.b.url)\n    * UnderSection b1\n      * First\n      * Second\n```\n\nSo far so good. But of course we also want to be able to render our `TableOfContent` to HTML.\nAs we don't want to repeat all the coding work for HTML we think about using an existing Markdown library.\n\nBut we don't want any hard coded dependencies to a specific library in our code.\n\nWith these design ideas in mind we specify a rendering processor:\n\n```haskell\n-- | render a ToC as a Text with html markup.\n--   we specify this function as a chain of parse and rendering functions\n--   which must be provided externally\ntocToHtmlText :: (TableOfContents -\u003e T.Text) -- 1. a renderer function from ToC to Text with markdown markups\n              -\u003e (T.Text -\u003e MarkDown)        -- 2. a parser function from Text to a MarkDown document\n              -\u003e (MarkDown -\u003e HTML)          -- 3. a renderer function from MarkDown to an HTML document\n              -\u003e (HTML -\u003e T.Text)            -- 4. a renderer function from HTML to Text\n              -\u003e TableOfContents             -- the actual ToC to be rendered\n              -\u003e T.Text                      -- the Text output (containing html markup)\ntocToHtmlText tocToMdText textToMd mdToHtml htmlToText =\n    tocToMdText \u003e\u003e\u003e    -- 1. render a ToC as a Text (consisting of properly indented Markdown)\n    textToMd    \u003e\u003e\u003e    -- 2. parse text with Markdown to a MarkDown data structure\n    mdToHtml    \u003e\u003e\u003e    -- 3. convert the MarkDown dat","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthma%2FLtuPatternFactory","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthma%2FLtuPatternFactory","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthma%2FLtuPatternFactory/lists"}