{"id":13512113,"url":"https://github.com/alhassy/HaskellCheatSheet","last_synced_at":"2025-03-30T22:31:57.568Z","repository":{"id":108701103,"uuid":"251249808","full_name":"alhassy/HaskellCheatSheet","owner":"alhassy","description":"A reference sheet for the basics of the mind-expanding Haskell language ^_^","archived":false,"fork":false,"pushed_at":"2020-04-05T02:41:57.000Z","size":1261,"stargazers_count":30,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-18T14:49:13.260Z","etag":null,"topics":["applicatives","cheatsheet","functional-programming","functors","haskell","monads","typeclasses"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alhassy.png","metadata":{"files":{"readme":"README.org","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2020-03-30T08:48:19.000Z","updated_at":"2024-12-31T22:49:39.000Z","dependencies_parsed_at":"2023-03-10T11:15:59.866Z","dependency_job_id":null,"html_url":"https://github.com/alhassy/HaskellCheatSheet","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/alhassy%2FHaskellCheatSheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FHaskellCheatSheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FHaskellCheatSheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FHaskellCheatSheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alhassy","download_url":"https://codeload.github.com/alhassy/HaskellCheatSheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246390896,"owners_count":20769475,"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":["applicatives","cheatsheet","functional-programming","functors","haskell","monads","typeclasses"],"created_at":"2024-08-01T03:01:30.480Z","updated_at":"2025-03-30T22:31:56.049Z","avatar_url":"https://github.com/alhassy.png","language":null,"funding_links":[],"categories":["Others"],"sub_categories":[],"readme":"# Created 2020-04-04 Sat 22:32\n#+OPTIONS: toc:nil d:nil\n#+OPTIONS: toc:nil d:nil\n#+TITLE: Haskell CheatSheet\n#+AUTHOR: [[https://alhassy.github.io/][Musa Al-hassy]]\n#+export_file_name: README.org\n\nA reference sheet for the basics of the mind-expanding Haskell language (•̀ᴗ•́)و\n\n#+begin_quote\n*The listing sheet, as PDF, can be found\n [[https://alhassy.github.io/HaskellCheatSheet/CheatSheet.pdf][here]]*,\n or as a [[https://alhassy.github.io/HaskellCheatSheet/CheatSheet_Portrait.pdf][single column portrait]],\n while below is an unruly html rendition.\n#+end_quote\n\nThis reference sheet is built from a\n[[https://github.com/alhassy/CheatSheet][CheatSheets with Org-mode]]\nsystem.\n\n#+html: \u003cp align=\"center\"\u003e\u003ca href=\"https://www.haskell.org/\"\u003e\u003cimg src=\"https://img.shields.io/badge/GHC-8.6.4-b48ead.svg?style=plastic\"/\u003e\u003c/a\u003e\n\n#+toc: headlines 2\n#+macro: blurb A reference sheet for the basics of the mind-expanding Haskell language (•̀ᴗ•́)و\n\n#+latex_header: \\usepackage{titling,parskip}\n#+latex_header: \\usepackage{eufrak} % for mathfrak fonts\n#+latex_header: \\usepackage{multicol,xparse,newunicodechar}\n\n#+latex_header: \\usepackage{etoolbox}\n\n#+latex_header: \\newif\\iflandscape\n#+latex_header: \\landscapetrue\n\n#+latex_header_extra: \\iflandscape \\usepackage[landscape, margin=0.5in]{geometry} \\else \\usepackage[margin=0.5in]{geometry} \\fi\n\n#+latex_header: \\def\\cheatsheetcols{2}\n#+latex_header: \\AfterEndPreamble{\\begin{multicols}{\\cheatsheetcols}}\n#+latex_header: \\AtEndDocument{ \\end{multicols} }\n\n#+latex_header: \\let\\multicolmulticols\\multicols\n#+latex_header: \\let\\endmulticolmulticols\\endmulticols\n#+latex_header: \\RenewDocumentEnvironment{multicols}{mO{}}{\\ifnum#1=1 #2 \\def\\columnbreak{} \\else \\multicolmulticols{#1}[#2] \\fi}{\\ifnum#1=1 \\else \\endmulticolmulticols\\fi}\n\n#+latex_header: \\def\\maketitle{}\n#+latex: \\fontsize{9}{10}\\selectfont\n\n#+latex_header: \\def\\cheatsheeturl{}\n\n#+latex_header: \\usepackage[dvipsnames]{xcolor} % named colours\n#+latex: \\definecolor{grey}{rgb}{0.5,0.5,0.5}\n\n#+latex_header: \\usepackage{color}\n#+latex_header: \\definecolor{darkgreen}{rgb}{0.0, 0.3, 0.1}\n#+latex_header: \\definecolor{darkblue}{rgb}{0.0, 0.1, 0.3}\n#+latex_header: \\hypersetup{colorlinks,linkcolor=darkblue,citecolor=darkblue,urlcolor=darkgreen}\n\n#+latex_header: \\setlength{\\parindent}{0pt}\n\n\n#+latex_header: \\def\\cheatsheetitemsep{-0.5em}\n#+latex_header: \\let\\olditem\\item\n#+latex_header_extra: \\def\\item{\\vspace{\\cheatsheetitemsep}\\olditem}\n\n#+latex_header: \\usepackage{CheatSheet/UnicodeSymbols}\n\n#+latex_header: \\makeatletter\n#+latex_header: \\AtBeginEnvironment{minted}{\\dontdofcolorbox}\n#+latex_header: \\def\\dontdofcolorbox{\\renewcommand\\fcolorbox[4][]{##4}}\n#+latex_header: \\makeatother\n\n\n\n#+latex_header: \\RequirePackage{fancyvrb}\n#+latex_header: \\DefineVerbatimEnvironment{verbatim}{Verbatim}{fontsize=\\scriptsize}\n\n\n#+macro: newline @@latex: \\newline@@\n\n#+latex_header: \\def\\cheatsheeturl{https://github.com/alhassy/HaskellCheatSheet}\n\n#+latex_header: \\def\\cheatsheetcols{2}\n#+latex_header: \\landscapetrue\n#+latex_header: \\def\\cheatsheetitemsep{-0.5em}\n\n#+latex_header: \\newunicodechar{𝑻}{\\ensuremath{T}}\n#+latex_header: \\newunicodechar{⊕}{\\ensuremath{\\oplus}}\n#+latex_header: \\newunicodechar{≈}{\\ensuremath{\\approx}}\n#+latex_header: \\newunicodechar{𝓍}{\\ensuremath{x}}\n#+latex_header: \\newunicodechar{α}{\\ensuremath{\\alpha}}\n#+latex_header: \\newunicodechar{β}{\\ensuremath{\\beta}}\n#+latex_header: \\newunicodechar{ε}{\\ensuremath{\\epsilon}}\n#+latex_header: \\newunicodechar{∂}{\\ensuremath{\\partial}}\n#+latex_header: \\newunicodechar{⊝}{\\ensuremath{\\ominus}}\n#+latex_header: \\newunicodechar{₋}{\\ensuremath{_-}}\n#+latex_header: \\newunicodechar{⟶}{\\ensuremath{\\rightarrow}}\n#+latex_header: \\newunicodechar{∉}{\\ensuremath{\\not\\in}}\n#+latex_header: \\newunicodechar{ }{\\ensuremath{\\;\\;}}\n\n#+begin_quote\n- [[#hello-home][Hello, Home!]]\n- [[#pattern-matching][Pattern Matching]]\n- [[#local-bindings][Local Bindings]]\n- [[#operators][Operators]]\n- [[#types][Types]]\n- [[#tuples][Tuples]]\n- [[#lists][Lists]]\n  - [[#pattern-matching-on-lists][Pattern Matching on Lists]]\n  - [[#common-methods-on-lists][Common Methods on Lists]]\n- [[#list-design-patterns][List ‘Design Patterns’]]\n  - [[#map][Map]]\n  - [[#filter][Filter]]\n  - [[#fold][Fold]]\n- [[#algebraic-data-types][Algebraic data types]]\n- [[#typeclasses-and-overloading][Typeclasses and overloading]]\n- [[#functor][Functor]]\n  - [[#identity-axiom][Identity Axiom]]\n  - [[#fusion-axiom][Fusion Axiom]]\n  - [[#functors-do-not-necessarily-contain-anything][Functors do not necessarily ‘contain’ anything]]\n  - [[#misc-results-about-functors][Misc results about Functors]]\n- [[#functor-examples][Functor Examples]]\n- [[#applicative][Applicative]]\n  - [[#axioms][Axioms]]\n  - [[#canonical-form----liftn][Canonical Form -- =liftN=]]\n  - [[#monoidal-presentation][Monoidal Presentation]]\n- [[#applicative-examples][Applicative Examples]]\n- [[#do-notation----subtle-difference-between-applicatives-and-monads][~Do~-Notation ---Subtle difference between applicatives and monads]]\n  - [[#do-notation-with-tuples-and-functions][Do-notation with tuples and functions]]\n- [[#formal-definition-of-do-notation][Formal Definition of ~Do~-Notation]]\n- [[#monad-laws][Monad Laws]]\n- [[#monad-examples][Monad Examples]]\n- [[#running-example----a-simple-arithmetic-language][Running Example ---A Simple Arithmetic Language]]\n- [[#maybe----possibly-failing-computations][Maybe ---Possibly Failing Computations]]\n- [[#writer----logging-information-as-we-compute][Writer ---Logging Information as we Compute]]\n- [[#reader----accessing-global-read-only-data][Reader ---Accessing ‘Global, read-only, data’]]\n- [[#state----read-and-write-to-local-storage][State ---Read and write to local storage]]\n- [[#reads][Reads]]\n#+end_quote\n\n* Hello, Home!\n\n#+begin_src haskell :tangle home.hs\nmain = do putStr \"What's your name? \"\n          name \u003c- getLine\n          putStrLn (\"It's 2020, \" ++ name ++ \"! Stay home, stay safe!\")\n#+end_src\n\n* Pattern Matching\n\nFunctions can be defined using the usual ~if_then_else_~ construct, or\n   as expressions /guarded/ by Boolean expressions as in mathematics, or\n   by /pattern matching/ ---a form of ‘syntactic comparision’.\n\n#+begin_src haskell\nfact n = if n == 0 then 1 else n * fact (n - 1)\n\nfact' n | n == 0 = 1\n       | n != 0 = n * fact' (n - 1)\n\nfact'' 0 = 1\nfact'' n = n * fact'' (n - 1)\n#+end_src\n\nThe above definitions of the factorial function are all equal.\n\nGuards, as in the second version, are a form of ‘multi-branching conditional’.\n\nIn the final version, when a call, say, ~fact 5~ happens we compare\n/syntactically/ whether ~5~ and the first pattern ~0~ are the same. They are not,\nso we consider the second case with the understanding that an identifier\nappearing in a pattern matches /any/ argument, so the second clause is used.\n\nHence, when pattern matching is used, order of equations matters: If we\ndeclared the ~n~-pattern first, then the call ~fact 0~ would match it and we end\nup with ~0 * fact (-1)~, which is not what we want!\n\nIf we simply defined the final ~fact~ using /only/ the first clause, then\n~fact 1~ would crash with the error /Non-exhaustive patterns in function fact/.\nThat is, we may define /partial functions/ by not considering all possible shapes of\ninputs.\n\nSee also [[https://gitlab.haskell.org/ghc/ghc/-/wikis/view-patterns][“view patterns”]].\n\n* Local Bindings\n\nAn equation can be qualified by a ~where~ or ~let~ clause for defining values or\nfunctions used only within an expression.\n\n#+begin_src haskell\n  …e…e…e where e = ℯ𝓍𝓅𝓇\n≈ let e = ℯ𝓍𝓅𝓇 in …ℯ𝓍𝓅𝓇…ℯ𝓍𝓅𝓇…ℯ𝓍𝓅𝓇\n#+end_src\n\nIt sometimes happens in functional programs that one clause of a function needs\n/part of/ an argument, while another operators on the /whole/ argument. It it\ntedious (and inefficient) to write out the structure of the complete argument\nagain when referring to it.\nUse the “as operator” ~@~ to label all or part of an argument, as in\n\n#+begin_src haskell\nf label@(x:y:ys) = ⋯\n#+end_src\n\n* Operators\nInfix operators in Haskell must consist entiry of ‘symbols’ such as ~\u0026, ^, !, …~\nrather than alphanumeric characters. Hence, while addition, ~+~, is written infix,\ninteger division is written prefix with ~div~.\n\nWe can always use whatever fixity we like:\n- If ~f~ is any /prefix/ binary function, then ~x `f` y~ is a valid /infix/ call.\n- If ~⊕~ is any /infix/ binary operator, then ~(⊕) x y~ is a valid /prefix/ call.\n\nIt is common to fix one argument ahead of time, e.g., ~λ x → x + 1~ is the\nsuccessor operation and is written more tersely as ~(+1)~. More generally, ~(⊕r) =\nλ x → x ⊕ r~.\n\nThe usual arithmeic operations are ~+, /, *, -~ but ~%~ is used to make fractions.\n\nThe Boolean operations are ~==, /=, \u0026\u0026, ||~ for equality, discrepancy,\nconjunction, and disjunction.\n\n* Types\n\nType are inferred, but it is better to write them explicitly so that /you\ncommunicate your intentions to the machine/. If you /think/ that expression ~e~ has\ntype ~τ~ then write ~e :: τ~ to /communicate/ that to the machine, which will silently\naccept your claim or reject it loudly.\n\n| Type               | Name        | Example Value         |\n|--------------------+-------------+-----------------------|\n| Small integers     | ~Int~       | ~42~                  |\n| Unlimited integers | ~Integer~   | ~7376541234~          |\n| Reals              | ~Float~     | ~3.14~ and ~2 % 5~    |\n| Booleans           | ~Boolean~   | ~True~ and ~False~    |\n| Characters         | ~Char~      | ~'a'~ and ~'3'~       |\n| Strings            | ~String~    | ~\"salam\"~             |\n| Lists              | ~[α]~       | ~[]~ or ~[x₁, …, xₙ]~ |\n| Tuples             | ~(α, β, γ)~ | ~(x₁, x₂, x₃)~        |\n| Functions          | ~α → β~     | ~λ x → ⋯~             |\n\n/Polymorphism/ is the concept that allows one function to operate on different types.\n- A function whose type contains /variables/ is called a /polymorphic function/.\n- The simplest polymorphic function is ~id ∷ a -\u003e a~, defined by ~id x = x~.\n\n* Tuples\n\n*Tuples* ~(α₁, …, αₙ)~ are types with values written ~(x₁, …, xₙ)~  where\neach ~xᵢ :: αᵢ~. The are a form of ‘record’ or ‘product’ type.\n\nE.g., ~(True, 3, 'a') :: (Boolean, Int, Char)~.\n\nTuples are used to “return multiple values” from a function.\n\nTwo useful functions on tuples of length 2 are:\n#+begin_src haskell\nfst :: (α, β) → α\nfst (x, y) = x\n\nsnd :: (α, β) → β\nsnd (x, y) = β\n#+end_src\n\nIf in addition you ~import Control.Arrow~ then you may use:\n#+begin_src haskell\nfirst :: (α → τ) → (α, β) → (τ, β)\nfirst f (x, y) = (f x, y)\n\nsecond :: (β → τ) → (α, β) → (α, τ)\nsecond g (x, y) = (x, g y)\n\n(***) :: (α → α′) → (β → β) → (α, β) → (α′, β′)\n(f *** g) (x, y) = (f x, g y)\n\n(\u0026\u0026\u0026) :: (τ → α) → (τ → β) → τ → (α, β)\n(f \u0026\u0026\u0026 g) x = (f x, g x)\n#+end_src\n\n* Lists\n\n*Lists* are sequences of items of the same type.\n\nIf each ~xᵢ ∷ α~ then ~[x₁, …, xₙ] ∷ [α]~.\n\nLists are useful for functions that want to ‘non-deterministicly’ return a\nvalue:  They return a list of all possible values.\n\n- The /empty list/ is ~[]~\n- We “cons”truct nonempty lists using ~(:) ∷ α → [α] → [α]~\n- Abbreviation: ~[x₁, …, xₙ] = x₁ ∶ (x₂ ∶ (⋯ (xₙ ∶ [])))~\n- /List comprehensions/: ~[f x | x \u003c- xs, p x]~ is the list of elements\n  ~f x~ where ~x~ is an element from list ~xs~ and ~x~ satisfies the property ~p~\n  - E.g., ~[2 * x | x \u003c- [2, 3, 4], x \u003c 4] ≈ [2 * 2, 2 * 3] ≈ [4, 6]~\n- Shorthand notation for segments: ~u~ may be ommitted to yield /infinite lists/\n  - ~[l .. u] = [l, l + 1, l + 2, …, u]~.\n  - ~[a, b, .., u] = [a + i * step | i \u003c- [0 .. u - a] ] where step = b - a~\n\n*Strings* are just lists of characters: ~\"c₀c₁…cₙ\" ≈ ['c₀', …, 'cₙ']~.\n- Hence, all list methods work for strings.\n\n** Pattern Matching on Lists\n*Pattern matching on lists*\n#+begin_src haskell\nprod []     = 1\nprod (x:xs) = x * prod xs\n\nfact n = prod [1 .. n]\n#+end_src\n\nIf your function needs a case with a list of say, length 3, then you can match\ndirectly on that /shape/ via ~[x, y, z]~ ---which is just an abbreviation for the\nshape ~x:y:z:[]~. Likewise, if we want to consider lists of length /at least 3/ then\nwe match on the shape ~x:y:z:zs~. E.g., define the function that produces the\nmaximum of a non-empty list, or the function that removes adjacent duplicates\n---both require the use of guards.\n\n** Common Methods on Lists\n#+begin_src haskell\n[x₀, …, xₙ] !! i = xᵢ\n[x₀, …, xₙ] ++ [y₀, …, yₘ] = [x₀, …, xₙ, y₀, …, yₘ]\nconcat [xs₀, …, xsₙ] = xs₀ ++ ⋯ ++ xsₙ\n\n{- Partial functions -}\nhead [x₀, …, xₙ] = x₀\ntail [x₀, …, xₙ] = [x₁, …, xₙ]\ninit [x₀, …, xₙ] = [x₀, …, xₙ₋₁]\nlast [x₀, …, xₙ] = xₙ\n\ntake k [x₀, …, xₙ] = [x₀, …, xₖ₋₁]\ndrop k [x₀, …, xₙ] = [xₖ, …, xₙ]\n\nsum     [x₀, …, xₙ] =  x₀ + ⋯ + xₙ\nprod    [x₀, …, xₙ] =  x₀ * ⋯ * xₙ\nreverse [x₀, …, xₙ] =  [xₙ, …, x₀]\nelem x  [x₀, …, xₙ] =  x == x₀ || ⋯ || x == xₙ\n\nzip [x₀, …, xₙ] [y₀, …, yₘ]  = [(x₀, y₀), …, (xₖ, yₖ)] where k = n `min` m\nunzip [(x₀, y₀), …, (xₖ, yₖ)] = ([x₀, …, xₖ], [y₀, …, yₖ])\n#+end_src\n\n[[https://en.wikipedia.org/wiki/Conjugacy_class][*Duality*]]: Let ~∂f = reverse . f . reverse~, then ~init = ∂ tail~ and\n~take k = ∂ (drop k)~; even ~pure . head = ∂ (pure . last)~ where ~pure x = [x]~.\n\n* List ‘Design Patterns’\n\nMany functions have the same ‘form’ or ‘design pattern’, a fact which is\ntaken advantage of by defining /higher-order functions/ to factor out the\nstructural similarity of the individual functions.\n\n** Map\n\n~map f xs = [f x | x \u003c- xs]~\n- Transform all elements of a list according to the function ~f~.\n\n** Filter\n~filter p xs = [x | x \u003c- xs, p x]~\n- Keep only the elements of the list that satisfy the predicate ~p~.\n- ~takeWhile p xs~ ≈ Take elements of ~xs~ that satisfy ~p~, but stop stop at\n  the first element that does not satisfy ~p~.\n- ~dropWhile p xs~ ≈ Drop all elements until you see one that does not satisfy\n  the predicate.\n- ~xs = takeWhile p xs ++ dropWhile p xs~.\n\n** Fold\nRight-folds let us ‘sum’ up the elements of the list, associating to the right.\n#+begin_src haskell\nfoldr (⊕) e ≈ λ (x₀ : (x₁ : (… : (xₙ : []))))\n              → (x₀ ⊕ (x₁ ⊕ (… ⊕ (xₙ ⊕ e))))\n#+end_src\n\nThis function just replaces cons ~“∶”~ and ~[]~ with ~⊕~ and ~e~. That's all.\n- E.g., replacing ~:,[]~ with themselves does nothing: ~foldr (:) [] = id~.\n\n#+latex: \\newpage\n/All functions on lists can be written as folds!/\n#+begin_src haskell\n   h [] = e  ∧  h (x:xs) = x ⊕ h xs\n≡  h = foldr (λ x rec_call → x ⊕ rec_call) e\n#+end_src\n- Look at the two cases of a function and move them to the two\n  first arguments of the fold.\n  - ~map f = foldr (λ x ys → f x : ys) []~\n  - ~filter p    = foldr (λ x ys → if (p x) then (x:ys) else ys) []~\n  - ~takeWhile p = foldr (λ x ys → if (p x) then (x:ys) else []) []~\n\nYou can also fold leftward, i.e., by associating to the left:\n#+begin_src haskell\nfoldl (⊕) e   ≈   λ       (x₀ : (x₁ : (… :  (xₙ : []))))\n                  → (((e ⊕ x₀) ⊕ x₁) ⊕ … ) ⊕ xₙ\n#+end_src\nUnless the operation ~⊕~ is associative, the folds are generally different.\n- E.g., ~foldl (/) 1 [1..n] ≈ 1 / n!~ where ~n ! = product [1..n]~.\n- E.g., ~-55 = foldl (-) 0 [1..10] ≠ foldr (-) 0 [1..10] = -5~.\n\nIf ~h~ swaps arguments ---~h(x ⊕ y) = h y ⊕ h x~--- then ~h~ swaps folds:\n\n ~h . foldr (⊕) e = foldl (⊝) e′~ where ~e′ = h e~ and ~x ⊝ y = x ⊕ h y~.\n\nE.g., ~foldl (-) 0 xs = - (foldr (+) 0 xs) = - (sum xs)~\n and ~n ! = foldr (*) 1 [1..n] = 1 / foldl (/) 1 [1..n]~.\n\n| /( Floating points are a leaky abstraction! )/ |\n\n* Algebraic data types\n\nWhen we have ‘possible scenarios’, we can make a type to consider each option.\nE.g., ~data Door = Open | Closed~ makes a new datatype with two different values.\nUnder the hood, ~Door~ could be implemented as integers and ~Open~ is 0 and ~Closed~\nis 1; or any other implementation ---/all that matters/ is that we have a new\ntype, ~Door~, with two different values, ~Open~ and ~Closed~.\n\nUsually, our scenarios contain a ‘payload’ of additional information; e.g., ~data\nDoor2 = Open | Ajar Int | Closed~. Here, we have a new way to construct ~Door~\nvalues, such as ~Ajar 10~ and ~Ajar 30~, that we could interpret as denoting how far\nthe door is open/. Under the hood, ~Door2~ could be implemented as pairs of\nintegers, with ~Open~ being ~(0,0)~, ~Ajar n~ being ~(1, n)~, and ~Closed~ being ~(2, 0)~\n---i.e., as the pairs “(value position, payload data)”. Unlike functions, a\nvalue construction such as ~Ajar 10~ cannot be simplified any further; just as the\nlist value ~1:2:3:[]~ cannot be simplified any further. Remember, the\nrepresentation under the hood does not matter, what matters is that we have\nthree possible /construction forms/ of ~Door2~ values.\n\nLanguages, such as C, which do not support such an “algebraic” approach,\nforce you, the user, to actually choose a particular representation ---even\nthough, it does not matter, since we only want /a way to speak of/ “different\ncases, with additional information”.\n\nIn general, we declare the following to get an “enumerated type with payloads”.\n#+begin_src haskell\ndata D = C₀ τ₁ τ₂ … τₘ | C₁ ⋯ | Cₙ ⋯ deriving Show\n#+end_src\nThere are =n= constructors ~Cᵢ~ that make /different/ values of type ~D~; e.g., ~C₀ x₁ x₂\n… xₘ~ is a ~D~-value whenever each ~xᵢ~ is a ~τᵢ~-value. The ~“deriving Show”~ at the end\nof the definition is necessary for user-defined types to make sure that values\nof these types can be printed in a standard form.\n\nWe may now define functions on ~D~ by pattern matching on the possible ways to\n/construct/ values for it; i.e., by considering the cases ~Cᵢ~.\n\nIn-fact, we could have written ~data D α₁ α₂ … αₖ = ⋯~, so that we speak of “D\nvalues /parameterised/ by types αᵢ”. E.g., “lists whose elements are of type α” is\ndefined by ~data List α = Nil | Cons α (List α)~ and, for example, ~Cons 1 (Cons 2\nNil)~ is a value of ~List Int~, whereas ~Cons 'a' Nil~ is of type ~List Char~. ---The\n~List~ type is missing the ~“deriving Show”~, see below for how to /mixin/ such a\nfeature.\n\nFor example, suppose we want to distinguish whether we have an α-value or a\nβ-value, we use ~Either~. Let's then define an example /infix/ function using\npattern matching.\n#+begin_src haskell\ndata Either α β = Left α | Right β\n\n(+++) :: (α → α′) → (β → β′) → Either α β → Either α′ β′\n(f +++ g) (Left  x) = Left $ f x\n(f +++ g) (Right x) = Right $ g x\n\nright :: (β → τ) → Either α β → Either α τ\nright f = id +++ f\n#+end_src\nThe above ~(+++)~ can be found in ~Control.Arrow~ and is also known as ~either~ in the\nstandard library.\n\n* Typeclasses and overloading\n\n/Overloading/ is using the same name to designate operations “of the same nature”\non values of different types.\n\nE.g., the ~show~ function converts its argument into a string; however, it is not\npolymorphic: We cannot define ~show :: α → String~ with one definition since some\nitems, like functions or infinite datatypes, cannot be printed and so this is\nnot a valid type for the function ~show~.\n\nHaskell solves this by having ~Show~ /typeclass/ whose /instance types/ ~α~ each\nimplement a definition of the /class method/ ~show~. The type of ~show~ is written\n~Show α =\u003e α -\u003e String~: /Given an argument of type ~α~, look in the global listing of\n~Show~ instances, find the one for ~α~, and use that;/ if ~α~ has no ~Show~ instance,\nthen we have a type error. One says “the type variable ~α~ has is /restricted/ to be\na ~Show~ instance” ---as indicated on the left side of the ~“=\u003e”~ symbol.\n\nE.g., for the ~List~ datatype we defined, we may declare it to be ‘showable’ like\nso:\n#+begin_quote\n#+begin_src haskell -n 1\n  instance Show a =\u003e Show (List a) where\n    show Nil         = \"Nope, nothing here\"\n    show (Cons x xs) = \"Saw \" ++ show x ++ \", then \" ++ show xs\n#+end_src\n#+end_quote\nThat is:\n1. /If ~a~ is showable, then ~List a~ is also showable./\n2. /Here's how to show ~Nil~ directly./\n3. /We show ~Cons x xs~ by using the ~show~ of ~a~ on ~x~, then recursively showing ~xs~./\n\n|               | Common Typeclasses                                 |\n|---------------+----------------------------------------------------|\n| ~Show~        | Show elements as strings, ~show~                   |\n| ~Read~        | How to read element values from strings, ~read~    |\n| ~Eq~          | Compare elements for equality, ~==~                |\n| ~Num~         | Use literals ~0, 20, …,~ and arithmetic ~+, *, -~  |\n| ~Ord~         | Use comparison relations ~\u003e, \u003c, \u003e=, \u003c=~            |\n| ~Enum~        | Types that can be listed, ~[start .. end]~         |\n| ~Monoid~      | Types that model ‘(untyped) composition’           |\n| ~Functor~     | /Type formers/ that model effectful computation    |\n| ~Applicative~ | Type formers that can sequence effects             |\n| ~Monad~       | Type formers that let effects depend on each other |\n\nThe ~Ord~ typeclass is declared ~class Eq a =\u003e Ord a where ⋯~, so that all ordered\ntypes are necessarily also types with equality. One says ~Ord~ is a /subclass/ of\n~Eq~; and since subclasses /inherit/ all functions of a class, we may always replace\n~(Eq a, Ord a) =\u003e ⋯~ by ~Ord a =\u003e ⋯~.\n\nYou can of-course define your own typeclasses; e.g., the ~Monoid~ class in Haskell\ncould be defined as follows.\n#+begin_src haskell\nclass Semigroup a where\n  (\u003c\u003e) :: a -\u003e a -\u003e a  {- A way to “compose” elements together -}\n  {- Axiom: (x \u003c\u003e y) \u003c\u003e z = x \u003c\u003e (y \u003c\u003e z) -}\n\nclass Semigroup a =\u003e Monoid a where\n  mempty :: a   {- Axiom: This is a ‘no-op’, identity, for composition \u003c\u003e -}\n#+end_src\nExample monoids ~(α, \u003c\u003e, mempty)~ include ~(Int, +, 0)~, ~([α], ++, [])~, and\n (Program statements, sequence “;”, the empty statement) ---this\nlast example is approximated as ~Term~ with ‘let-in’ clauses at the end of this\ncheatsheet. /Typeclasses are interfaces, possibly with axioms specifying their\nbehaviour./\n\nAs shown earlier, Haskell provides a the ~deriving~ mechanism for making it easier\nto define instances of typeclasses, such as ~Show, Read, Eq, Ord, Enum~. How?\nConstructor names are printed and read as written as written in the ~data~\ndeclaration, two values are equal if they are formed by the same construction,\none value is less than another if the constructor of the first is declared in\nthe ~data~ definition before the constructor of the second, and similarly for\nlisting elements out.\n* Functor\n\n/Functors are type formers that “behave” like collections: We can alter their/\n/“elements” without messing with the ‘collection structure’ or ‘element\npositions’./ The well-behavedness constraints are called /the functor axioms/.\n#+begin_src haskell\nclass Functor f where\n  fmap :: (α → β) → f α → f β\n\n(\u003c$\u003e) = fmap {- An infix alias -}\n#+end_src\n\nThe axioms cannot be checked by Haskell, so we can form instances that fail to\nmeet the implicit specifications ---two examples are below.\n\n** Identity Axiom\n\n*Identity Law*: ~fmap id = id~\n\n/Doing no alteration to the contents of a collection does nothing to the collection./\n\nThis ensures that “alterations don't needlessly mess with element values”\ne.g., the following is not a functor since it does.\n#+begin_src haskell :tangle probably.hs\n{- I probably have an item -}\ndata Probably a = Chance a Int\n\ninstance Functor Probably where\n  fmap f (Chance x n) = Chance (f x) (n `div` 2)\n#+end_src\n\n** Fusion Axiom\n*Fusion Law:* ~fmap f . fmap g = fmap (f . g)~\n\n/Reaching into a collection and altering twice is the same as reaching in and\naltering once./\n\nThis ensures that “alterations don't needlessly mess with collection structure”;\ne.g., the following is not a functor since it does.\n\n#+begin_src haskell :tangle pocket.hs\nimport Prelude hiding (Left, Right)\n\n{- I have an item in my left or my right pocket -}\ndata Pocket a = Left a | Right a\n\ninstance Functor Pocket where\n  fmap f (Left  x) = Right (f x)\n  fmap f (Right x) = Left  (f x)\n#+end_src\n\n** Functors do not necessarily ‘contain’ anything\n\nIt is important to note that functors model well-behaved container-like types,\nbut of-course the types do not actually need to contain anything at all! E.g.,\nthe following is a valid functor.\n#+begin_src haskell :tangle Liar.hs\n{- “I totally have an α-value, it's either here or there.” Lies! -}\ndata Liar α = OverHere Int | OverThere Int\n\ninstance Functor Liar where\n  fmap f (OverHere  n) = OverHere  n\n  fmap f (OverThere n) = OverThere n\n#+end_src\nNotice that if we altered ~n~, say by dividing it by two, then we break the\nidentity law; and if we swap the constructors, then we break the fusion law.\nSuper neat stuff!\n\nIn general, functors take something boring and generally furnish it with\n‘coherent’ structure, but *there is not necessarily an α ‘inside’ f α*.\nE.g., ~f α = (ε → α)~ has as values “recipes for forming an α-value”,\nbut unless executed, there is no ~α~-value.\n\n** Misc results about Functors\n\n#+latex: \\vspace{0.5em}\n- ~fmap f xs~ ≈ /for each/ element ~x~ in the ‘collection’ ~xs~, yield ~f x~.\n- Haskell can usually ~derive~ functor instances since they are [[http://archive.fo/U8xIY][unique]]: Only one\n  possible definition of ~fmap~ will work.\n- Reading the functor axioms left-to-right, they can be seen as /optimisation laws/\n  that make a program faster by reducing work.\n- The two laws together say /fmap distributes over composition/:\n  ~fmap (f₁ . f₂ . ⋯ . fₙ)  =  fmap f₁ . ⋯ . fmap fₙ~ for ~n ≥ 0~.\n\n*Naturality Theorems:* If ~p ∷ f a → g a~ for some /functors/ ~f~ and ~g~,\nthen ~fmap f . p  =  p . fmap f~ for any /function/ ~f~.\n\nHence, any generic property ~p ∷ f α → ε~ is invariant over fmaps:\n~p(fmap f xs) = p xs~. E.g., the length of a list does not change even when an\nfmap is applied.\n\n* Functor Examples\n\nLet ~f₁, f₂~ be functors and ~ε~ be a given type.\n\n| Type Former                                                                                                 | ~f α~                  | ~f \u003c$\u003e x~                             |\n|-------------------------------------------------------------------------------------------------------------+------------------------+---------------------------------------|\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Identity.html#t:Identity][Identity]]  | ~α~                    | ~f \u003c$\u003e x = f x~                       |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Applicative.html#t:Const][Constant]]       | ~ε~                    | ~f \u003c$\u003e x = x~                         |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/GHC-List.html][List]]                              | ~[α]~                  | ~f \u003c$\u003e [x₀, …, xₙ] = [f x₀, …, f xₙ]~ |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Either.html#t:Either][Either]]                | ~Either ε α~           | ~f \u003c$\u003e x = right f~                   |\n|-------------------------------------------------------------------------------------------------------------+------------------------+---------------------------------------|\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Product.html#t:Product][Product]]     | ~(f₁ α, f₂ α)~         | ~f \u003c$\u003e (x, y) = (f \u003c$\u003e x, f \u003c$\u003e y)~   |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Compose.html#t:Compose][Composition]] | ~f₁ (f₂ α)~            | ~f \u003c$\u003e x = (fmap f) \u003c$\u003e x~            |\n| [[http://comonad.com/reader/2012/abstracting-with-applicatives/][Sum]]                                      | ~Either (f₁ α) (f₂ α)~ | ~f \u003c$\u003e ea = f +++ f~                  |\n|-------------------------------------------------------------------------------------------------------------+------------------------+---------------------------------------|\n| [[http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Writer-Lazy.html#g:2][Writer]]            | ~(ε, α)~               | ~f \u003c$\u003e (e, x) = (e, f x)~             |\n| [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader.html][Reader]]                    | ~ε → α~                | ~f \u003c$\u003e g = f . g~                     |\n| [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Lazy.html#g:2][State]]             | ~ε → (ε, α)~           | ~f \u003c$\u003e g = second f . g~              |\n\nNotice that writer is the product of the constant and the identity functors.\n\nUnlike reader, the type former ~f α = α → ε~ is /not/ a functor since there is no\nway to implement ~fmap~. In contrast, ~f α = (α → ε, α)~ /does/ have an implementation\nof ~fmap~, but it is not lawful.\n\n* Applicative\n/Applicatives are collection-like types that can apply collections of functions\nto collections of elements./\n\nIn particular, /applicatives can fmap over multiple arguments/; e.g., if we try to\nadd ~Just 2~ and ~Just 3~, we find =(+) \u003c$\u003e Just 2 :: Maybe (Int → Int)= and this is\nnot a function and so cannot be applied further to ~Just 3~ to get ~Just 5~.\nWe have both the function and the value wrapped up, so we need a way to apply\nthe former to the latter. The answer is ~(+) \u003c$\u003e Just 2 \u003c*\u003e Just 3~.\n\n#+begin_src 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  {- “apply” -}\n\n{- Apply associates to the left: p \u003c*\u003e q \u003c*\u003e r = (p \u003c*\u003e q) \u003c*\u003e r) -}\n#+end_src\n\nThe method ~pure~ lets us inject values, to make ‘singleton collections’.\n\n- /Functors transform values inside collections; applicatives can additionally\n  combine values inside collections./\n- Exercise: If ~α~ is a monoid, then so too is ~f α~ for any applicative ~f~.\n\n** Axioms\nThe applicative axioms ensure that apply behaves like usual functional application:\n\n- Identity: ~pure id \u003c*\u003e x = x~ ---c.f., ~id x = x~\n- Homomorphism: ~pure f \u003c*\u003e pure x = pure (f x)~ ---it really is function application\n  on pure values!\n  - Applying a non-effectful function to a non-effectful argument in an effectful\n    context is the same as just applying the function to the argument and then\n    injecting the result into the content.\n- Interchange: ~p \u003c*\u003e pure x = pure ($ x) \u003c*\u003e p~ ---c.f., ~f x = ($ x) f~\n  - Functions ~f~ take ~x~ as input ≈ Values ~x~ project functions ~f~ to particular values\n  - When there is only one effectful component, then it does not matter whether\n    we evaluate the function first or the argument first, there will still only be\n    one effect.\n  - Indeed, this is equivalent to the law: ~pure f \u003c*\u003e q = pure (flip ($)) \u003c*\u003e q \u003c*\u003e pure f~.\n\n- Composition: ~pure (.) \u003c*\u003e p \u003c*\u003e q \u003c*\u003e r = p \u003c*\u003e (q \u003c*\u003e r)~\n   ---c.f., ~(f . g) . h = f . (g . h)~.\n\nIf we view ~f α~ as an “effectful computation on α”, then the above laws ensure\n~pure~ creates an “effect free” context. E.g., if ~f α = [α]~ is considered\n“nondeterminstic α-values”, then ~pure~ just treats usual α-values as\nnondeterminstic but with no ambiguity, and ~fs \u003c*\u003e xs~ reads “if we\nnondeterminsticly have a choice ~f~ from ~fs~, and we nondeterminsticly an ~x~ from\n~xs~, then we nondeterminsticly obtain ~f x~.” More concretely, if I'm given\nrandomly addition or multiplication along with the argument 3 and another\nargument that could be 2, 4, or 6, then the result would be obtained by\nconsidering all possible combinations: ~[(+), (*)] \u003c*\u003e pure 3 \u003c*\u003e [2, 4, 6] =\n[5,7,9,6,12,18]~. The name ~“\u003c*\u003e”~ is suggestive of this ‘cartesian product’ nature.\n\nGiven a definition of apply, the definition of ~pure~ may be obtained\nby unfolding the identity axiom.\n\nUsing these laws, we regain the original ~fmap~ ---since ~fmap~'s are [[http://archive.fo/U8xIY][unique]] in\nHaskell--- thereby further cementing that applicatives model “collections that\ncan be functionally applied”: ~f \u003c$\u003e x = pure f \u003c*\u003e x~. ( Hence, every applicative\nis a functor whether we like it or not. )\n- The identity applicative law is then just the identity law of functor: ~id \u003c$\u003e x = x~.\n- The homomorphism law now becomes: ~pure . f = fmap f . pure~.\n\n  - This is the “naturality law” for ~pure~.\n\n** Canonical Form -- =liftN=\n\n[[http://www.staff.city.ac.uk/~ross/papers/Applicative.pdf][The laws]] may be interpreted as left-to-right rewrite rules and so are a\n procedure for transforming any applicative expression into the canonical form\n of “a pure function applied to effectful arguments”: ~pure f \u003c*\u003e x₁ \u003c*\u003e ⋯ \u003c*\u003e\n xₙ~. In this way, one can compute in-parallel the, necessarily independent, ~xᵢ~\n then combine them together.\n\nNotice that the canonical form generalises ~fmap~ to ~n~-arguments:\nGiven ~f ∷ α₁ → ⋯ → αₙ → β~ and ~xᵢ ∷ f αᵢ~, we obtain an ~(f β)~-value.\nThe case of ~n = 2~ is called ~liftA2~, ~n = 1~ is just ~fmap~, and for ~n = 0~ we have\n~pure~!\n** Monoidal Presentation\n\nNotice that ~lift2A~ is essentially the cartesian product in the setting of lists,\nor ~(\u003c\u0026\u003e)~ below ---c.f., ~sequenceA :: Applicative f ⇒ [f a] → f [a]~.\n\n#+begin_src haskell\n(\u003c\u0026\u003e) :: f a → f b → f (a, b)   {- Not a standard name! -}\n(\u003c\u0026\u003e) = liftA2 (,)  -- i.e., p \u003c\u0026\u003e q = (,) \u003c$\u003e p \u003c*\u003e q\n#+end_src\nThis is a pairing operation with properties of ~(,)~ mirrored at the applicative level:\n#+begin_src haskell\n{- Pure Pairing -} pure x \u003c\u0026\u003e pure y = pure (x, y)\n{- Naturality   -} (f \u0026\u0026\u0026 g) \u003c$\u003e (u \u003c\u0026\u003e v) = (f \u003c$\u003e u) \u003c\u0026\u003e (g \u003c\u0026\u003e v)\n\n{- Left Projection  -} fst \u003c$\u003e (u \u003c\u0026\u003e pure ()) = u\n{- Right Projection -} snd \u003c$\u003e (pure () \u003c\u0026\u003e v)  = v\n{- Associtivity     -} assocl \u003c$\u003e (u \u003c\u0026\u003e (v \u003c\u0026\u003e w)) = (u \u003c\u0026\u003e v) \u003c\u0026\u003e w\n#+end_src\nThe final three laws above suffice to prove the original applicative axioms, and so\nwe may define ~p \u003c*\u003e q = uncurry ($) \u003c$\u003e (p \u003c\u0026\u003e q)~.\n\n* Applicative Examples\n\nLet ~f₁, f₂~ be functors and let ~ε~ a type.\n\n| Functor                                                                                                     | ~f α~                  | ~f \u003c*\u003e x~                                   |\n|-------------------------------------------------------------------------------------------------------------+------------------------+---------------------------------------------|\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Identity.html#t:Identity][Identity]]  | ~α~                    | ~f \u003c*\u003e x = f x~                             |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Applicative.html#t:Const][Constant]]       | ~ε~                    | ~e \u003c*\u003e d = e \u003c\u003e d~                          |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/GHC-List.html][List]]                              | ~[α]~                  | =fs \u003c*\u003e xs = [f x ∣ f \u003c- fs, x \u003c- xs]=      |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Either.html#t:Either][Either]]                | ~Either ε α~           | ~ef \u003c*\u003e ea = right (λ f → right f ea) ef~   |\n|-------------------------------------------------------------------------------------------------------------+------------------------+---------------------------------------------|\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Compose.html#t:Compose][Composition]] | ~f₁ (f₂ α)~            | ~f \u003c*\u003e x = (\u003c*\u003e) \u003c$\u003e f \u003c*\u003e x~               |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Product.html#t:Product][Product]]     | ~(f₁ α, f₂ α)~         | ~(f, g) \u003c*\u003e (x, y) = (f \u003c*\u003e x, g \u003c*\u003e y)~    |\n| [[http://comonad.com/reader/2012/abstracting-with-applicatives/][Sum]]                                      | ~Either (f₁ α) (f₂ α)~ | Challenge: Assume ~η ∷ f₁ a → f₂ a~         |\n|-------------------------------------------------------------------------------------------------------------+------------------------+---------------------------------------------|\n| [[http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Writer-Lazy.html#g:2][Writer]]            | ~(ε, α)~               | ~(a , f) \u003c*\u003e (b, x) = (a \u003c\u003e b, f x)~        |\n| [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader.html][Reader]]                    | ~ε → α~                | ~f \u003c*\u003e g = λ e → f e (g e)~  ---c.f., ~SKI~ |\n| [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Lazy.html#g:2][State]]             | ~ε → (ε, α)~           | ~sf \u003c*\u003e sa = λ e → let (e′, f) = sf e~      |\n|                                                                                                             |                        |                    ~in second f (sa e′)~    |\n\nIn the writer and constant cases, we need ~ε~ to also be a monoid.\nWhen ε is /not/ a monoid, then those two constructions give examples of functors\nthat are /not/ applicatives ---since there is no way to define ~pure~.\nIn contrast, ~f α = (α → ε) → Maybe ε~ is not an applicative since no\ndefinition of apply is lawful.\n\nSince readers ~((-\u003e) r)~ are applicatives, we may, for example, write ~(⊕) \u003c$\u003e f\n\u003c*\u003e g~ as a terse alternative to the “pointwise ⊕” method ~λ x → f x ⊕ g x~. E.g.,\nusing ~(\u0026\u0026)~ gives a simple way to chain predicates.\n\n* ~Do~-Notation ---Subtle difference between applicatives and monads\nRecall the ~map~ operation on lists, we could define it ourselves:\n#+begin_src haskell :tangle delme.hs\nmap' :: (α -\u003e β) -\u003e [α] -\u003e [β]\nmap' f []     = []\nmap' f (x:xs) = let y  = f x\n                    ys = map' f xs\n                in  (y:ys)\n#+end_src\nIf instead the altering function ~f~ returned effectful results,\nthen we could gather the results along with the effect:\n#+begin_src haskell :tangle delme1.hs\n{-# LANGUAGE ApplicativeDo #-}\n\nmapA :: Applicative f =\u003e (a -\u003e f b) -\u003e [a] -\u003e f [b]\nmapA f []     = pure []\nmapA f (x:xs) = do y  \u003c- f x\n                   ys \u003c- mapA f xs\n                   pure (y:ys)\n                {- ≈ (:) \u003c$\u003e f x \u003c*\u003e mapA f xs -}\n#+end_src\n\nApplicative syntax can be a bit hard to write, whereas ~do~-notation is more\nnatural and reminiscent of the imperative style used in defining ~map'~ above. For\ninstance, the intuition that ~fs \u003c*\u003e ps~ is a cartesian product is clearer in\ndo-notation: ~fs \u003c*\u003e ps ≈ do {f ← fs; x ← ps; pure (f x)}~ where the right side is\nread /“for-each f in fs, and each x in ps, compute f x”/.\n\n#+latex: \\columnbreak\n\n[[https://dl.acm.org/doi/pdf/10.1145/3241625.2976007][In-general]], ~do {x₁ ← p₁; …; xₙ ← pₙ; pure e} ≈ pure (λ x₁ … xₙ → e) \u003c*\u003e p₁ \u003c*\u003e ⋯\n\u003c*\u003e pₙ~ *provided* ~pᵢ~ does not mention ~xⱼ~ for ~j \u003c i~; but =e= may refer to all ~xᵢ~. If\nany ~pᵢ~ mentions an earlier ~xⱼ~, then we could not translate the ~do~-notation into\nan applicative expression.\n\nIf ~do {x ← p; y ← qx; pure e}~ has ~qx~ being an expression *depending* on ~x~,\nthen we could say this is an abbreviation for ~(λ x → (λ y → e) \u003c$\u003e qx) \u003c$\u003e p~\nbut this is of type ~f (f β))~. Hence, to allow later computations to depend\non earlier computations, we need a method ~join :: f (f α) → f α~ with which\nwe define  ~do {x ← p; y ← qx; pure e} ≈ join $ ~(λ x -\u003e (λ y → e) \u003c$\u003e qx) \u003c$\u003e p~.\n\nApplicatives with a ~join~ are called monads and they give us a *“programmable\nsemicolon”*. Since later items may depend on earlier ones, ~do {x ← p; y ← q;\npure e}~ could be read /“let x be the value of computation p, let y be the value\nof computation q, then combine the values via expression e”/. Depending on how\n~\u003c*\u003e~ is implemented, such ‘let declarations’ could short-circuit (~Maybe~) or be\nnondeterministic (~List~) or have other effects such as altering state.\n\nAs the ~do~-notation clearly shows, the primary difference between =Monad= and\n=Applicative= is that =Monad= allows dependencies on previous results, whereas\n=Applicative= does not.\n\n** Do-notation with tuples and functions\n\nDo-syntax also works with tuples and functions --c.f., reader monad below---\nsince they are monadic; e.g., every clause ~x \u003c- f~ in a functional do-expression\ndenotes the resulting of applying ~f~ to the (implicit) input.\nMore concretely:\n#+begin_src haskell\ngo :: (Show a, Num a) =\u003e a -\u003e (a, String)\ngo = do {x \u003c- (1+); y \u003c- show; return (x, y)}\n\n-- go 3 = (4, \"3\")\n#+end_src\n\nLikewise, tuples, lists, etc.\n\n* Formal Definition of ~Do~-Notation\n\nFor a general applicative ~f~, a ~do~ expression has the form ~do {C; r}~, where ~C~ is\na (possibly empty) list of commands separated by semicolons, and ~r~ is an\nexpression of type ~f β~, which is also the type of the entire ~do~ expression. Each\ncommand takes the form ~x ← p~, where ~x~ is a variable, or possibly a pattern; if ~p\n:: f α~ then ~x :: α~. In the particular case of the anonymous variable, ~_ ← p~ may\nbe abbreviated to ~p~.\n\nThe translation of a ~do~ expression into ~\u003c*\u003e/join~ operations and ~where~ clauses is\ngoverned by three rules ---the last one only applies in the setting of a monad.\n#+begin_src haskell\n(1)  do {r}           = r\n(2A) do {x ← p; C; r} = q \u003c*\u003e p where q x = do {C; r} --Provided x ∉ C\n(2M) do {x ← p; C; r} = join $ map q p where q x = do {C; r}\n\n{- Fact: When x ∉ C, (2A) = (2M). -}\n#+end_src\n\nBy definition chasing and induction on the number of commands ~C~, we have:\n#+begin_src haskell\n[CollapseLaw]  do {C; do {D; r}} = do {C; D; r}\n#+end_src\nLikewise:\n#+begin_src haskell\n[Map ] fmap f p = do {x ← p; pure (f x)} -- By applicative laws\n[Join] join ps  = do {p ← ps; p}         -- By functor laws\n#+end_src\n\n*Do-Notation Laws*: Here are some desirable usability properties of ~do~-notation.\n#+begin_src haskell\n[RightIdentity]  do {B; x ← p; pure x}       = do {B; p}\n[LeftIdentity ]  do {B; x ← pure e; C; r}    = do {B; C[x ≔ e]; r[x ≔ e]}\n[Associtivity ]  do {B; x ← do {C; p}; D; r} = do {B; C; x ← p; D; r}\n#+end_src\n\nHere, ~B, C, D~ range over sequences of commands and ~C[x ≔ e]~ means the sequence ~C~\nwith all free occruences of ~x~ replaced by ~e~.\n\n- Associtivity gives us a nice way to ‘inline’ other calls.\n- The LeftIdentity law, read right-to-left, lets us “locally give a name” to the\n  possibly complex expression ~e~.\n\n  If ~pure~ forms a singleton collection, then LeftIdentity is a “one-point rule”:\n  We consider /all/ ~x ← pure e~, but there is only /one/ such ~x~, namely ~e~!\n\nIn the applicative case, where the clauses are independent, we can prove, say,\n~RightIdentity~ using the identity law for applicatives ---which says essentially\n\n~do {x \u003c- p; pure x} = p~--- then apply induction on the length of ~B~.\n\nWhat axioms are needed for the monad case to prove the ~do~-notation laws?\n\n* Monad Laws\nHere is the definition of the monad typeclass.\n#+begin_src haskell :tangle del_4.hs\nclass Applicative m =\u003e Monad (m :: * -\u003e *) where\n  (\u003e\u003e=) :: m a -\u003e (a -\u003e m b) -\u003e m b\n\n(\u003c=\u003c) :: Monad m =\u003e (b -\u003e m c) -\u003e (a -\u003e m b) -\u003e a -\u003e m c\nf \u003c=\u003c g = join . fmap f . g\n#+end_src\n\nWhere's ~join~!? Historically, monads entered Haskell first with interface ~(\u003e\u003e=),\nreturn~; later it was realised that ~return = pure~ and the relationship with\napplicative was cemented.\n\n‘Bind’ ~(\u003e\u003e=)~ is definable from ~join~ by ~ma \u003e\u003e= f = join (fmap f ma)~, and, for\nthis reason, bind is known as “flat map” or “concat map” in particular\ninstances. For instance, the second definition of ~do~-notation could be\nexpressed:\n#+begin_src haskell\n(2M′) do {x ← p; C; r} = p \u003e\u003e= q where q x = do {C; r}\n#+end_src\nConversely, ~join ps = do {p ← ps; p} = ps \u003e\u003e= id~. Likewise, with (2M′), note how\n~(\u003c*\u003e)~ can be defined directly in-terms of ~(\u003e\u003e=)~\n\n---c.f., ~mf \u003c*\u003e mx = do {f ← mf;\nx ← mx; return (f x)}~.\n\nSince ~fmap f p = do {x ← p; return (f x)} = p \u003e\u003e= return . f~, in the past monad\ndid not even have functor as a superclass ---c.f., [[http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#v:liftM][liftM]].\n\nThe properties of ~\u003e\u003e=, return~ that prove the desired ~do~-notation laws are:\n#+begin_src haskell\n[LeftIdentity ] return a \u003e\u003e= f   ≡  f a\n[RightIdentity] m \u003e\u003e= return     ≡  m\n[Associtivity ] (m \u003e\u003e= f) \u003e\u003e= g  ≡  m \u003e\u003e= (\\x -\u003e f x \u003e\u003e= g)\n                i.e.,   (m  \u003e\u003e=  (\\x -\u003e f x))  \u003e\u003e=  g\n                       = m  \u003e\u003e=  (\\x -\u003e f x    \u003e\u003e=  g)\n#+end_src\n\nEquivalently, show the ‘fish’ ~(\u003c=\u003c)~ is associative with identity being ~pure~\n---c.f., monoids!\n\nIt is pretty awesome that ~(\u003e\u003e=), return~ give us a functor, an applicative, and\n(dependent) do-notation! Why? Because bind does both the work of ~fmap~ and ~join~.\nThus, ~pure, fmap, join~ suffice to characterise a monad.\n\n| /Join determines how a monad behaves!/ |\n\nThe monad laws can be expressed in terms of ~join~ [[https://en.wikibooks.org/wiki/Haskell/Category_theory#The_monad_laws_and_their_importance][directly]]:\n#+begin_src haskell\n[Associativity] join . fmap join = join . join\n{- The only two ways to get from “m (m (m α))” to “m α” are the same. -}\n\n[Identity Laws] join. fmap pure = join . pure = id\n{- Wrapping up “m α” gives an “m (m α)” which flattens to the original element. -}\n#+end_src\n\nThen, notice that the (free) naturality of join is:\n#+begin_src haskell\njoin . fmap (fmap f) = fmap f . join  ∷  m (m α) → m β\n#+end_src\n\nAgain, note that ~join~ doesn't merely flatten a monad value, but rather performs\nthe necessary logic that determines /how the monad behaves/.\n\nE.g., suppose ~m α = ε → (ε, α)~ is the type of ~α~-values that can be configured\naccording to a fixed environment type ~ε~, along with the possibly updated\nconfiguration ---i.e., functions ~ε → (ε, α)~. Then any ~a ∶ ε → (ε, ε → (ε, α))~ in ~m\n (m α)~ can be considered an element of ~m α~ if we /propagate the environment\nconfiguration/ through the outer layer to obtain a new configuration for the\ninner layer: ~λ e → let (e′, a′) = a e in a′ e′~. The join dictates how a\nconfiguration is /modified then passed along/: We have two actions, ~a~ and ~a′~, and\njoin has /sequenced/ them by pushing the environment through the first thereby\nmodifying it then pushing it through the second.\n\n* Monad Examples\n\nLet ~f₁, f₂~ be functors and let ~ε~ a type.\n\n| Applicative                                                                                                 | ~m α~          | ~join :: m (m α) → m α~                                             |\n|-------------------------------------------------------------------------------------------------------------+----------------+---------------------------------------------------------------------|\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Identity.html#t:Identity][Identity]]  | ~α~            | ~λ x → x~                                                           |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Applicative.html#t:Const][Constant]]       | ~ε~            | ~λ x → x~  ---Shucks!                                               |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/GHC-List.html][List]]                              | ~[α]~          | ~λ xss → foldr (++) [] xss~                                         |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Either.html#t:Either][Either]]                | ~Either ε α~   | Exercise ^_^                                                        |\n|-------------------------------------------------------------------------------------------------------------+----------------+---------------------------------------------------------------------|\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Compose.html#t:Compose][Composition]] | ~f₁ (f₂ α)~    | [[https://stackoverflow.com/q/7040844/3550444][Nope! Not a monad!]] |\n| [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Product.html#t:Product][Product]]     | ~(f₁ α, f₂ α)~ | ~λ p → (fst \u003c$\u003e p, snd \u003c$\u003e p)~                                      |\n|-------------------------------------------------------------------------------------------------------------+----------------+---------------------------------------------------------------------|\n| [[http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Writer-Lazy.html#g:2][Writer]]            | ~(ε, α)~       | ~λ (e, (e′, a)) → (e \u003c\u003e e′, a)~                                     |\n| [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader.html][Reader]]                    | ~ε → α~        | ~λ ra → λ e → ra e e~                                               |\n| [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Lazy.html#g:2][State]]             | ~ε → (ε, α)~   | ~λ ra → λ e → let (e′, a) = ra e in a e′~                           |\n\nIn writer, we need ~ε~ to be a monoid.\n\n- Notice how, in writer, join merges the outer context with the inner context:\n  /Sequential writes are mappended together!/\n- If ~pure~ forms ‘singleton containers’ then ~join~ flattens containers of containers\n  into a single container.\n\nExcluding the trivial monoid, the constant functor is /not/ a monad: It fails the\nmonad identity laws for join. Similarly, ~f α = Maybe (α, α)~ is an applicative\nbut /not/ a monad ---since there is no lawful definition of ~join~. Hence,\napplicatives are strictly more generally than monads.\n\n* Running Example ---A Simple Arithmetic Language\n\nLet's start with a weak language:\n#+begin_src haskell :tangle simple_terms.hs\ndata Term = Int Int | Div Term Term deriving Show\n\nthirteen = Int 1729 `Div` (Int 133 `Div` Int 1)\nboom     = Int 1729 `Div` (Int 12  `Div` Int 0)\n\neval₀ :: Term -\u003e Int\neval₀ (Int n) =  n\neval₀ (n `Div` d) = let top    = eval₀ n\n                        bottom = eval₀ d\n                    in  top `div` bottom\n#+end_src\n\nHow do we accomodate safe division by zero? Print to the user what's happening\nat each step of the calcuation? Have terms that access ‘global’ variables? Have\nterms that can store named expressions then access them later?\n\nWe'll make such languages and their ~eval~'s will be nearly just as simple as this\none (!) but accomodate these other issues.\n\n* [[http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Maybe.html][Maybe]] ---Possibly Failing Computations\nSafe evaluator: No division errors.\n#+begin_src haskell :tangle simple_terms.hs\neval₁ :: Term -\u003e Maybe Int\neval₁ (Int n) = pure n\neval₁ (n `Div` d) = do t \u003c- eval₁ n\n                       b \u003c- eval₁ d\n                       if b == 0 then Nothing else pure (t `div` b)\n#+end_src\nExercise: Rewrite ~evalᵢ~ without ~do~-notation and you'll end-up with nested case\nanalysis leading into a straicase of code that runs right off the page.\n\n- Applicative is enough for ~eval₁, eval₂, eval₃~, but ~eval₄~ needs ~Monad~.\n\n* [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Writer-Lazy.html#g:2][Writer]] ---Logging Information as we Compute\n\nUse a pair type ~W ε α~ to keep track of an environment ~ε~ and a value ~α~.\n#+begin_src haskell :tangle simple_terms.hs\ndata Writer ε α = W ε α deriving Show\n\nwrite :: ε -\u003e Writer ε ()\nwrite e = W e ()\n\ninstance Functor (Writer ε) where\n  fmap f (W e a) = W e (f a)\n#+end_src\nAggregate, merge, environments using their monoidal operation.\n#+begin_src haskell :tangle simple_terms.hs\ninstance Monoid ε =\u003e Applicative (Writer ε) where\n  pure a = W mempty a\n  (W e f) \u003c*\u003e (W d a) = W (e \u003c\u003e d) (f a)\n\ninstance Monoid ε =\u003e Monad (Writer ε) where\n  (\u003e\u003e=) = \\ ma f -\u003e join (pure f \u003c*\u003e ma)\n    where join (W e (W d a)) = W (e \u003c\u003e d) a\n#+end_src\n\nAn evaluator that prints to the user what's going on.\n#+begin_src haskell :tangle simple_terms.hs\neval₂ :: Term -\u003e Writer String Int\neval₂ it@(Int n) = W (\"\\n Evaluating: \" ++ show it) n\neval₂ it@(n `Div` d) = do write $ \"\\n Evaluating: \" ++ show it\n                          t \u003c- eval₂ n\n                          b \u003c- eval₂ d\n                          pure $ (t `div` b)\n\n-- Try this! With “boom”, we get to see up to the boint of the error ^_^\n-- let W e x = eval₂ thirteen in putStrLn e\n#+end_src\n\n#+latex: \\vspace{-1em}\n* [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader.html#g:2][Reader]] ---Accessing ‘Global, read-only, data’\n#+latex: \\hspace{-1.5em}\nUse a function type ~ε → α~ to get ~α~-values that ‘reads’ from a configuration\nenvironment ε.\n#+begin_src haskell :tangle terms_with_vars.hs\ndata Reader ε α = R {run :: ε -\u003e α}\n\ninstance Functor (Reader ε) where\n  fmap f (R g) = R $ f . g\n\ninstance Applicative (Reader ε) where\n  pure a = R $ const a\n  (R f) \u003c*\u003e (R g) = R $ \\e -\u003e f e (g e) {- “S” combinator -}\n\ninstance Monad (Reader ε) where\n  ma \u003e\u003e= f = join (pure f \u003c*\u003e ma)\n    where join (R rf) = R $ \\e -\u003e run (rf e) e\n#+end_src\n\nA language with access to global variables; uninitialised variables are 0 by\ndefault.\n#+begin_src haskell :tangle terms_with_vars.hs\ndata Term = Int Int | Div Term Term | Var String deriving Show\n\ntype GlobalVars = [(String, Int)]\n\nvaluefrom :: String -\u003e GlobalVars -\u003e Int\nvaluefrom x gvs = maybe 0 id $ lookup x gvs\n\neval₃ :: Term -\u003e Reader GlobalVars Int\neval₃ (Int x) = pure x\neval₃ (Var x) = R $ \\e -\u003e x `valuefrom` e\neval₃ (n `Div` d) = do t \u003c- eval₃ n\n                       b \u003c- eval₃ d\n                       pure (t `div` b)\n\nstate    = [(\"x\", 1729), (\"y\", 133)] :: GlobalVars\nthirteen = Var \"x\" `Div` (Var \"y\" `Div` Int 1)\n-- run (eval₃ thirteen) state\n#+end_src\n\n* [[https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Lazy.html#g:2][State]] ---Read and write to local storage\n\nLet's combine writer and reader to get state: We can both read and write to data\nby using functions ~ε → (ε, α)~ that read from an environment ε and result in a\nnew environment as well as a value.\n- ~IO α ≅ State TheRealWorld α~ ;-)\n#+begin_src haskell :tangle terms_with_storage.hs\ndata State ε α = S {run :: ε -\u003e (ε, α)}\n\npush :: Monoid ε =\u003e ε -\u003e State ε ()\npush d = S $ \\e -\u003e (d \u003c\u003e e, ())\n\ninstance Functor (State ε) where\n  fmap f (S g) = S $ \\ e -\u003e let (e', a) = g e in (e', f a)\n\ninstance Applicative (State ε) where\n  pure a = S $ \\e -\u003e (e, a)\n  (S sf) \u003c*\u003e (S g) = S $ \\e -\u003e let (e',  a) = g e\n                                   (e'', f) = sf e' in (e'', f a)\n\ninstance Monad (State ε) where\n  ma \u003e\u003e= f = join (pure f \u003c*\u003e ma)\n    where join (S sf) = S $ \\e -\u003e let (e', S f) = sf e in f e'\n#+end_src\n\nA simple language with storage; a program's value is the value of its final store.\n#+begin_src haskell :tangle terms_with_storage.hs\ndata Expr = Let String Expr Expr | Var String | Int Int | Div Expr Expr\n           deriving Show\n\neval₄ :: Expr -\u003e State GlobalVars Int\neval₄ (Var x) = S $ \\e -\u003e let r = x `valuefrom` e in ((x,r):e, r)\neval₄ (Int x) = pure x\neval₄ (Let x t body) = do n \u003c- eval₄ t\n                          push [(x, n)] -- Applicative is NOT enough here!\n                          eval₄ body\neval₄ (n `Div` d) = do t \u003c- eval₄ n; b \u003c- eval₄ d; pure (t `div` b)\n\nthirteen = Let \"x\" (Int 1729)\n             $ Let \"y\" (Int 133 `Div` Int 1)\n                $ Var \"x\" `Div` Var \"y\"\n\n-- run (eval₄ thirteen) []\n#+end_src\n\nExercise: Add to the oringal =Term= type a constructor =Rndm [Term]=, where =Rndm\n[t₁, …, tₙ]= denotes non-deterministicly choosing one of the terms ~tᵢ~. Then write\nan evaluator that considers all possible branches of a computation:\n~eval₅ : Term → [Int]~.\n\nIf we want to mixin any of the features for our evaluators, we need to use ‘monad\ntransformers’ since monads do not compose in general.\n\n#+latex: \\columnbreak\n* Reads\n\n- /Introduction to Functional Programming/ by Richard Bird\n  - Assuming no programming, this book end by showing how to write a theorem\n    prover powerful enough to prove many of laws scattered throughout the book.\n\n- [[http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf][Monads for functional programming]] by Philip Wadler\n  - This covers the ~evalᵢ~ and more ^_^\n\n- [[https://docs.racket-lang.org/heresy/monad-do.html][Comprehending Monads]] by Philip Wadler\n\n- [[http://dev.stephendiehl.com/hask/][What I Wish I Knew When Learning Haskell]]\n\n- [[https://wiki.haskell.org/Typeclassopedia][Typeclassopedia]] ---/The essentials of each type class are introduced, with\n  examples, commentary, and extensive references for further reading./\n\n- [[http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html][You Could Have Invented Monads! (And Maybe You Already Have.)]]\n\n- [[http://learnyouahaskell.com/chapters][Learn You a Haskell for Great Good]] ---An accessible read with many examples, and drawings\n\n- [[https://en.wikibooks.org/wiki/Haskell][The Haskell WikiBook]] ---Has four beginner's tracks and four advanced tracks\n\n- [[https://alhassy.github.io/CatsCheatSheet/CheatSheet.pdf][Category Theory Cheat Sheet]] ---The “theory of typed composition”:\n  Products, Sums, Functors, Natural Transformations ^_^\n\n- [[https://alhassy.github.io/AgdaCheatSheet/CheatSheet.pdf][Agda Cheat Sheet]] ---Agda is Haskell on steroids in that it you can invoke\n  Haskell code and write proofs for it.\n\n- LINQ for [[http://tomasp.net/blog/idioms-in-linq.aspx/#csidiomsl][applicatives]] and [[https://livebook.manning.com/book/real-world-functional-programming/chapter-12/28][monads]].\n  - Monads ≈ SQL/Linq ≈ Comprehensions/Generators\n\n#+latex: \\ifnum\\cheatsheetcols=1 \\newpage \\else \\columnbreak \\fi\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falhassy%2FHaskellCheatSheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falhassy%2FHaskellCheatSheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falhassy%2FHaskellCheatSheet/lists"}