{"path": "/posts/modeling-algorithms-with-types/", "title": "Modeling algorithms with types · Bruno Dias", "html": "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"description\" content=\"Modeling algorithms with types\">\n  <title>Modeling algorithms with types · Bruno Dias</title>\n  <link rel=\"canonical\" href=\"https://diasbruno.github.io/posts/modeling-algorithms-with-types/\" data-post-metadata>\n  <meta name=\"author\" content=\"Bruno Dias\" data-post-metadata>\n  <meta property=\"og:type\" content=\"article\" data-post-metadata>\n  <meta property=\"og:title\" content=\"Modeling algorithms with types\" data-post-metadata>\n  <meta property=\"og:url\" content=\"https://diasbruno.github.io/posts/modeling-algorithms-with-types/\" data-post-metadata>\n  <meta property=\"article:published_time\" content=\"2021-12-03T15:00:00Z\" data-post-metadata>\n  <link rel=\"icon\" href=\"/assets/site/signature.svg\" type=\"image/svg+xml\">\n  <link rel=\"alternate\" type=\"application/atom+xml\" title=\"diasbruno\" href=\"/atom.xml\">\n  <link rel=\"alternate\" type=\"application/json\" href=\"/posts/modeling-algorithms-with-types/content.json\">\n  <link rel=\"stylesheet\" href=\"/assets/site/tokens.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/site.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/footer.css\">\n\n</head>\n<body class=\"light\">\n<div id=\"site-page\">\n<a class=\"skip-link\" href=\"#content\">Skip to content</a>\n<header class=\"site-header\">\n  <a class=\"brand\" href=\"/\" data-site-navigation aria-label=\"Bruno Dias, home\">\n    <img src=\"/assets/site/signature.svg\" width=\"24\" height=\"34\" alt=\"\">\n  </a>\n  <nav aria-label=\"Main navigation\">\n    <ul>\n<li><a class=\"nav-vrn\" href=\"/vrn/\" data-site-navigation><span class=\"nav-label\">vrn</span> <span class=\"nav-badge\">research</span></a></li>\n<li><a class=\"nav-posts\" href=\"/posts/\" data-site-navigation aria-current=\"location\">Posts</a></li>\n<li><a class=\"nav-projects\" href=\"/projects/\" data-site-navigation>Projects</a></li>\n<li><a class=\"nav-about\" href=\"/about/\" data-site-navigation>About</a></li>\n</ul>\n  </nav>\n</header>\n\n<main class=\"section\" id=\"content\" tabindex=\"-1\">\n  <article class=\"post-detail\">\n    <header class=\"section-header\">\n      <p class=\"post-category\">Post</p>\n      <h1>Modeling algorithms with types</h1>\n\n      <p><time datetime=\"2021-12-03T15:00:00Z\">2021-12-03</time></p>\n    </header>\n    <div class=\"post-columns\">\n      <section class=\"post-body\" aria-label=\"Article\">\n\n<p>Things get so much easier when you try\nto understand how the types work together\nto accomplish some work.</p>\n<p>In this article, we are going to model\na system that apply discounts using many\nstrategies.</p>\n<p>I'm going to use Haskell and javascript.\nhaskell (or ocaml if you like) is great to visualize\nwhat's going on the type level...</p>\n<p>We can starting by trying to think\non the simplest way to accomplish the job.</p>\n<p>We can start by using a simple subtraction <code>(-)</code>.</p>\n<pre><code class=\"language-hs\">applyDiscount :: Float -&gt; Float -&gt; Float\napplyDiscount price discount = price - discount\n\nlet price = 10.0\n    discounts = [1.0, 4.0]\n    finalPrice = 5.0\nin foldl applyDiscount price discounts == finalPrice\n</code></pre>\n<pre><code class=\"language-js\">const applyDiscount = (price, discount) =&gt; price - discount;\n\nconst price = 10.0;\nconst discounts = [1.0, 4.0];\nconst finalPrice = 5.0;\n\ndiscounts.reduce(applyDiscount, price) == finalPrice;\n</code></pre>\n<p>Then we can clarify what which <code>Float</code> means\non the type specifiction...</p>\n<pre><code class=\"language-hs\">type Price = Float\ntype Discount = Float\n\napplyDiscount :: Price -&gt; Discount -&gt; Price\napplyDiscount price discount = price - discount\n</code></pre>\n<p>Now we have <code>Price -&gt; Discount -&gt; Price</code> which means\n&quot;given a Price and a Discount, it returns back the price\nafter the discount&quot;...and that means, in this case,\nthat the Price acts like an accumulator!</p>\n<p>With this information, we can now improve <code>applyDiscount</code>\nto be more generic.</p>\n<pre><code class=\"language-hs\">class ApplyDiscount a where\n  applyDiscount :: a -&gt; Discount -&gt; a\n\napplyDiscounts :: ApplyDiscount a =&gt; a -&gt; [Discount] -&gt; a\napplyDiscounts = foldl applyDiscount\n</code></pre>\n<p>In this case, in typescript, it should be the same as...</p>\n<pre><code class=\"language-ts\">interface ApplyDiscount {\n  applyDiscount(discount: Discount): ApplyDiscount;\n}\n</code></pre>\n<p>Now, we just need to create instances for each <code>a</code>!</p>\n<pre><code class=\"language-hs\">newtype ApplyAll = ApplyAll Price\n  deriving (Show, Eq)\n\ninstance ApplyDiscount a where\n  applyDiscount (ApplyAll p) d = ApplyAll (p - d)\n\nlet discounts = [1.0, 4.0]\n    strategy = ApplyAll 10.0\n    finalPrice = ApplyAll 5.0\nin foldl applyDiscount strategy discounts == finalPrice\n</code></pre>\n<pre><code class=\"language-js\">class ApplyAll {\n  constructor(x) { this.price = x; }\n  applyDiscount(d) { return new ApplyAll(this.price - d); }\n}\n\nconst discounts = [1.0, 4.0];\nconst strategy = new ApplyAll(10.0);\nconst finalPrice = 5.0;\n\nconst applyDiscount =\n  (strategy, discount) =&gt; strategy.applyDiscount(discount);\n\ndiscounts.reduce(applyDiscount, strategy).price == finalPrice;\n</code></pre>\n<p>Now we have our first strategy! <code>ApplyAll</code>\njust apply all discounts available,\nand this is a great first strategy.</p>\n<p>A new requirement has arived!</p>\n<p>Now, we have too apply all discounts,\nbut we are not going to let the final price\ngoes negative.</p>\n<pre><code class=\"language-hs\">newtype ApplyAllNoNegative = ApplyAllNoNegative Price\n  deriving (Show, Eq)\n\ninstance ApplyDiscount a where\n  applyDiscount (ApplyAllNoNegative p) d =\n    ApplyAllNoNegative (max 0 (p - d))\n\nlet discounts = [5.0, 5.0]\n    strategy = ApplyAllNoNegative 8.0\n    finalPrice = ApplyAllNoNegative 0.0\nin foldl applyDiscount strategy discounts == finalPrice\n</code></pre>\n<pre><code class=\"language-js\">class ApplyAllNoNegative {\n  constructor(x) { this.price = x; }\n  applyDiscount(d) {\n    const price = Math.max(0, this.price - d);\n    return new ApplyAllNoNegative(price);\n  }\n}\n\nconst discounts = [1.0, 4.0];\nconst strategy = new ApplyAllNoNegative(10.0);\nconst finalPrice = 5.0;\n\ndiscounts.reduce(applyDiscount, strategy).price == finalPrice;\n</code></pre>\n<p>Too easy!</p>\n<p>Our next task is to:</p>\n<p>&quot;If it goes negative, just collect\nall discounts that we couldn't apply,\notherwise return the final price.&quot;</p>\n<pre><code class=\"language-hs\">newtype CollectDiscountWhenGoesNegative =\n  Applying Price |\n  NotApplied [Discount]\n  deriving (Show, Eq)\n\ninstance ApplyDiscount a where\n  applyDiscount (Applying p) d =\n    let x = p - d\n    in if x &gt;= 0 then\n         Applying x\n       else\n         NotApplied [d]\n  applyDiscount (NotApplied ls) c =\n    NotApplied (c : ls)\n\nlet discounts = [5.0, 5.0]\n    strategy = Applying 10.0\n    finalPrice = Applying 0.0\nin foldl applyDiscount strategy discounts == finalPrice\n\nlet discounts = [5.0, 8.0]\n    strategy = Applying 10.0\n    finalPrice = NotApplied [8.0]\nin foldl applyDiscount strategy discounts == finalPrice\n</code></pre>\n<pre><code class=\"language-js\">// Don't do this! It's just to help visualize what's going on.\nclass CollectDiscountWhenGoesNegative {}\n\nclass NotApplied extends CollectDiscountWhenGoesNegative {\n  constructor(x) { this.list = x; }\n  applyDiscount(d) { retun new this(this.list.concat([d])); }\n}\n\nclass Applying extends CollectDiscountWhenGoesNegative {\n  constructor(x) { this.price = x; }\n  applyDiscount(d) {\n    const price = this.price - d;\n    if (price &gt;= 0) {\n      return new Applying(price);\n    } else {\n      return new NotApplied([d]);\n    }\n  }\n}\n\nconst discounts = [1.0, 4.0];\nconst strategy = new Applying(10.0);\nconst finalPrice = 5.0;\n\ndiscounts.reduce(applyDiscount, strategy).price == finalPrice;\n\nconst discounts = [1.0, 4.0];\nconst strategy = new Applying(1.0);\n\ndiscounts.reduce(applyDiscount, strategy).list == [4.0];\n</code></pre>\n<p>It's really easy to work with this. If\nthe discount goes negative, we know exactly\nwhich discounts were not applied to mark on\nthe frontend as feedback.</p>\n<p>Our final task is:</p>\n<p>&quot;It must not apply duplicate discounts,\nand it must keep the duplicated to send as feedback\nto the user. Also, it must use the previous strategies\nso we can allow it goes negative or not.&quot;</p>\n<pre><code class=\"language-hs\">\ntype AlreadyAppliedDiscounts = S.Set Discount\ntype DuplicatedDiscounts = [Discount]\n\ndata DontApplyDuplicate a =\n DontApplyDuplicate AlreadyAppliedDiscounts DuplicatedDiscounts a\n deriving (Show, Eq)\n\ndadup = DontApplyDuplicate\n\ninstance (ApplyDiscount a) =&gt; ApplyDiscount (DontApplyDuplicate a) where\n applyDiscount (DontApplyDuplicate ls xs s) d =\n   if S.member d ls then\n     dadup ls (d : xs) s\n   else\n     dadup (S.insert d ls) xs $ applyDiscount s d\n\n-- could be a `Default` instance\nnew = dadup S.empty []\n\nlet discounts = [5.0, 5.0]\n   strategy = new (Applying 10.0)\n   finalPrice = dadup (S.fromList [5.0]) [5.0] (Applying 5)\nin foldl applyDiscount strategy discounts == finalPrice\n\nlet discounts = [5.0, 8.0]\n   strategy = Applying 10.0\n   finalPrice = NotApplied [8.0]\nin foldl applyDiscount strategy discounts == finalPrice\n</code></pre>\n<pre><code class=\"language-js\">class DontApplyDuplicate {\n  constructor(strategy) {\n    this.usedDiscounts = new Set();\n    this.duplicated = [];\n    this.strategy = strategy;\n  }\n  applyDiscount(d) {\n    if (this.usedDiscount.has(d)) {\n     this.duplicated.push(d);\n     return this;\n    }\n    this.usedDiscount.add(d);\n    this.strategy = this.strategy.applyDiscount(d)\n    return this;\n  }\n}\n\nconst discounts = [1.0, 4.0];\nconst strategy = new DontApplyDuplicate(new Applying(10.0));\nconst finalPrice = 5.0;\n\ndiscounts.reduce(\n  (p, d) =&gt; p.applyDiscount(d),\n  strategy\n).price == finalPrice;\n\nconst discounts = [1.0, 1.0, 4.0, 6.0];\nconst strategy = new DontApplyDuplicate(new Applying(10.0));\n\nconst {\n  usedDiscounts,\n  duplicated,\n  strategy: { list },\n} = discounts.reduce(applyDiscount, strategy);\n\nusedDiscount = [1.0, 4.0];\nduplicated = [1.0];\nlist = [6.0];\n</code></pre>\n\n      </section>\n      <aside class=\"post-links\" aria-labelledby=\"post-links-heading\">\n        <h2 id=\"post-links-heading\">Links</h2>\n        <ul>\n<li><a href=\"/posts/\" data-site-navigation>All posts</a></li>\n        </ul>\n      </aside>\n    </div>\n  </article>\n</main>\n\n<footer class=\"site-footer\">\n  <div class=\"site-footer-inner\">\n    <a class=\"site-footer-home\" href=\"/\" data-site-navigation>Bruno Dias</a>\n    <ul aria-label=\"Footer links\">\n      <li><a href=\"https://github.com/diasbruno\">GitHub</a></li>\n      <li><a href=\"/atom.xml\">Atom feed</a></li>\n    </ul>\n  </div>\n</footer>\n\n</div>\n<script type=\"module\" src=\"/assets/site/navigation.js\"></script>\n</body>\n</html>\n"}
