<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Iven Marquardt on Medium]]></title>
        <description><![CDATA[Stories by Iven Marquardt on Medium]]></description>
        <link>https://medium.com/@iquardt?source=rss-1b365454a190------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*giGTf6GI7L6U1anlX5-35g.jpeg</url>
            <title>Stories by Iven Marquardt on Medium</title>
            <link>https://medium.com/@iquardt?source=rss-1b365454a190------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:48:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iquardt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Little Recursion Refresher]]></title>
            <link>https://medium.com/@iquardt/a-little-recursion-refresher-188e1ecf8123?source=rss-1b365454a190------2</link>
            <guid isPermaLink="false">https://medium.com/p/188e1ecf8123</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Iven Marquardt]]></dc:creator>
            <pubDate>Thu, 07 May 2020 21:50:38 GMT</pubDate>
            <atom:updated>2020-05-07T21:50:38.270Z</atom:updated>
            <content:encoded><![CDATA[<p>Recursion is the bread and butter tool of every proper functional programmer. Here is a brief refresher about its major forms:</p><pre>// body recursion</pre><pre>const mapRec = f =&gt; ([x, …xs]) =&gt;<br> x === undefined<br> ? []<br> : [f(x), …mapRec(f) (xs)];</pre><pre>// tail recursion</pre><pre>const mapTRec = f =&gt; ([x, …xs], acc = []) =&gt;<br> x === undefined<br> ? acc<br> : mapTRec(f) (xs, acc.concat(f(x)));</pre><pre>// recursion in continuation passing style</pre><pre>const mapCPS = f =&gt; ([x, …xs]) =&gt; k =&gt;<br> x === undefined<br> ? k([])<br> : mapCPS(f) (xs) (ys =&gt; k([f(x), …ys]));</pre><pre>const sqr = x =&gt; x * x;<br>const id = x =&gt; x;</pre><pre>mapRec(sqr) ([1,2,3]); // [1,4,9]<br>mapTRec(sqr) ([1,2,3]); // [1,4,9]<br>mapCPS(sqr) ([1,2,3]) (id); // [1,4,9]</pre><p>Actually there is still tail recursion modulo cons, mutual recursion, monad recurison, corecursion etc.</p><p><a href="https://github.com/kongware/scriptum/blob/master/ch-9.md">Learn more about recursion and trampolining at my course</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188e1ecf8123" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorry, but Functors are not a means to map over an Array]]></title>
            <link>https://medium.com/@iquardt/sorry-but-functors-are-not-a-means-to-map-over-an-array-b21caae3098a?source=rss-1b365454a190------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21caae3098a</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Iven Marquardt]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 18:42:32 GMT</pubDate>
            <atom:updated>2020-04-26T18:42:32.184Z</atom:updated>
            <content:encoded><![CDATA[<p>…because they are much more general: Functors lift any ordinary function into numerous structures and effectful contexts.</p><p>See how we lift the pure function inc = x =&gt; x + 1 in a context that either produces an Array asynchronously or yields nothing at all. All it takes is the composition of these three functions:</p><pre>const tMap = f =&gt; tx =&gt;<br> Task((res, rej) =&gt; tx.task(x =&gt; res(f(x)), rej));</pre><pre>const optMap = f =&gt; tx =&gt;<br> match(tx, {<br> None: _ =&gt; None,<br> Some: ({some: x}) =&gt; Some(f(x))<br> });</pre><pre>const arrMap = f =&gt; xs =&gt;<br> xs.map((x, i) =&gt; f(x, i));</pre><p>Consider what it means in terms of code reuse in general if you can reuse all your simple functions in dozens of scenarios.</p><p><a href="https://github.com/kongware/scriptum/blob/master/ch-13.md">Read the full story aboutn functors</a> including the complete, runnable code of the given example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21caae3098a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[f is not the same as x => f(x)]]></title>
            <link>https://medium.com/@iquardt/f-is-not-the-same-as-x-f-x-19fe332706ca?source=rss-1b365454a190------2</link>
            <guid isPermaLink="false">https://medium.com/p/19fe332706ca</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Iven Marquardt]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 09:57:12 GMT</pubDate>
            <atom:updated>2020-04-23T10:00:59.397Z</atom:updated>
            <content:encoded><![CDATA[<p>f is not the same as x =&gt; f(x)when it comes to evaluation in a strictly evaluated language like Javascript. The latter renders a function slightly more lazy:</p><pre>const mapFold = f =&gt; acc =&gt; ix =&gt; {<br> for (let [i, x] of ix)<br> acc = f(acc) (x);</pre><pre>return acc;<br>};</pre><pre>const arrSnoc = xs =&gt; x =&gt;<br> (xs.push(x), xs);</pre><pre>const mapToArr =<br> mapFold(arrSnoc) ([]);</pre><pre>const mapToArr_ = ix =&gt;<br>//                ^^<br> mapFold(arrSnoc) ([]) (ix);<br>//                     ^^^^</pre><pre>const foo = new Map([[0, “foo”], [1, “bar”], [2, “baz”]]);</pre><pre>mapToArr(foo);<br>mapToArr_(foo);</pre><pre>mapToArr(foo); // [“foo”, “bar”, “baz”, “foo”, “bar”, “baz”]<br>mapToArr_(foo); // [“foo”, “bar”, “baz”]<br></pre><p>mapToArr gets a fesh array as accumulator each time it is called and hence keeps the side effect caused by arrSnoc local. Adding redundant lambda abstractions to a derived function is called eta abstraction and the opposite operation eta reduction.</p><p><a href="https://github.com/kongware/scriptum/blob/master/ch-5.md">Read more on lazy evaluation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19fe332706ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Row Polymorphic Records for More Type Safety]]></title>
            <link>https://medium.com/@iquardt/row-polymorphic-records-for-more-type-safety-aa9830d59b9b?source=rss-1b365454a190------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9830d59b9b</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Iven Marquardt]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 15:55:58 GMT</pubDate>
            <atom:updated>2020-04-20T16:09:55.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Row Polymorphic Records for More Type Safety in Typescript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1/0*0HSLXRZ-x44gZbL2.png" /></figure><p>Typescript’s type system uses structural subtyping and hence allows every data structure for a given type that contains at least the demanded properties.</p><p>However, we can easily restrict this less safe polymorphism to row polymorphism by utilizing generics:</p><pre>type foo = { first: string, last: string };<br> <br>const o = { first: “Foo”, last: “Oof”, age: 30 }; <br>const p = { first: “Bar”, last: “Rab”, age: 45 }; <br>const q = { first: “Baz”, last: “Zab”, gender: “m” };</pre><pre>const main = &lt;T extends foo&gt;(o: T) =&gt; (p: T) =&gt; o.first + o.last<br> <br>main(o) (p); // type checks <br>main(o) (q); // type error</pre><p><a href="https://www.typescriptlang.org/play/?ssl=1&amp;ssc=1&amp;pln=10&amp;pc=25#code/C4TwDgpgBAZg9nKBeKBvWBLATgZ2ALijywwDsBzAGigBsBDPQ4s8qAXwG4BYAKF4GM4pPFEQp0MbIygAiAGIIZ1etJkB5ODCVQ65CIQDMABnbceg4cChhkaTLgKyAQnSzaVjmQCU6AI226+lAALACspgJCIgCOthJSni4AXu4MngBaftp6pAAmEFiEMgC2MhF85lFWxXRktgA8ACpQEAAewBB5OLAIAHwAFHCEjQCUyL1Q-WDDY0gTcAB0kg5QANSiCx68vDVkgyNTIxxQAPQnUKCQUPwAFhD8ANY4O7Wk+-3RR6fnpHAA7i0sFg4FggA">Playground</a></p><p>This isn’t as type safe as nominal typing but definitively an improvement. Read more in the 12th chapter <a href="https://github.com/kongware/scriptum/blob/master/ch-12.md">A Little Type Theory</a> of the functional programming in Javascript course.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9830d59b9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functors Dissected]]></title>
            <link>https://medium.com/@iquardt/functors-and-context-fc1ed137a8b6?source=rss-1b365454a190------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc1ed137a8b6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functor]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Iven Marquardt]]></dc:creator>
            <pubDate>Wed, 31 Jan 2018 18:48:52 GMT</pubDate>
            <atom:updated>2018-03-02T19:49:16.571Z</atom:updated>
            <content:encoded><![CDATA[<h4>Type-directed Functional Programming for Non-Mathematicians in Javascript</h4><h3>Preamble</h3><p>This is a <a href="https://medium.com/@iquardt/functional-programming-series-fc7247f8bc05">series</a> of loosely connected posts around type-directed functional programming in Javascript. You can use <a href="https://github.com/kongware/ftor"><strong>ftor</strong></a> - a pluggable runtime type checker - to reproduce the code given in this post in a virtually typed Javascript environment.</p><h3>Properties</h3><p>A type is a functor if it satisfies the following properties:</p><ul><li>it is parameterized over another type</li><li>it must be associated with an operation that lifts an ordinary pure function into a context and complies with the functor laws</li></ul><p>Apart from that the language must provide a mechanism to overload the name of the lift operator.</p><h3>Context</h3><p>Let’s clarify the somewhat vague terms <em>context</em> and <em>effect</em>. Each functor operates in a computational context. It is the raison d’ être of a functor so to speak. You can imagine it as something in which a pure computation shows a certain behavior, because it is exposed to an effect that occurs in the given context.</p><p>In the context of theList type, for example, a computation produces any number of results. In the context of the Reader type a computation can access an implicitly shared read-only-environment. In the context of the Option type a computation may fail and produce no result at all.</p><p>As you may have already noticed each context is associated with a type. Instead of providing special language constructs for them the functional paradigm treats effects like values, so that we can compose them and pass them around like first class citizens. Treating effects like values is in fact one of the core principles of functional programming.</p><p>It is worth mentioning that a type can represent several meaningful contexts and hence can be associated with several functors. The function type, for instance, comprises the read-only-environment context (Reader) and the rest-of-the-computation context (Cont).</p><h3>Type Level</h3><p>From a type level perspective a functor is a parameterized type or type constructor. But first things first.</p><h4>Ground Types</h4><p>String,Number and Boolean are native Javascript types. They are also called ground types, because they are inhabited, that means there are actually values of that type.</p><h4>Type Constructors</h4><p>Array and Map on the other hand are type constructors that need another or more types to become an inhabited ground type. Like a constructor on values expects values as arguments a type constructor expects types as arguments. It is parameterized over types.</p><pre>// polymorphic type constructors</pre><pre>[a] // Array type constructor<br>Map k v // Map type constructor</pre><pre>// monomorphic ground types</pre><pre>Array(2); // [Number]<br>new Map([[&quot;foo&quot;, true]]); // Map String Boolean</pre><p>a,k and v are type variables that are simple placeholders for the missing types. Javascript’s rudimentary runtime type system doesn’t distinguish type and value constructors - don’t let that confuse you.</p><h4>Polymorphic in the Type Constructor</h4><p>Now we want to express a type that is able to represent all possible functors, not just List or Map. To do so we simply substitute the type constructor portion of the type signature with another type variable, as we did with the type parameters:</p><pre>f a</pre><p>There we are. f is the parameterized type we’ve been looking for. This is all we need at the type level to represent a functor. It is essential that f is only parameterized with a single type parameter. f a b doesn’t meet this requirement and hence could never construct a functor type.</p><h3>Term Level</h3><p>In order to fully understand functors you need to understand both the type and the term level. A proper functor type must provide a lift operation called map that takes an ordinary pure function on values and returns a function on values in a context. In other words, the pure function is lifted in a context. Now you can reuse all your pure functions in different contexts and keep your code DRY.</p><p>Since there are lots of different functors and we desire a uniform interface we need a mechanism to overload the map function. Some purely functional languages use type classes to allow overloading in a restricted and type-safe manner. In Javascript we either use the prototype system or even fall back to simple namespaces and explicit type dictionary passing.</p><p>We have to take a closer look at map‘s general type signature to reveal another crucial property:</p><pre>map :: (a -&gt; b) -&gt; f a -&gt; f b</pre><p>The type tells us that map must preserve the functor f and thus the context, that is to say map over a List must produce a new List. <strong>Functors are context preserving.</strong></p><p>Mathematically speaking, a functor is a mapping of types (a/b to f) and a mapping of functions (a -&gt; b to f a -&gt; f b). Hence the operation’s name.</p><h3>Laws</h3><p>The functor laws enforce the context preserving behavior and guarantee that all funtors can be composed in a uniform way:</p><ul><li>identity: map(id) === id</li><li>composition: comp(f) (g) === comp(map(f)) (map(g))</li></ul><pre>const id = x =&gt; x;<br>const comp = f =&gt; g =&gt; x =&gt; f(g(x));</pre><h3>A Mind-Blowing Functor</h3><p>I could have made it easy for myself and just pick the List functor as an example and you’d think: It’s just a fancy container after all. But I take the hard way and try to eliminate this analogy from your head. The functor instance of the function type:</p><pre>// (b -&gt; c) -&gt; (a -&gt; b) -&gt; a -&gt; c<br>const map = f =&gt; tf =&gt; x =&gt; f(tf(x));</pre><pre>const sqr = n =&gt; n * n,<br>  inc = n =&gt; n + 1;</pre><pre>const functorialComp = map(inc) (sqr);</pre><pre>functorialComp(2); // 5</pre><p>Yes, this is just function composition and for the functor instance of the function type map happens to be composition. But how can we specialize the general functor type (a -&gt; b) -&gt; f a -&gt; f b to match (b -&gt; c) -&gt; (a -&gt; b) -&gt; a -&gt; c? In order to do this we need to understand what f exactly stands for.</p><p>I mentioned earlier that functors are parameterized over a single type. The function type constructor, however, requires two types - one for the argument and another for the result value: a -&gt; b. For functions to be an instance of functors, we must therefore ignore the type of the return value. Consequently, f represents the argument a and the function type itself -&gt;, both put together: a -&gt;. This is invalid syntax in Haskell, hence we must fall back to the commonly used prefix notation (-&gt;) a:</p><pre>f    a<br>(-&gt;) a</pre><p>Next, I substitute f of the general functor type with (-&gt;) r. I use another letter to distinguish the functor type parameter from other type variables:</p><pre>(a -&gt; b) -&gt; f a -&gt; f b</pre><pre>// substitution<br>(a -&gt; b) -&gt; (-&gt;) r a -&gt; (-&gt;) r b // prefix notation</pre><pre>// rewrite in infix notation<br>(a -&gt; b) -&gt; (r -&gt; a) -&gt; (r -&gt; b)</pre><p>This is almost the desired function composition type, except for the parenthesis at the end. These parenthesis are unnecessary but make it clear that composition is in fact equivalent to the functor operation: It takes a pure function (a -&gt; b) and a functor (another pure function in this case)(r -&gt; a) and returns yet another pure function (r -&gt; b). This is equivalent to f a and f b, that means the context is preserved. The function type together with function compostion can form a functor.</p><h3>Composition</h3><p>The composition of two functors is always a functor itself:</p><pre>// auxiliary function</pre><pre>const Adt = tCons =&gt; vCons =&gt; {<br>  const t = new tCons();<br>  t.run = k =&gt; vCons(k);<br>  return t;<br>};</pre><pre>const map = f =&gt; xs =&gt; xs.map(x =&gt; f(x));<br>const sqr = n =&gt; n * n;</pre><pre>// Option type</pre><pre>const Option = Adt(function Option() {});<br>const Some = x =&gt; Option(cases =&gt; cases.Some(x));<br>const None = Option(cases =&gt; cases.None);</pre><pre>const runOption = cases =&gt; tx =&gt; tx.run(cases);</pre><pre>Option.map = f =&gt; tx =&gt;<br>  runOption({Some: x =&gt; Some(f(x)), None: None}) (tx);</pre><pre>// mock data</pre><pre>const options = [Some(1), None, Some(3), Some(4)];</pre><pre>// map over the nested functor</pre><pre>map(Option.map(sqr)) (options);<br>// [Some(1), None, Some(9), Some(16)]</pre><p>To access the values inside a nested functor you have to nest the matching versions of map accordingly. Please note that I used a special encoding to allow tagged unions in Javascript. There will be a separate post around tagged unions and algebraic data types later in this series.</p><h3>Natural Transformation</h3><p>Natural transformations provide a way of transforming one functor into another, while respecting its internal structure:</p><pre>// Array to Option transformation</pre><pre>const safeHead = xs =&gt; xs.length === 0<br>  ? None<br>  : Some(xs[0]);</pre><pre>// mock data</pre><pre>const xs = [1, 2, 3],<br>  ys = [];</pre><pre>safeHead(xs); // Some(1)<br>safeHead(ys); // None</pre><p>safeHead works on the List functor itself, not on its values. In fact, the function must not modify the values but only the context, otherwise it isn’t a natural transformation. The following law must apply:</p><pre>comp(map(f) (natTrans) === comp(natTrans) (map(f))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc1ed137a8b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type-Safe Anonymous Recursion]]></title>
            <link>https://medium.com/@iquardt/anonymous-recursion-e145478fdef3?source=rss-1b365454a190------2</link>
            <guid isPermaLink="false">https://medium.com/p/e145478fdef3</guid>
            <category><![CDATA[combinator]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Iven Marquardt]]></dc:creator>
            <pubDate>Thu, 25 Jan 2018 21:56:13 GMT</pubDate>
            <atom:updated>2018-02-12T08:23:34.538Z</atom:updated>
            <content:encoded><![CDATA[<h4>Type-directed Functional Programming for Non-Mathematicians in Javascript</h4><h3>Preamble</h3><p>This is a <a href="https://medium.com/@iquardt/functional-programming-series-fc7247f8bc05">series</a> of loosely connected posts around type-directed functional programming in Javascript. You can use <a href="https://github.com/kongware/ftor"><strong>ftor</strong></a> - a pluggable runtime type checker - to reproduce the code given in this post in a virtually typed Javascript environment.</p><h3>The U Combinator</h3><p>We can easily write a recursive anonymous function in untyped Javascript:</p><pre>const U = f =&gt; f(f);</pre><pre>const factU = rec =&gt; acc =&gt; n =&gt; n === 0<br>  ? acc<br>  : rec(rec) (n * acc) (n - 1);</pre><pre>const fact = U(factU) (1); // 1 is the initial value for acc</pre><pre>fact(5); // 120</pre><p>factU is an anonymous recursive function, because its name doesn’t appear in its body. I merely assigned it to a variable to keep the example simple. However, this implementation contains two shortcomings:</p><ol><li>The passed function argument has to call itself before the recursion can take place: rec(rec) (n * acc) (n -1)</li><li>The U combinator cannot be typed, because it would create an infinite type: ((... -&gt; a) -&gt; a) -&gt; a</li></ol><h3>The Y Combinator</h3><p>Let’s utilize a simplified version of the Y combinator to circumvent these drawbacks. Here is a translation of Haskell’s fix function:</p><pre>// fix :: (a -&gt; a) -&gt; a<br>const fix = f =&gt; f(fix(f));</pre><pre>const factU = rec =&gt; acc =&gt; n =&gt; n === 0<br>  ? acc<br>  : rec(n * acc) (n - 1);</pre><pre>const fact = fix(factU) (1); // stack overflow</pre><p>This implementation blows the stack, because Javascript is a strictly evaluated language, butY in its original implementation requires lazy evaluation. We can always use eta-expansion in situations like this:</p><pre>// fix :: ((a -&gt; b) -&gt; a -&gt; b) -&gt; a -&gt; b<br>const fix = f =&gt; x =&gt; f(fix(f)) (x);</pre><pre>const factU = rec =&gt; acc =&gt; n =&gt; n === 0<br>  ? acc<br>  : rec(n * acc) (n - 1);</pre><pre>const fact = fix(factU) (1); // 1 is the initial value for acc</pre><pre>fact(5); // 120</pre><p>This works but the type signature looks wrong. We just added a second argument and get a bloated signature - that doesn’t seem right! We can verify it by deriving the type:</p><pre>(a -&gt; a) -&gt; a // rename type vars<br>(b -&gt; b) -&gt; b // add additional argument &quot;a&quot; to function argument<br>((a -&gt; b) -&gt; a -&gt; b) -&gt; b // and to the function itself<br>((a -&gt; b) -&gt; a -&gt; b) -&gt; a -&gt; b</pre><p>There we are.</p><p>As opposed to theU combinator fix is a type safe combinator that finds the <a href="https://en.wikibooks.org/wiki/Haskell/Fix_and_recursion">least-defined fixed point of a function</a>, if one exists.</p><p>Without fix we would have to define our recursive fact with an auxiliary function, unless we’re willing to leak private API, namely acc:</p><pre>const fact = n =&gt; {<br>  const aux = acc =&gt; n =&gt; n === 0<br>    ? acc<br>    : aux(n * acc) (n - 1);</pre><pre>  return aux(1) (n);<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e145478fdef3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Currying and Abstraction over Arity]]></title>
            <link>https://medium.com/@iquardt/currying-the-underestimated-concept-in-javascript-c95d9a823fc6?source=rss-1b365454a190------2</link>
            <guid isPermaLink="false">https://medium.com/p/c95d9a823fc6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[currying]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Iven Marquardt]]></dc:creator>
            <pubDate>Sat, 19 Nov 2016 10:22:11 GMT</pubDate>
            <atom:updated>2018-01-29T18:36:40.499Z</atom:updated>
            <content:encoded><![CDATA[<h4>Type-directed Functional Programming for Non-Mathematicians in Javascript</h4><h3>Preamble</h3><p>This is a <a href="https://medium.com/@iquardt/functional-programming-series-fc7247f8bc05">series</a> of loosely connected posts around type-directed functional programming in Javascript. You can use <a href="https://github.com/kongware/ftor"><strong>ftor</strong></a> - a pluggable runtime type checker - to reproduce the code given in this post in a virtually typed Javascript environment.</p><h3>Definition</h3><p>Currying is a technique that refers to function declarations. In its original mathematical sense it is the transformation of a function with n parameters into a sequence of n functions, which each return an unary, anonymous function. More precisely, the arity is transformed from n-ary to n * 1-ary. But why limit it to one argument? Because it allows us to simplify the functional interface considerably. And because this limitation entails very desirable properties, as we’ll hopefully see in the course of this post.</p><pre>const add = x =&gt; y =&gt; x + y; // curried function declaration<br><br>add(1) (2); // procedural application</pre><pre>const inc = add(1); // partial application</pre><p>Currying is right-associative, that is to sayadd = x =&gt; y =&gt; x + y is equivalent to add = x =&gt; (y =&gt; x + y). By partially applying curried functions, we can defer the execution of the actual computation over which they abstract. Moreover, the resulting intermediate anonymous functions (lambdas) are often very useful themselves.</p><h3>Delimitation to Partial Application</h3><p>Currying has its own notion of partial application, namely partially applying a function sequence. This notion is regularly confused with partial application of multi-argument functions:</p><pre>const partial = (f, ...xs) =&gt; (...ys) =&gt; f(...xs, ...ys);<br><br>const reduce = (f, acc, xs) =&gt; xs.reduce(f, acc);<br><br>const add = (x, y) =&gt; x + y;<br><br>const sum = partial(reduce, add, 0);<br><br>sum([1, 2, 3, 4]) // 10</pre><p>A partially applied multi-argument function has received some but not all of its required arguments and waits to receive the pending ones with the next invocation.</p><h3>Why Curry</h3><p>It’s difficult to illustrate the benefit of currying, because the concept acts <strong>systemic</strong>. Systemic means that a property needs to interact with other basic properties in order to fully develop its advantages. There is a mutual dependency between the properties involved.</p><p>One of these concepts currying is playing nicely with are higher order functions, which themselves derive from first class functions. Currying makes working with higher order functions much more effective, provided the passed in functions are in curried form themselves. Since higher order functions are such an important concept and ubiquitous in the functional paradigm, this interaction can be considered the killer application of currying.</p><p>The most significant advantage of currying along with higher order functions is <strong>abstraction over arity</strong>. Whenever a higher order function is polymorphic in its return value, the passed function argument can be of arbitrary arity. The following compostion operator, which composes two unary functions, illustrates the concept quite nicely:</p><pre>const comp = f =&gt; g =&gt; x =&gt; f(g(x));<br><br>const inc = x =&gt; x + 1; // unary function</pre><pre>const mul = y =&gt; x =&gt; x * y; // binary function</pre><pre>// normal composition of two unary functions<br>comp(inc) (inc) (2); // 4</pre><pre>// composition of a binary and an unary function<br>comp(mul) (inc) (2) (3); // 9</pre><pre>// invalid composition of an inner binary function<br>comp(inc) (mul) (2) (3); // type error</pre><p>As you can see from the type error, abstraction over arity doesn’t always work. The involved types must be compatible. The underlying mechanism becomes more obvious when we take a closer look at the type level:</p><pre>comp :: (b -&gt; c) -&gt; (a -&gt; b) -&gt;  a -&gt; c      <br>         f       =&gt;  g       =&gt; (x =&gt; f(g(x)))</pre><p>f‘s arity doesn’t matter, because comp is polymorphic in its return type c. If f is substituted withinc, comp‘s return type becomes x =&gt; f(g(x)). If f is substituted with mul, comp‘s return type becomes x =&gt; y =&gt; f(g(x)) (y), which is perfectly valid. However, this doesn’t apply to g, hence the type error above.</p><p>As already mentioned, another benefit of currying is that partially applied functions are often useful themselves, because they allow you to derive functionality without having to declare a separate function each time. This applies not only to simple cases such as deriving inc from a partial applied add, but also for far more complex examples.</p><h3>How to Curry</h3><h4>Functions in your own realm</h4><p>The concise arrow syntax that ships with EcmaScript 2015 makes it a piece of cake to declare manually curried functions with little syntactic overhead:</p><pre>const add = m =&gt; n =&gt; m + n;</pre><pre>// ES5...</pre><pre>function add(m) {<br>  return function(n) {<br>    return m + n;<br>  };<br>}</pre><h4>Third party functions</h4><p>Multi-argument functions beyond your control can be programmatically curried with a corresponding combinator:</p><pre>const add = (m, n) =&gt; m + n;</pre><pre>const curry = f =&gt; x =&gt; y =&gt; f(x, y);</pre><pre>const curry3 = f =&gt; x =&gt; y =&gt; z =&gt; f(x, y, z);</pre><pre>const curriedAdd = curry(add); // programmatic currying</pre><pre>curriedAdd(2) (3); // 5</pre><h4>Methods</h4><p>Instead of going through the trouble of programmatically currying methods just use simple wrappers:</p><pre>const reduce = f =&gt; acc =&gt; xs =&gt;<br>  xs.reduce((acc_, x) =&gt; f(acc_) (x), acc);</pre><h4>Uncurry</h4><p>Sometimes what you really want is to uncurry a function in order to gain compatibility to native ones:</p><pre>const uncurry = f =&gt; (x, y) =&gt; f(x) (y);</pre><pre>const uncurry3 = f =&gt; (x, y, z) =&gt; f(x) (y) (z);</pre><pre>const add = m =&gt; n =&gt; m + n;</pre><pre>const xs = [1, 2, 3, 4];</pre><pre>xs.reduce(uncurry(add), 0); // 10</pre><h3>Variadic functions</h3><p>Variadic functions except any number of arguments and are thus incompatible with currying. You can certainly define variadic functions in curried form by supplying an explicit length argument, but this is merely a nice hack, as both concepts contradict each other. My advice is to not waste your time on this.</p><h3>Optional Arguments</h3><p>While I must admit that variadic functions are sometime convenient, I really dislike functions containing optional arguments. Currying is a concept to avoid just that. If your curried functions really need optional arguments, rather use a configuration object.</p><p>Optional arguments obscure the mathematical origin of functions and complicate their interface, without giving you much.</p><h3>Why Argument Order Matters</h3><p>Abstractions are always a trade-off and so is currying. Since we supply only one argument per call, their order gains more importance:</p><pre>const sub = m =&gt; n =&gt; m - n;</pre><pre>const sub_ n =&gt; m =&gt; m - n;</pre><pre>const dec = sub(1);</pre><pre>const dec_ = sub_(1);</pre><pre>sub(10) (5); // 5 (A)</pre><pre>sub_(10) (5); // -5 (B)</pre><pre>dec(10); // -9 (C)</pre><pre>dec_(10); // 9 (D)</pre><p>We can probably agree on that the application in line C is certainly counterintuitive . But the other examples tempt to be interpreted differently. Some people will read line A<em> “subtract 10 from 5”</em>, others as <em>“subtract 5 from 10”</em>. The proper solution for this ambiguity would be to apply functions in infix position as we do with operators. This isn’t valid Javascript, though:</p><pre>(10) sub (5) // syntax error</pre><p>There is no simple solution to this issue in Javascript. You must decide for yourself which style to use and than stick to it. Here are some combinators to ease the pain:</p><pre>const $ = (x, f, y) =&gt; f(x) (y);</pre><pre>const _ = f =&gt; y =&gt; x =&gt; f(x) (y); // aka flip</pre><pre>const sub = m =&gt; n =&gt; m - n;</pre><pre>const dec = _(sub) (1);</pre><pre>dec(10); // 9</pre><pre>$(10, sub, 5); // 5</pre><p>I’ve used syntactic names rather than semantic ones in order to imply that this combinators are actually operators. The expression _(sub) (1) indicates visually that sub is applied to its second argument, whereas the first argument on the left side is pending.</p><p>Please note that the argument order only concerns non-commutative functions:</p><pre>add(2) (3) === add(3) (2); // commutative</pre><pre>sub(2) (3) !== sub(3) (2); // non-commutative</pre><p>When you compare the parameter order of curried with multi-argument functions at declaration time, two essential rules arise for curried functions:</p><ul><li>the primary parameter should be placed at the end to facilitate function composition</li><li>parameters that are least likely to change should be placed leftmost to facilitate partially applied functions</li></ul><h3>Don’t!</h3><p>You ought not</p><ul><li>relay on Function’s length property</li><li>use magic auto currying, that is functions as return values are curried automatically</li><li>use programmatic curry solutions that allow partial application in arbitrary positions of the argument list (e.g. reduce(f, __, xs))</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c95d9a823fc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>