<?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 Anler on Medium]]></title>
        <description><![CDATA[Stories by Anler on Medium]]></description>
        <link>https://medium.com/@anler?source=rss-4e8eff463540------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DWQoE4UBRrBxgnEFlIGXvA.jpeg</url>
            <title>Stories by Anler on Medium</title>
            <link>https://medium.com/@anler?source=rss-4e8eff463540------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:45:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anler/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[Closure under composition]]></title>
            <link>https://medium.com/@anler/closure-under-composition-a3e020865cea?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e020865cea</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Sat, 21 Oct 2017 18:18:19 GMT</pubDate>
            <atom:updated>2017-10-28T18:35:20.218Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>In the very beginning of my path to becoming a functional programmer I had to learn about <em>closures</em>… <strong>twice</strong>.</p><h4>Lexical closures</h4><p>The first time was when I learned about <em>lexical closures</em>, which are a way of attaching an environment to a given function capturing some or all of its free variables.</p><p>For example, the following function has a <em>free</em> variable y , that is, is not bound by any lexically-surrounding binding:</p><pre>(fn [x] (x y))</pre><p>And here we have the same function with y <em>captured</em> by the binding of the let:</p><pre>(let [y &quot;Hola!]<br>  (fn [x] (x y)))</pre><p>The aha moment comes when you realise that the runtime of your language keeps the environment with the captured variables around for as long as the function itself lives:</p><pre>(def call-with-hola! (let [y &quot;¡Hola!&quot;]<br>                       (fn [x] (x y))))<br>(call-with-hola! identity)<br>&quot;¡Hola!&quot;</pre><p>Another realisation we might have is that now we have the tools to create <em>objects</em>, understanding objects as a data structure that bundles together several procedures with some state:</p><pre>(defn new-rectangle [x y x&#39; y&#39;]<br>  (let [∆X (- x&#39; x)<br>        ∆Y (- y&#39; y)]<br>    {:area (fn [] (* ∆X ∆Y))<br>     :perimeter (fn [] (+ ∆X ∆Y))}))</pre><pre>(def r (new-rectangle 0 0 5 10))</pre><pre>((:area r))<br>50</pre><pre>((:perimeter r))<br>15</pre><h4>Set theory closures</h4><p>The second time was when I learned about the meaning of <em>closure</em> in mathematics:</p><blockquote>A <a href="https://en.wikipedia.org/wiki/Set_(mathematics)">set</a> has <strong>closure</strong> under an <a href="https://en.wikipedia.org/wiki/Operation_(mathematics)">operation</a> if performance of that operation on members of the set always produces a member of the same set; in this case we also say that the set is <strong>closed</strong> under the operation.</blockquote><p>For example, the natural numbers ℕ are closed under addition, because the result of adding two natural numbers will always be a natural number. The same cannot be said of subtraction, because the result of subtracting two natural numbers might be a natural number, zero, or a negative number.</p><p>Another example more close to programming is when working with functions and function composition, composing two functions will always result in another function:</p><pre>addClosingExclamation = (++ &quot;!&quot;)</pre><pre>addOpeningExclamation = (&quot;¡&quot; ++)</pre><pre>addExclamation = addOpeningExclamation . addClosingExclamation</pre><pre>addExclamation &quot;Hola&quot;<br>&quot;¡Hola!&quot;</pre><p>Yet another, more broad example in programming is when composing expressions, composing two expressions will always result in another expression, and this is why in functional programming everything is an expression, even statements:</p><pre>(let [x (let [y &quot;¡Hola!&quot;]<br>          y)]<br>  x)</pre><p>The aha moment of this type of closure comes when you realise that working in closure is like driving a highway with guardrails, you are safe, and you cannot make mistakes when combining the values with the operation they are closed under. Also, knowing about this gives you better judgment on wether things compose or not.</p><h4>Things that don’t compose</h4><p>There are <em>a lot</em> of these things depending on the context: <em>locks</em>, <em>monads</em>, <em>objects, exceptions, macros,…</em> In a lot of situations the meaning of <em>compose</em> is not that combining two things you get another thing, but that the effects of combining two things, gives you the expected composed effect.</p><p>For example, let’s see how exceptions and macros do not compose in the context of <em>everything’s an expression</em> so common in functional languages.</p><p>Exceptions do not compose because combining two expressions that may throw exceptions do not gives back an expression that may throw, or report, two exceptions:</p><pre>(defn pair-results [x y]<br>  [(x) (y)])</pre><pre>(pair-results (fn [] (assert false &quot;ka&quot;))<br>              (fn [] (assert false &quot;boom!&quot;)))<br>AssertionError Assert failed: ka</pre><p>Macros do not compose because depending on the order of evaluation of two different macros, a value or an error might happen:</p><pre>(defmacro sleep-units% [value unit]<br>  `(* ~value<br>        ~(case unit<br>           seconds 1<br>           minutes 60<br>           hours 3600)))</pre><pre>(sleep-units% 5 seconds)<br>5</pre><pre>(sleep-units% 5 (rand-nth [&#39;seconds &#39;minutes]))<br>IllegalArgumentException No matching clause</pre><p>It seems like when you need to use macros, you move into a limbo were you are not exactly sure if you are allowed to use the full power of the language.</p><p>The above examples are just to proof that those things, in the context of functional languages of <em>everything’s an expression, </em>do not <em>automatically </em>compose and that you have to put some effort in designing them to do so.</p><h4>Conclusion</h4><p>One of the ultimate goals of functional programming is to turn into <em>composable</em> as many imperative programming constructions as possible, even then, things still may be <em>composable</em> in one context but not in another. Whether this is something software engineers should always strive for is open to discussion, but I think that keeping it present when designing software will do more good than harm. After all, the core of functional programming is composition and for functional programmers c<em>omposition is the way of handling complexity.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e020865cea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type safe Scala — Tagged types]]></title>
            <link>https://medium.com/@anler/type-safe-scala-tagged-types-e009cb7a4068?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/e009cb7a4068</guid>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Mon, 19 Jun 2017 06:16:28 GMT</pubDate>
            <atom:updated>2017-06-19T06:18:42.079Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Today let’s talk about briefly about <em>tagged</em> <em>types</em>. A tagged type is useful when the type you’re working with is completely valid for your domain of application but still you want to add extra information to the type just as we did with <a href="https://medium.com/@anler/type-safe-scala-phantom-type-parameters-a638f07164e6">phantom type parameters</a>.</p><p>For example, let’s take the situation where we have to send information to some service, but the information needs to be protected with an ephemeral key. java.security.Key is perfectly valid, but we can use tagged types to encode the fact that the key is ephemeral, and use that information whenever we need to check we are indeed using an ephemeral key:</p><pre>import java.security.Key<br>import javax.crypto.KeyGenerator</pre><pre>import tag.Tagged</pre><pre>sealed trait Ephemeral  // phantom type used to tag</pre><pre>def generateKey: Tagged[Key, Ephemeral] = {<br>  val gen = KeyGenerator.getInstance(&quot;AES&quot;)<br>  gen.init(128) // Block size</pre><pre>  tag(gen.generateKey)<br>}</pre><p>The implementation for tagging types is really simple:</p><pre>object tag {</pre><pre>  sealed trait Tag[U]<br>  type Tagged[T, U] = T with Tag[U]</pre><pre>  def apply[T, U](value: T): Tagged[T, U] =<br>    value.asInstanceOf[Tagged[T, U]]</pre><pre>}</pre><p>And the magic resides in that Tagged[T, U] is a subtype of T : implicitly[Tagged[T, U] &lt;:&lt; T] will yield a value for any T and U. Whenever we need T, we can just use the tagged type variant, but if instead we need Tagged[T, U], we cannot pass T without the required tag.</p><p>Take a look at how <a href="https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/typeoperators.scala#L25">tagged types are implemented in shapeless</a>, there they use @@ instead of Tagged and a class Tagger to benefit from type inference when tagging: tag[Ephemeral](key) instead of tag[Key, Ephemeral](key) as it would be in our example if we couldn’t use the inference of the return type of our generateKey function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e009cb7a4068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type safe Scala — Phantom type parameters]]></title>
            <link>https://medium.com/@anler/type-safe-scala-phantom-type-parameters-a638f07164e6?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/a638f07164e6</guid>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Thu, 15 Jun 2017 23:34:57 GMT</pubDate>
            <atom:updated>2017-06-16T05:40:00.044Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Phantom types parameters is one of my favourite features in type systems with <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametric polymorphism</a>: Java, Kotlin, Scala, C#, F#, Haskell, OCaml, and many others.</p><p>What is a phantom type parameter? A phantom type parameter is a type parameter that is checked statically by the compiler but not used at runtime. Let’s see an example:</p><pre>final case class Key[KeyType](jkey: java.security.Key)</pre><p>KeyType is a type parameter that it looks like is useless because we don’t need an instance of it to create a value of type Key.</p><p>What are they good for? They let you <em>tag</em> or <em>mark</em> types with additional information, which ultimately let you define compiler-checked invariants on what order some operations should follow, how they compose, or how they propagate the additional information.</p><p>Here’s an example on how to use phantom type parameters to check statically that we use a private key when decrypting a piece of information encrypted with a public key:</p><pre>sealed trait PK  // public key type<br>sealed trait SK  // private key type</pre><pre>final case class Key   [KeyType](jkey: java.security.Key)<br>// carries key type info ^^^^^^</pre><pre>final case class Secret[KeyType](bytes: Array[Byte])<br>//                      ^^^^^^^<br>// carries key type used for encryption</pre><pre>def generateKeyPair: (Key[PK], Key[SK]) = {<br>  val gen = java.security.KeyPairGenerator.getInstance(&quot;RSA&quot;)<br>  val pair = gen.generateKeyPair</pre><pre>  (Key(pair.getPublic), Key(pair.getPrivate))  <br>}</pre><pre>def encrypt(key: Key[PK], data: Array[Byte]): Secret[PK] = {<br>  val cipher = javax.crypto.Cipher.getInstance(&quot;RSA&quot;)<br>  cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key.jkey)<br>  Secret(cipher.doFinal(data))<br>}</pre><pre>def decrypt(key: Key[SK], secret: Secret[PK]): Array[Byte] = {<br>  val cipher = javax.crypto.Cipher.getInstance(&quot;RSA&quot;)<br>  cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key.jkey)<br>  cipher.doFinal(secret.bytes)<br>}</pre><pre>val data     = &quot;phantom&quot;.getBytes<br>val (pk, sk) = generateKeyPair</pre><pre>val secret = encrypt(pk, data)</pre><pre>decrypt(sk, encrypt(pk, data)).toVector == data.toVector // true</pre><pre>// if we make a mistake and try to decrypt with the encryption key<br>// we&#39;ll get a compiler error<br>//         vv--^^^^^^^^^^^^^^<br>// decrypt(pk, encrypt(pk, data)).toVector == data.toVector</pre><p>We can further improve that example to contemplate the case where we encrypt with the private key and decrypt with the public key. I leave you the entire snippet of code as a gist because is a bit longer, notice however how an implicit parameter CanDecrypt is used to establish the encryption/decryption relation we need between the different keys.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d582854cb2e3eb13cecd0e2ce50d76e9/href">https://medium.com/media/d582854cb2e3eb13cecd0e2ce50d76e9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a638f07164e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type safe Scala — Use domain types]]></title>
            <link>https://medium.com/@anler/type-safe-scala-use-domain-types-9c7f663bb43c?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c7f663bb43c</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[type-safety]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Mon, 12 Jun 2017 18:43:30 GMT</pubDate>
            <atom:updated>2017-06-12T18:55:57.783Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>By domain types I mean to be able to give a more specific/well-defined semantics to an existing data type. Let’s say we have an api to work with banking account numbers, where an account number is a numeric string between nine and nineteen characters long:</p><pre>def getBalance (account: String): BigDecimal = ???</pre><pre>def deposit(account: String, amount: BigDecimal): Unit = ???</pre><pre>def withdraw(account: String, amount: BigDecimal): Unit = ???</pre><p>Looking at those method we can immediately spot the issue of using the primitive String data type for modelling the account number: how should we handle, in each method, the case where the account number is invalid? And the answer is… we do not!</p><p>Instead we design our API as follows:</p><pre>sealed abstract class AccountNumber(value: String)</pre><pre>object AccountNumber {<br>  val accountNumberRegex = “[0–9]{9,19}”<br>  val errorMsg = “Account number has to be a numeric string between 9 and 19 characters long.”</pre><pre>  def fromString(str: String): Either[String, AccountNumber] = <br>    if (str.matches(accountNumberRegex))<br>      Right(new AccountNumber(str) {})<br>    else<br>      Left(errorMsg)<br>}</pre><pre>// The rest of our API methods rely now on a valid AccountNumber<br>def getBalance(account: AccountNumber): BigDecimal = ???</pre><pre>def deposit(account: AccountNumber, amount: BigDecimal): Unit = ??? </pre><pre>def withdraw(account: AccountNumber, amount: BigDecimal): Unit = ???</pre><p>Notice how our previous methods now can take for granted that they are working with valid account numbers, because the only way of constructing AccountNumber instances is by going through the code guarded by a validation check, this means that whenever our code compiles we can be sure that it is as safe as strong our validation check is. The use of the Either type is precisely to force the users of the API to deal with (or deliberately ignore) the possibility of using an invalid account number.</p><h4>Improving runtime performance</h4><p>One of the downsides of the previous solution is that we are creating a wrapper type which is used only at compile time to enforce invariants, but that at runtime is completely useless. Scala provides something similar to Haskell’s newtype called <em>value classes</em>:</p><blockquote>Value classes are a new mechanism in Scala to avoid allocating runtime objects. This is accomplished through the definition of new AnyVal subclasses…It has a single, public val parameter that is the underlying runtime representation. The type at compile time is wrapped, but at runtime, the representation is the underlying type.</blockquote><p>This is great although in reality the evaporation of the wrapper type is not guaranteed to disappear and some people in the Scala community are looking for other ways to achieve it.</p><p>So, if instead of using an abstract class we could use a value class:</p><pre>package api</pre><pre>private[api] final case class AccountNumber(value: String) extends AnyVal </pre><pre>object AccountNumberBuilder {<br>  // ... same as above<br>}</pre><p><em>The </em><em>private[api] thingy is necessary to forbid direct access to the </em><em>apply method of the companion object that is automatically generated by Scala for case classes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c7f663bb43c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type safe Scala — Don’t use null]]></title>
            <link>https://medium.com/@anler/type-safe-scala-dont-use-null-3a1420b2a9d8?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a1420b2a9d8</guid>
            <category><![CDATA[null]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[type-safety]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Sat, 03 Jun 2017 21:06:48 GMT</pubDate>
            <atom:updated>2017-06-12T19:01:37.747Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Null is a special value that denotes a <em>reference that points to nowhere</em> hence inhabits all reference types in Scala and Java. It was first implemented by the great <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a>, in his own words <em>because it was too easy to implement</em> and since then has caused a lot of headaches to developers.</p><p>The very problem of null is not null itself but rather how traditional type systems make use of it. To understand why null exists let’s think of an array of string references, and that we want to remove one of the references (for example to avoid loitering) without performing the costly operation of resizing the array, what reference value should we use when replacing the original reference? In this case we need an special reference value that denotes the <em>zero reference</em>, that’s precisely null.</p><p>If null is necessary, why is it so dreaded then? Because traditional imperative type systems implicitly bypass the reference layer for the programmer (this is good for the learning curve but bad for avoiding bugs), causing all sort of trouble when the followed reference is null.</p><p>A solution would be if type systems made explicit the use of references, instead of letting us write:</p><pre>var name: String = &quot;Anler&quot;<br>name = null</pre><pre>println(&quot;Hello &quot; ++ name) // throws java.lang.NullPointerException</pre><p>They should force us to write:</p><pre>var name: Reference[String] = Reference(&quot;Anler&quot;)<br>name = null<br>// println(&quot;Hello &quot; ++ name) wouldn&#39;t compile because name is a <br>// Reference, not a String</pre><pre>println(&quot;Hello &quot; ++ name.getOrElse(&quot;no name&quot;)) // Hello no name</pre><p>Because of Scala’s compatibility with Java, we don’t get forced to use an explicit strong reference type, but we still can avoid the null disease by using the <em>Option pattern</em> cure, and the idea is very simple: if we want to express the <em>possibility of absence</em>, we can use something very similar to what we already use for expressing <em>indeterminacy</em>.</p><p>For expressing <em>indeterminacy</em> we use lists, defined as:</p><pre>sealed trait List[+A]<br>final case object Nil extends List[Nothing]<br>final case class Cons[A](h: A, t: List[A]) extends List[A]</pre><p>For expressing <em>possibility of absence</em> we could use also a list, but that’s too unnecessarily powerful (for more information on why that is bad check out <a href="https://www.youtube.com/watch?v=GqmsQeSzMdw">Constraints Liberate, Liberties Constrain</a> by Runar Bjarnason), so we better use a list that can only hold one element: Option.</p><pre>sealed trait Option[+A]<br>final case object None extends Option[Nothing]<br>final case class Some[A](a: A) extends Option[A]</pre><p>Once we got that, we can start using it in all places where we don’t have a value to return, for example:</p><p>When performing division, instead of returning an Int or fail with an exception when the divisor is zero, we return Option[Int]:</p><pre>def divide(a: Int, b: Int): Option[Int] =<br>  if (b == 0) None<br>  else        Some(a / b)</pre><p>When indexing a list, instead of returning a value A for that index or fail with an exception when that index doesn&#39;t exist, we return Option[A]:</p><pre>def index[A](xs: List[A], i: Int): Option[A] =<br>  try   { Some(xs(i))    }<br>  catch { case _ =&gt; None }</pre><p>Thanks to using Option we have transformed what in the beginning was a Partial function into a Total function. See <a href="https://en.wikipedia.org/wiki/Partial_function">Partial functions</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a1420b2a9d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Functional Programming?]]></title>
            <link>https://medium.com/front-end-weekly/what-is-functional-programming-b786c01a3a23?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/b786c01a3a23</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Sun, 19 Jun 2016 23:31:11 GMT</pubDate>
            <atom:updated>2016-06-21T14:17:46.573Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgKIkkhl7iYZw3gZ_EZyEA.jpeg" /></figure><p>Let’s keep it short shall we?</p><blockquote>Functional Programming is a program construction technique that forbids the use of assignment.</blockquote><p>And by assignment I mean any form of mutation.</p><p>I prefer to use this definition because is easy to remember, short and concise. If you try to program with that constrain and that constrain only, you will soon find that, as a consequence, all your functions are going to be pure because they cannot have state, they are also going to be referentially transparent because they are pure, and if you keep going you will find yourself reinventing the functional vocabulary: folds, maps, filters, functors, applicatives, monads and so on.</p><h4>What is state?</h4><p>When something has the ability to mutate, we say that the thing has an accumulated effect, or identity, or state. Things with state are intractable for the reason that we cannot easily establish equality between them. This problem rapidly acquires philosophical dimensions when those <em>things</em> are us: Am I the same I was yesterday? Nobody knows.</p><p>Also a common problem with state is we can no longer share things easily, because we don’t know who is going to change them.</p><p>State is also related with time, as soon as you introduce state in your design you are coupling that design’s time with the human time. This is bad because what could be described by some static truth (a velocity function for example) is now blurred by an apparent non determinism that mess up everything. Take for example our own existence, do we have free will or the universe has everything set up for us? These kind of questions will be easier to answer if we could freely move in time as we move in space.</p><h4>Why do we need state?</h4><p>The less crucial reason is that:</p><blockquote>State gives us the best modularity we can get.</blockquote><p>How’s that? Well think about it, you can easily isolate any complex system just by giving it state. Think of a random numbers generator, the client of that system only need to know that the it gives a random number whenever is used, none of the system internals leak outside of it.</p><p>Why is it the less crucial one? Because in some places you can mimic the same modularity without state. In programming languages, Haskell is a language that goes pretty far in pushing the state to the boundaries of your system. Let’s see the random numbers generator example in programming languages.</p><p>Example with state in JavaScript:</p><pre>function twoRands() {<br> var a = Math.random();<br> var b = Math.random();<br> return [a, b];<br>}</pre><p>there <em>Math.random</em> is a function with state.</p><p>Example without state in Haskell:</p><pre>twoRands :: Random a =&gt; Rand (a, a)<br>twoRands = do<br> a &lt;- rand<br> b &lt;- rand<br> return (a, b)</pre><p>there <em>rand</em> is a function without state, but its internals are hidden by <a href="https://gist.github.com/anler/4c9d6a99b2f05a5a5243cb433c8e0ee8">Rand</a> which is a monad I define as a wrapper of the State monad.</p><p>And the more crucial reason is:</p><blockquote>We are prisoners of time, and for some problems that concern us we cannot use static truths to solve them, because we can’t possibly know such truths.</blockquote><p>Think of concurrency: situations that are inherently non deterministic.</p><h4>Conclusion</h4><p>Functional programming is all about static truths such as in Math, is easier to reason about, is tractable, and in a lot of places solves our problems better than imperative solutions. But as in life everything’s not black and white, there are a lot of shades as there are problems that cannot be solved without state, so our goal is to find a balance. For me pure functional languages are the greatest examples of that balance.</p><h4>References</h4><ul><li><a href="https://mitpress.mit.edu/sicp/full-text/book/book.html">Structure and Interpretation of Computer Programs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b786c01a3a23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/what-is-functional-programming-b786c01a3a23">What is Functional Programming?</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion aerobics (the Y-combinator)]]></title>
            <link>https://medium.com/@anler/recursion-aerobics-the-y-combinator-19af79ab459e?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/19af79ab459e</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Thu, 17 Sep 2015 00:00:00 GMT</pubDate>
            <atom:updated>2016-06-21T13:54:19.479Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>This post is more an exercise for me than anything else (any of my posts are?), I want to be able to get to the Y-combinator from a named function. If you don’t know what it is just keep reading, but be advised, there are explanations done by smarter people that you should be aware of, <a href="https://www.youtube.com/watch?v%3DFITJMJjASUs">Y-Not talk by Jim Weirich</a> and <a href="https://mitpress.mit.edu/books/little-schemer">Daniel P. Friedman’s book The Little Schemer</a> comes to mind.</p><p>I first knew about the Y-combinator while reading Paul Graham’s paper <a href="http://languagelog.ldc.upenn.edu/myl/ldc/llog/jmc.pdf">The Roots of Lisp</a>, there he said that Lisp’s primitive labels wasn’t technically necessary since you can implement recursive functions by means of the Y-combinator, and that’s what I’m going to try to derive here, I’m going to make an anonymous function recursive.</p><p>Let’s take as an example the function factorial, which equation looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*1UqD1_rkTwQU3bRTX7fNeQ.png" /></figure><p>Here’s how I would write that function in JavaScript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a6595b345d9e80e3431b850c556362c/href">https://medium.com/media/6a6595b345d9e80e3431b850c556362c/href</a></iframe><p>Now let’s imagine we can’t name our functions and they all must be anonymous, our previous example will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e952be1b6c28faed3a3f0acb6350206f/href">https://medium.com/media/e952be1b6c28faed3a3f0acb6350206f/href</a></iframe><p>The only thing we can do with this function is calculate the factorial of <em>0</em>, for <em>n&gt;0</em> it will throw a <em>ReferenceError</em> because factorial is not defined, and this is where it becomes interesting. Can we call ourselves without a name? It turns out we can, let’s keep going.</p><p>Now we write a function that allow us to compute a bigger factorial, the factorial of <em>n</em> for <em>n ≤ 1</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7484414a52d326b39882fb2f2398e065/href">https://medium.com/media/7484414a52d326b39882fb2f2398e065/href</a></iframe><p>And a bigger one, the factorial of <em>n</em> for <em>n ≤ 2</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/304b4455547797d4208bfb547415e0aa/href">https://medium.com/media/304b4455547797d4208bfb547415e0aa/href</a></iframe><p>As we can see, in every step of supporting a bigger <em>n </em>we keep needing one factorial function inside our factorial function. This is because we aren’t allowed to <strong>name</strong> our functions, the only way we have to make a function available to another function is by supplying the first as an argument to the second:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cde9b2ca7b0ac0e0940d920b83ba832/href">https://medium.com/media/7cde9b2ca7b0ac0e0940d920b83ba832/href</a></iframe><p>Look at the function we just defined, if it had a name, it would be something like <em>makeFactorial</em> right? that is, a sort of <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory function</a> that returns a factorial function.</p><p>Before continuing let’s use one trick to ease our understanding of this recursion hell, let’s name our functions using <em>$</em> as a prefix, this is just to not get lost in the anonymous functions soup but remember we can’t call $-prefixed functions.</p><p>Updating our previous example we get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d53b8bbe2a77c584fb131815ed0b68a8/href">https://medium.com/media/d53b8bbe2a77c584fb131815ed0b68a8/href</a></iframe><p>A question arise: if our <em>$makeFactorial </em>returns <em>$factorial</em> but <strong>also receives</strong> <em>factorial</em>, why don’t we just return what we receive? Let’s try it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cfe7ab0537a9e33dc6b035163ecf260/href">https://medium.com/media/0cfe7ab0537a9e33dc6b035163ecf260/href</a></iframe><p>But we just lost again the reference to <em>factorial </em>inside our <em>$factorial.</em> This is confusing… Let’s wrap it again in our factory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a695166157cbe1c5a96dff43c9c911ec/href">https://medium.com/media/a695166157cbe1c5a96dff43c9c911ec/href</a></iframe><p>Better, but now <em>makeFactorial</em> <strong>receives</strong> <em>makeFactorial </em>as the argument, not <em>factorial.</em> Let’s change the parameter’s name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ed23634302422686b8c69e9afc158a0/href">https://medium.com/media/5ed23634302422686b8c69e9afc158a0/href</a></iframe><p>One more thing, remember that we were looking for a <em>makeFactorial</em> that returns a <em>factorial</em>, not a <em>makeFactorial</em>, the winner move here is to try the path of calling <em>makeFactorial </em>with itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1afe76a31d7d7b9dc1dc4d02f07a6ff/href">https://medium.com/media/f1afe76a31d7d7b9dc1dc4d02f07a6ff/href</a></iframe><p>We also have to change the name of the <em>factorial</em> parameter since it’s now <em>makeFactorial</em>, and here we can already begin to feel the anticipation of the solution because we can use <em>makeFactorial</em> to get our factorial and ultimately recur.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bb306a1a447382321b70509bd684902/href">https://medium.com/media/1bb306a1a447382321b70509bd684902/href</a></iframe><p>This one looks like a solution, for simplicity let’s bind the resulting function as factorial and try it with some input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80278faa94578a45d89924c000bbf8e2/href">https://medium.com/media/80278faa94578a45d89924c000bbf8e2/href</a></iframe><p>It seems we just made recursion out of thin air, isn’t it?</p><h4>The applicative Y-combinator</h4><p>What’s left is refination, we certainly achieved recursion with anonymous functions, but if we had to repeat the same for each recursive function we need to define it would be very annoying.</p><p>So, let’s go back to our ideal case which is being able to use the factorial function as the real factorial function, not with some non-sense stuck in its guts.</p><p>We want to use this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c2b2095d54e7ab166997d5b6c748c24/href">https://medium.com/media/5c2b2095d54e7ab166997d5b6c748c24/href</a></iframe><p>That is, we want to just use <em>factorial</em> inside our function, not <em>(makeFact(makeFact))(n)</em> so going back to our last working example, let’s rewrite it as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c099cfbdd445128f74f6e51221e69fdb/href">https://medium.com/media/c099cfbdd445128f74f6e51221e69fdb/href</a></iframe><p>If you try that you’ll be stuck in an infinite loop because in order to compute the result of <em>makeFactorial</em> you have to compute the result of <em>$makeFactorial</em>. We need to defer its evaluation somehow, the way we achieve this in strict languages is by wrapping our expression with a function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4112060da43783daed6c26eb169812fe/href">https://medium.com/media/4112060da43783daed6c26eb169812fe/href</a></iframe><p>We’ve reached our goal, our function is there completely <strong>self-contained, </strong>let’s move it out from there by making yet another function that receives our function as a parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f96ce3efb84574f023bf3b4431f1aded/href">https://medium.com/media/f96ce3efb84574f023bf3b4431f1aded/href</a></iframe><p>We’ve just reached to the Y-combinator, a function that can be used to do recursion with anonymous functions. This function has anything to do with calculating factorials anymore, so let’s clean it by removing the names.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb0961966fe56f5a6f95a8bed861f94/href">https://medium.com/media/3cb0961966fe56f5a6f95a8bed861f94/href</a></iframe><h4>Remarks</h4><p>There’s more to this than what is told, and more rigorous math below of it. If you want to know more I recommend you to read the Wikipedia entry on <a href="https://en.wikipedia.org/wiki/Fixed-point_combinator">Fixed-point combinators</a>. Also watch the talk I posted at the beginning, and buy or borrow a copy of The Little Schemer, it does a better job explaining it that’s for sure! apart from being a great book for doing recursion aerobics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19af79ab459e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Curry and Partial Application. Know the difference!]]></title>
            <link>https://medium.com/@anler/curry-and-partial-application-know-the-difference-7567b50f221b?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/7567b50f221b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[haskell]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Sun, 09 Aug 2015 00:00:00 GMT</pubDate>
            <atom:updated>2016-06-18T01:16:27.576Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>The problem</h3><p>I’ve seen people referring to partial application as <em>currying</em>, specially people in the Groovy community since in that language the function used for partial application is named <strong>curry</strong>.</p><p>Partial application in action using Groovy:</p><pre>def addition = {a, b -&gt; a + b} // function of two parameters<br>def addTwo = addition.curry(2) // fix first parameter to argument 2<br>println addTwo(3)              // call with the other argument 3<br>// results in 5</pre><p>The problem strikes at line: <em>addition.curry(2) </em>where it’s calling <strong>curry</strong> to the operation of <strong>partial application</strong>.</p><p>Let’s read the definitions of each of them.</p><h3>Partial application.</h3><blockquote><em>In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity.</em></blockquote><blockquote><em>Given a function:</em></blockquote><blockquote><em>f :(X ×Y ×Z) →N</em></blockquote><blockquote><em>we might fix (or ‘bind’) the first argument, producing a function of type:</em></blockquote><blockquote><em>partial(f) :(Y ×Z) →N</em></blockquote><blockquote><em>Evaluation of this function might be represented as f-partial(y, z) instead of the original function f(x, y, z).</em></blockquote><blockquote><em>– Wikipedia</em></blockquote><h3>Currying</h3><blockquote><em>Given a function f of type:</em></blockquote><blockquote><em>f :(X ×Y) →Z</em></blockquote><blockquote><em>currying it makes a function curry(f) of type:</em></blockquote><blockquote><em>curry(f) :X →(Y →Z)</em></blockquote><blockquote><em>That is, curry(f) takes an argument of type X and returns a function of type Y →Z.</em></blockquote><blockquote><em>– Wikipedia</em></blockquote><p>So, partial application can be seen as a higher-order function that receives a function and some arguments and returns a function with those arguments fixed, let’s pretend it’s type is something like:</p><pre>partial: NAryFunction → [Argument] → NAryFunction</pre><p>looking at it from the typed point of view we can state that partial application of an n-ary function is another n-ary function with <em>length [Argument] </em>arguments less.</p><p>On the other hand currying can be seen as a higher-order function that receives an n-ary function and returns an unary function, let’s pretend it’s type is something like:</p><pre>curry :: NAryFunction → UnaryFunction1 → ... → UnaryFunctionN</pre><p>So it transforms a multi-argument function in a set of nested functions of one argument each and that return the nested function until all the arguments are supplied. This is done because functions of one argument are <em>more tractable</em>.</p><p>So as you can see from their <strong>pretended</strong> type signatures, they are completely different!</p><p>Generally what we found in most languages is partial application and in the face of partial application currying is probably not needed because is awkward to use in most imperative languages (because of the repeated function-calling syntax), take for example this snippet of JavaScript:</p><pre>// <br>// curry and partial are fictional functions<br>// <br>let addition = (a, b) =&gt; a + b<br>let additionCurried = curry(addition) </pre><pre>// with partial application you can do more than one thing <br>// that is, you can fix how many arguments you need<br>let addTwo = partial(addition, 2)<br>let four = partial(addition, 2, 2)</pre><pre>// with currying on the other hand you have only one way <br>// which is give the function one argument at a time<br>let addTwo = additionCurried(2)<br>let four = additionCurried(2)(2)</pre><p>See it from this point of view, a function f can be partially applied using two techniques:</p><ol><li>Partially apply the function directly: partial(f, [args…])</li><li>Curry the function: curry(f) which obligates you to supply the rest of the arguments one-by-one</li></ol><p>In most languages the first option is preferred because syntactically looks better and lets you fix more than one argument at a time.</p><h3>The beauty of Haskell</h3><p>One of the things I like most from Haskell is its syntax, which is funny because I used to hate it and favor Lisp syntax (or lack of it :P). Haskell doesn’t have partial application, but curried functions, but thanks to Haskell syntax where function evaluation doesn’t need any special notation the use of curried functions looks just as partial application. Take for example the following:</p><pre>addition a b = a + b <br>addTwo = addition 2 <br>four = addition 2 2</pre><p>I want you to pay special attention to this line <em>four = addition 2 2</em>, here addition is a curried function that cannot receive more than one argument at a time, but with Haskell’s syntax that’s transparent, it looks just as partial application, what’s really happening though is that Haskell sees that expression as <em>(addition 2) 2</em>, in other words, it calls addition with the argument 2 and calls again its result <em>(addition 2) </em>with the argument 2. This is contrary to what we see in other languages where functions and values are clearly separated and there is special syntax for evaluating a function. Take for example the same snippet of code in JavaScript:</p><pre>let addition = curry((a, b) =&gt; a + b)<br>let addTwo = addition(2)<br>let four = addition(2)(2)</pre><p>Here you see that since four is curried we are obligated to give it all its arguments one-by-one and because of JavaScript’s syntax the process looks kind of ugly <em>addition(2)(2) </em>compared to partial application <em>partial(addition, 2, 2)</em>.</p><h3>Some drops of history</h3><p>The name <em>Currying</em> was given by <a href="https://en.wikipedia.org/wiki/Christopher_Strachey">Christopher Strachey</a> as a reference to <a href="https://en.wikipedia.org/wiki/Haskell_Curry">Haskell Brooks Curry</a> (the Haskell language is named after hime), an American logician known for his work in combinatory logic.</p><p>The <em>currying</em> technique was actually invented by <a href="https://en.wikipedia.org/wiki/Moses_Sch%25C3%25B6nfinkel">Moses Schönfinkel</a>, a Russian logician who was the <em>inventor</em> of combinatory logic, and it was a simplification to the work done in combinatory logic and lambda calculus that states that functions of two or more arguments can be replaced by functions taking just one argument.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7567b50f221b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fold you so]]></title>
            <link>https://medium.com/@anler/fold-you-so-a0596faf03d9?source=rss-4e8eff463540------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0596faf03d9</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anler]]></dc:creator>
            <pubDate>Fri, 10 Jul 2015 00:00:00 GMT</pubDate>
            <atom:updated>2016-06-18T01:02:29.118Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<blockquote><em>A </em><strong><em>higher-order</em></strong><em> function is a function that receives a function as a parameter and/or returns a function as its result.</em></blockquote><p>The <strong>fold</strong> family of functions apply an operator over a data structure in a single pass. They are present in many languages, sometimes with a different name of such as <strong>reduce</strong>.</p><p>Depending on how the operation is grouped when traversing the list there are two variants of a fold:</p><ol><li>fold-right (<em>foldr</em>) where the operation groups to the right.</li><li>fold-left (<em>foldl</em>) where the operation groups to the left.</li></ol><h3>Foldr</h3><p>Let’s start with the simplest one and take a look to the following functions:</p><pre>sum&#39; [] = 0<br>sum&#39; xs = head xs + sum&#39; (tail xs)</pre><pre>product&#39; [] = 1<br>product&#39; xs = head xs * product&#39; (tail xs)</pre><p>Can you spot a common pattern in those functions? Can you spot the differences with this:</p><pre>f [] = v<br>f xs = head xs ⊕ f (tail xs)</pre><p>Correct! there are no differences! So, wouldn’t be nice that we abstracted the previous functions pattern? Well, we can do that it, and we call the abstraction <strong><em>foldr</em></strong>:</p><p>Visually, applying <em>foldr</em> to a list looks like this:</p><pre>foldr ⊕ v [x1, x2, ..., xn] = x1 ⊕ (x2 ⊕ (...(xn ⊕ v)...))</pre><p>now you should have a clue on why it is called <em>foldr</em> because it groups the operations to the right. Using it, we can re-implement the above functions in this way:</p><pre>sum&#39; = foldr (+) 0 </pre><pre>product&#39; = foldr (*) 1</pre><p>Now, let’s see the implementation of <em>foldr</em> along with its type signature:</p><pre>foldr :: (a -&gt; b -&gt; b) -&gt; b -&gt; [a] -&gt; b<br>foldr ⊕ v [] = v<br>foldr ⊕ v xs = head xs ⊕ (foldr ⊕ v (tail xs))</pre><p>What conclusions do we can get from it? Let’s see:</p><ul><li><em>foldr</em> is a recursive function.</li><li><em>v</em> is used as the result when the list <strong>is empty</strong>.</li><li>⊕ has to be a binary function (an operator), that’s what <em>a -&gt; b -&gt; b</em> means.</li><li>⊕ first parameter is of type a so it has to be an element of the list because the list has type <em>[a]</em>.</li><li>⊕ second parameter is of type <em>b</em> so it has to be <em>v</em> because that’s the type of, well, <em>v</em>, moreover, its result is also of type <em>b</em> which is telling us that the result is used as a new <em>v</em>.</li></ul><p>Our examples have something else in common, let’s first see what’s the definition of a <strong>Monoid</strong>:</p><blockquote><em>In abstract algebra, a branch of mathematics, a Monoid is an algebraic structure with a single associative binary operation and an identity element. — Wikipedia</em></blockquote><p>In our examples <em>(+)</em> is an associative operation and zero it’s its identity element, so we say that natural numbers form a Monoid under addition. The same happens with <em>(*)</em> and one.</p><p>whenever ⊕ and <em>v</em> form a Monoid, we can state <em>foldr</em> will have the type:</p><pre>foldr :: (a -&gt; a -&gt; a) -&gt; a -&gt; [a] -&gt; a</pre><h3>Foldl</h3><p>We already know about <em>foldr</em> and we know it groups the operation to the right, so let’s define a foldl that instead groups the operation to the left:</p><pre>foldl ⊕ [] = v<br>foldl ⊕ [x1, x2, ..., xn] = ((...(v ⊕ xn)...⊕ x2) ⊕ x1)</pre><p>The recursive pattern abstracted by <em>foldl</em> looks like this:</p><pre>f v [] = v<br>f v xs = f (v ⊕ head xs) (tail xs)</pre><p>So its implementation along with its type signature must be:</p><pre>foldl :: (b -&gt; a -&gt; b) -&gt; b -&gt; [a] -&gt; b<br>foldl ⊕ v [] = v<br>foldl ⊕ v xs = foldl ⊕ (v ⊕ head xs) (tail xs)</pre><h3>Similarities between foldr and foldl</h3><p>As you have seen <em>foldr</em> and <em>foldl</em> functions are very similar, in fact, as with <em>foldr</em>, when ⊕ and <em>v</em> form a monoid we can state its type will be:</p><pre>foldl :: (a -&gt; a -&gt; a) -&gt; a -&gt; [a] -&gt; a</pre><p>so in the presence of a Monoid <em>foldr</em> and <em>foldl</em> have both the <strong>same</strong> type. This guides us to what is called the <strong>first duality theorem</strong>:</p><pre>foldl ⊕ v xs = foldr ⊕ v xs</pre><p>whenever ⊕ and <em>v</em> form a Monoid and <em>xs</em> is a finite list.</p><p>So our example functions, sum and product, can be implemented using any of the two because of the <strong>first duality theorem</strong>, and whenever this is the case, using <em>foldl</em> is going to result in a more efficient solution since its algorithm is <em>tail recursive</em>.</p><h3>Remarks</h3><ul><li>The <em>Fold you so</em> expression is taken from the amazing book <a href="http://learnyouahaskell.com/">Learn You a Haskell for Great Good</a></li><li>All the information came from <a href="http://wikipedia.org/">Wikipedia</a> and these books: <a href="http://www.amazon.com/Introduction-Functional-Programming-International-Computing/dp/0134841891?tag%3Dduckduckgo-d-20">Introduction to Functional Programming</a> and <a href="http://www.amazon.com/Programming-Haskell-Graham-Hutton/dp/0521692695?tag%3Dduckduckgo-d-20">Programming in Haskell</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0596faf03d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>