<?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 Eric Breyer on Medium]]></title>
        <description><![CDATA[Stories by Eric Breyer on Medium]]></description>
        <link>https://medium.com/@eric-breyer?source=rss-e55b34a5129a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KXTmAn7xuk1hAk1xw9rZDQ.png</url>
            <title>Stories by Eric Breyer on Medium</title>
            <link>https://medium.com/@eric-breyer?source=rss-e55b34a5129a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:07:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eric-breyer/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[The Hideous Beauty of Point-Free Programming]]></title>
            <link>https://blog.devgenius.io/the-hideous-beauty-of-point-free-programming-e8608e3df09d?source=rss-e55b34a5129a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8608e3df09d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Eric Breyer]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 05:50:40 GMT</pubDate>
            <atom:updated>2023-03-01T14:13:33.122Z</atom:updated>
            <content:encoded><![CDATA[<h4>An exercise in combinators using Haskell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*Kz9qGp8KJnd8vfkrI-K2uw.png" /></figure><p>In my quest to learn how to use Haskell, I have started tackling the <a href="https://projecteuler.net/">Project Euler</a> suite of problems. I also became enamored with the idea of point-free or tacit programming, a style in which function arguments are implicit, ie. the function argument has no “points” it references. (Note: This article assumes a basic understanding of Haskell syntax and basic functions, especially the application ($) and composition (.) operators)</p><h4>Point-Free</h4><p>Point-free is a term originating from outside of computer science but all it means is that the function has no explicit arguments. For example, addOne n = n + 1 is not point-free, but we can tweak the definition slightly to addOne = (+) 1 to make it point-free. A sequence of partial application and composition can make arguments implicit in the definition.</p><p>We can also call these functions and this style “tacit.” The English definition of tacit is “Not spoken” or “Implied by or inferred from actions or statements.” With point-free functions, the arguments are there but they are not spoken, they are implicit.</p><p>(A point does not refer to the composition operator ., in fact, point-free code tends to have a lot of .s)</p><h4>What’s the “Point”</h4><p>Tacit programming can get very convoluted very fast, but it can also be a cleaner way to express ideas. As with every programming (and engineering) design decision, there are trade-offs.</p><p>Going back to our simple addOne example, let&#39;s say instead of adding one to a number we wanted to increment each value in a list by one. A naive implementation could be addOneList list = map (\n -&gt; n + 1) list. This will certainly work, but we can immediately see the lambda adds unnecessary complexity. Let&#39;s try switching that out as in the add-one example addOneList list = map ((+) 1) list. Now the map reads a bit more declaratively as “add one to each list element”, but there is still one argument list in the function’s definition. Since list is the last argument and also the last thing in the function body, we can do a lambda calculus eta-abstraction (\x-&gt;Ax = A) to obtain addOneList = map ((+) 1). This code reads much more clear and more concise than what we started with and is a likely example of common use cases of the point-free style.</p><h4>Going Deeper</h4><p>In my silly quest to make everything I write in Haskell point-free, I have come up with some useful definitions and rules.</p><p><strong>Eta-Reduction:</strong> func x = &lt;stuff&gt; x =&gt; func = &lt;stuff&gt;</p><p><strong>Composition: </strong>func x = &lt;stuff&gt; $ &lt;stuff2&gt; x =&gt; func x = &lt;stuff&gt; . &lt;stuff2&gt;</p><p><strong>Flipping:</strong> With the definition of the c (cardinal) combinator <br>c f a b = f b a = flip, we can apply the composition and eta-reduction rules to greater effect, for example:</p><pre>--&lt;primes = ...&gt;--<br>getPrimes n = take n primes<br>getPrimes n = c take primes n --flip<br>getPrimes = c take primes --eta-reduce<br><br>getMorePrimes n = take (n * 2) primes<br>getMorePrimes n = c take primes (n * 2) --flip<br>getMorePrimes n = c take primes ((*) 2 n)<br>getMorePrimes n = c take primes $ (*) 2 n<br>getMorePrimes = c take primes . (*) 2 --compose</pre><p>This starts to get hard to read taken together, but if we work backward, these definitions are still fairly readable, and possibly even preferable (depending on your tolerance for combinators). The final definition of getMorePrimes can be read as: “multiply the yet-to-be-determined input by 2 and pass the result to the function that will take a yet-to-be-determined number of primes.” This is of course only one way of reasoning and is a little hand-wavy, but I find a backward-to-forwards way of reasoning about composition can be helpful.</p><p><strong>The Phoenix: </strong>With the definition of the p(phoenix) combinator <br>p a f g x = a (f x) (g x), we get a way to use two argument functions. p takes a binary function and two unary functions. It applies an argument to the two unary functions and then combines the results with the binary function. I like to think of it as a “split-combine” operation. Potential use case to filter multiples of 5 and 3 out of a list:</p><pre>f35 lat = filter (\x -&gt; (x `mod` 3 /= 0) &amp;&amp; (x `mod` 5 /= 0)) lat<br>= filter (\x -&gt; (x `mod` 3 /= 0) &amp;&amp; (x `mod` 5 /= 0)) -- eta<br>= filter (\x -&gt; (&amp;&amp;)(x `mod` 3 /= 0) (x `mod` 5 /= 0))<br>= filter (p (&amp;&amp;) (\x -&gt; x `mod` 3 /= 0) (\x -&gt; x `mod` 5 /= 0))<br>= filter (p (&amp;&amp;) (\x -&gt; ((/=) 0) $ x `mod` 3 ) (\x -&gt; x `mod` 5 /= 0))<br>= filter (p (&amp;&amp;) (\x -&gt; ((/=) 0) $ c mod 3 x) (\x -&gt; x `mod` 5 /= 0))<br>= filter (p (&amp;&amp;) (((/=) 0) . c mod 3) (\x -&gt; x `mod` 5 /= 0)) -- compose<br>f35 = filter (p (&amp;&amp;) (((/=) 0) . c mod 3) (((/=) 0) . c mod 5))</pre><p>This final definition is even harder to parse through. It is still possible but as we go further it is probably best to just start with a correct “point-full” function and trust the “tacitification” process.</p><h4>Point-Free Project Euler</h4><p>Problem 3 asks for the largest prime factor of the number 600851475143. My solution involves a function biggestDiv :: Integer -&gt; [Integer] -&gt; Integer that takes an Integer and a list of possible factors (primes in this case) and finds the first one. The idea is that you can pass the number and a list of primes into this function to find the largest prime factor of said number.</p><pre>biggestDiv n potentialDivisors = <br>  if (n == 1) <br>  then (head potentialDivisors) <br>  else<br>    if (mod n (head potentialDivisors) == 0) <br>    then (biggestDiv (n `div` (head potentialDivisors)) potentialDivisors) <br>    else (biggestDiv n (tail potentialDivisors))</pre><p>To make this tacit we need a new definition of if that is a function, not a keyword</p><pre>if&#39; :: Bool -&gt; a -&gt; a -&gt; a<br>if&#39; True  x _ = x<br>if&#39; False _ y = y</pre><p>From here we get</p><pre>biggestDiv n pd = <br>  if&#39; (n == 1) <br>  (head pd) <br>  (if&#39; (mod n (head pd) == 0) <br>    (biggestDiv (n `div` (head pd)) pd) <br>    (biggestDiv n (tail pd)))</pre><p>Let&#39;s try to eliminate the leftmost argument pd first. There are two branches of the if’ that use the argument pd that are “combined” back together with the (if’ (n == 1)), this looks like a good spot for p!</p><pre>biggestDiv n = <br>  p (if&#39; (n == 1))<br>  (\pd -&gt; (head pd))<br>  (\pd -&gt; if&#39; (mod n (head pd) == 0) <br>    (biggestDiv (n `div` (head pd)) pd) <br>    (biggestDiv n (tail pd)))</pre><p>Now we have two functions combined with an if, and each takes an implicit argument. Unfortunately, we have replaced one explicit point with two more, so let&#39;s try to make these lambdas tacit too.</p><pre>biggestDiv n = <br>  p (if&#39; (n == 1))<br>  head<br>  (\pd -&gt; if&#39; (mod n (head pd) == 0) <br>    (biggestDiv (n `div` (head pd)) pd) <br>    (biggestDiv n (tail pd)))</pre><p>The first one was easy! Now we are going to have to do the same p trick for this second if, but a bit differently, since the predicate also needs pd. Here we are going to have to use Haskell’s s combinator (&lt;*&gt;) a few times too. f &lt;*&gt; g = \x -&gt; fx(gx), kind of like p, but one arg is passed straight instead of through a function. You can also think of &lt;*&gt;as applying f to g after they have both taken the argument. We are starting to skip steps here, so try to keep up or just enjoy!</p><pre>biggestDiv n = <br>  p (if&#39; (n == 1))<br>  head<br>  (\pd -&gt; (p if&#39; <br>              (((==) 0) . mod n . head) <br>              ((c biggestDiv) &lt;*&gt; (div n . head)) pd)<br>    (biggestDiv n (tail pd)))<br><br>-- use an s to chain the first part of the if to the else clause<br><br>biggestDiv n = <br>  p (if&#39; (n == 1)) head<br>  ((&lt;*&gt;) ((p if&#39;) <br>              (((==) 0) . mod n . head) <br>              (c biggestDiv &lt;*&gt; (div n . head)))<br>    (biggestDiv n . tail))</pre><p>The pd is gone! Now to eliminate the n. This gets a lot harder since we have to start flipping arguments.</p><pre>biggestDiv = <br>  (\n -&gt; (c p) head (if&#39; $ (==) 1 n)) &lt;*&gt;<br>  (\n -&gt; (&lt;*&gt;) ((p if&#39;) <br>                (((==) 0) . mod n . head) <br>                (c biggestDiv &lt;*&gt; (div n . head)))<br>    (biggestDiv n . tail))<br><br>-- flip to eliminate first lambda<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (\n -&gt; (&lt;*&gt;) ((p if&#39;) <br>                (((==) 0) . mod n . head) <br>                (c biggestDiv &lt;*&gt; (div n . head)))<br>    (biggestDiv n . tail))<br><br>-- use a p to pass the n to the two functions applied to &lt;*&gt;<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (\n -&gt; (p if&#39;) <br>                (((==) 0) . mod n . head) <br>                (c biggestDiv &lt;*&gt; (div n . head)))<br>    (\n -&gt; biggestDiv n . tail))<br><br>-- eliminate the first lambda with a p<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    (\n -&gt; ((==) 0) . mod n . head) <br>                    (\n -&gt; c biggestDiv &lt;*&gt; (div n . head)))<br>    (\n -&gt; (.) (biggestDiv n) tail))<br><br>-- eliminate the second lambda with some flips<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    (\n -&gt; ((==) 0) . mod n . head) <br>                    (\n -&gt; c biggestDiv &lt;*&gt; (div n . head)))<br>    (\n -&gt; (c (.)) tail (biggestDiv n)))<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    (\n -&gt; ((==) 0) . mod n . head) <br>                    (\n -&gt; c biggestDiv &lt;*&gt; (div n . head)))<br>    ((c (.)) tail . biggestDiv))<br><br>-- we have created another 2 lambdas so its time for more elimination!<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    (\n -&gt; (c (.)) head (((==) 0) . mod n)) <br>                    (\n -&gt; c biggestDiv &lt;*&gt; (div n . head)))<br>    ((c (.)) tail . biggestDiv))<br><br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    ((c (.)) head . (((==) 0 .) . mod)) <br>                    (\n -&gt; c biggestDiv &lt;*&gt; (div n . head)))<br>    ((c (.)) tail . biggestDiv))<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    (((==) 0 .) . (c (.)) head . mod)<br>                    (\n -&gt; c biggestDiv &lt;*&gt; (div n . head)))<br>    ((c (.)) tail . biggestDiv))<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    (((==) 0 .) . (c (.)) head . mod)<br>                    (\n -&gt; c biggestDiv &lt;*&gt; ((c (.)) head (div n))))<br>    ((c (.)) tail . biggestDiv))<br><br>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                    (((==) 0 .) . (c (.)) head . mod)<br>                    ((c biggestDiv &lt;*&gt;) . ((c (.)) head . div )))<br>    ((c (.)) tail . biggestDiv))</pre><p>We are now completely point free! There are no named parameters anywhere! However, notice we have a lot of (c (.)) (reverse compositions) lying around. In an attempt to make this more “Haskelly”, I have defined a reverse composition infix operator.</p><pre>(^.) :: (a-&gt;b) -&gt; (b-&gt;c) -&gt; (a-&gt;c)<br>f ^. g = c (.) f g</pre><p>Using ^., we can reduce the definition even further to</p><pre>biggestDiv = <br>  ((c p) head . if&#39; . (==) 1) &lt;*&gt;<br>  (p (&lt;*&gt;) (p (p if&#39;) <br>                (((==) 0 .) . (head ^.) . mod)<br>                ((c biggestDiv &lt;*&gt;) . ((head ^.) . div )))<br>    ((tail ^.) . biggestDiv))</pre><p>Add a few finishing flourishes to eliminate some parens…</p><pre>biggestDiv = <br>  (&lt;*&gt;) ((c p) head . if&#39; . (==) 1) $<br>  p (&lt;*&gt;) (p (p if&#39;) <br>                (((==) 0 .) . (head ^.) . mod)<br>                ((c biggestDiv &lt;*&gt;) . ((head ^.) . div ))) $<br>    (tail ^.) . biggestDiv</pre><p>And now we can finally rest. Obviously, this definition is completely unwieldy and impossible to change and debug, but it offers a fun exercise and proof of concept. When you can manipulate the arguments to your functions with combinators, explicit arguments are merely syntax. I find the fact that any function can be made tacit in a (fairly) simple manner very beautiful, but it can produce some terrible-looking code. Hence my description of this form of biggestDiv as “hideously beautiful”.</p><p>Note: When actually solving the problem I came up with this form:</p><pre>biggestDiv = p (&lt;*&gt;) ((head ^.) . if&#39; . (==) 1) $<br>                 p (&lt;*&gt;) <br>                     (p (p if&#39;) <br>                         (((==) 0 .) . (head ^.) . mod) <br>                         ((c biggestDiv &lt;*&gt;) . (head ^.) . div )) $ <br>                     (tail ^.) . biggestDiv</pre><p>It is almost exactly the same as the one I came up with in this article (my second try) but the first line comes out a bit different. The definitions are equivalent, as in they give the same answers, but it could be a fun exercise to try to convert between the two forms to formally prove the equivalence. I have not done this yet so I will leave this as an exercise for the reader. I don’t remember how I got a different reduction the first time.</p><p>Unless you are working in a language like APL, full tacit programming is almost never the right call. However, a lot of times writing point-free, or even just eliminating a few points, can create cleaner and clearer code. I find tacit functions lend themselves especially well to being used as arguments for mapping and reduction functions.</p><h3>About the author</h3><p>Eric Breyer is a computer science undergrad at Rice University. You can find him at his <a href="http://www.ericbreyer.com/">website</a>, as well as on <a href="https://github.com/ericbreyer">GitHub</a> and <a href="https://www.linkedin.com/in/eric-breyer/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8608e3df09d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/the-hideous-beauty-of-point-free-programming-e8608e3df09d">The Hideous Beauty of Point-Free Programming</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overloading the Subscripting[] Operator in C++]]></title>
            <link>https://blog.devgenius.io/overloading-the-subscripting-operator-in-c-1745e8818e02?source=rss-e55b34a5129a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1745e8818e02</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[red-black-tree]]></category>
            <dc:creator><![CDATA[Eric Breyer]]></dc:creator>
            <pubDate>Tue, 01 Nov 2022 01:14:46 GMT</pubDate>
            <atom:updated>2022-11-01T14:07:04.156Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing Map Square Bracket Indexing for Get/Set in C++</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*R17CbBd2MPM7-HsuPP_51Q.png" /></figure><h4>Disclaimer</h4><p>I like to misuse the word “index” and use it as a verb to mean finding the value at an index in a data structure (often array or list). I further like to misuse this meaning by extending it to “indexing” a map, which is just getting the value stored at a key. Essentially “indexing” is using the square bracket operator on something (mymap[key]). I don&#39;t know why I say this or if it is a common thing, but from a quick google search, I suspect it’s not.</p><h4>Prologue</h4><p>Recently, I decided to implement a Red-Black Tree in C++ as a personal project. This already exists as std::map and std::set and is a pain to implement with segfaults happening on almost every line, but it was both a good exercise in red-black trees (which I am learning in school) and C++ (which is always good to improve at). I got my tree working with gets, sets, inserts, and remove, and all was well with the world. However, I was missing the easy syntax of C# and python where one can just index a map with map[key] = value instead of using clunky methods and dot syntax. In practice, we can write the dots and it’s not a big deal, but this was already an experiment so why not try to make usage that tiny bit easier (and cooler)?</p><h4>Operator Overloading</h4><p>C++ allows us to override almost every operator for custom types such as +, - , &gt; , = , and the subscription operator []. The normal behavior in C/C++ is to perform pointer arithmetic and dereferencing automatically as in pointer[5] = *(pointer+5), but semantically it has become more synonymous with indexing (or subscripting, hence the name) arrays, lists, and maps. The syntax to overload this operator for a type is to make a method with the signature &lt;returnType&gt; operator[](&lt;paramType&gt; &lt;param&gt;). The singular parameter corresponds to what goes inside the square brackets. This method could be invoked on a map mymap as<br>&lt;returnType&gt; v = mymap[&lt;param&gt;];</p><h4>Overloading [] on the Tree</h4><p>It is a bit tough to implement the subscription operator like we want, because it needs to serve two functions, getting and setting. We can’t reference the value field directly, because there are specific getters and setters for that, we don’t want it exposed. Thus we need to change behavior depending on <em>how </em>and<em> where </em>the operator is used. int val = mymap[key]; should call a getter method whereas mymap[key] = val; should call a setter/insertion. There really isn’t a way to make two overloads with different behavior (you can try it yourself to see why), so we have to come up with a trickier solution. We can have operator[] a return a “proxy” object, that overloads operators and calls the right methods depending on what is done to it.</p><pre>rbtree&lt;K, V&gt;::getSetProxy operator[](K key) {<br>    return getSetProxy(this, key);<br>}</pre><p>Now the call int val = mymap[key]; becomes int val = getSetProxy; and mymap[key] = val; becomes getSetProxy = val;</p><h4>getSetProxy</h4><p>This proxy object will handle getting and setting depending on what the user tries to do. Construction of the proxy takes in a reference to the tree, so that it can perform the operations, and the key, so that it knows where to get/set/insert.</p><p>The set case is fairly straightforward. We will set using the assignment = operator, so we can overload it to call the setter method instead.</p><pre>class getSetProxy {<br>    rbtree&lt;K, V&gt; *theTree;<br>    K key;<br>...<br>    void operator=(V value) {<br>        if (!theTree-&gt;setValue(key, value)) {<br>            theTree-&gt;insert(key, value);<br>        }<br>    }<br>...<br>}</pre><p>The value on the right side of the assignment gets set or inserted at the key in the tree.</p><p>Get is a bit trickier. There is an operator in C++ called the implicit cast operator, with signature operator T() const; where T is the type to cast to and const just means this function can’t modify the class. This function gets called any time C++ needs to cast to a different type.</p><pre>myclass myobj = myobj();<br>int myint = myobj;<br>//          ^^^^^<br>//          implicit cast int() is called</pre><p>So in T val = getSetProxy; , operator T() will be called. We can overload this to give us get functionality like so:</p><pre>class getSetProxy {<br>    rbtree&lt;K, V&gt; *theTree;<br>    K key;<br>...<br>    operator V() const {<br>        return theTree-&gt;getValue(key);<br>    }<br>...<br>}</pre><h4>Putting it All Together</h4><p>Please forgive me for the abuse of notation and equality and all of math that is about to occur.</p><p>V value = mymap[key];<br>→V value = getSetProxy{key = key};<br>→V value = getSetProxy.operatorV();<br>→V value = mymap.getValue(key);</p><p>mymap[key] = value; (assuming key is not in map for simplicities sake)<br>→getSetProxy{key = key} = value;<br>→getSetProxy{key = key}.operator=(value);<br>→mymap-&gt;setValue(key, value)</p><h4>Epilogue</h4><p>C++ is pretty fun in that you can really make the language your own. I was able to take clunky syntax and make it more familiar to me in a few (albeit a bit tricky) lines of code. The code for the entire project, including this subscripting part can be found <a href="https://github.com/ericbreyer/redBlackTreeInCpp">here</a> on my GitHub.</p><h3>About the author</h3><p>Eric Breyer is a computer science undergrad at Rice University. You can find him at his <a href="http://www.ericbreyer.com/">website</a>, as well as on <a href="https://github.com/ericbreyer">GitHub</a> and <a href="https://www.linkedin.com/in/eric-breyer/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1745e8818e02" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/overloading-the-subscripting-operator-in-c-1745e8818e02">Overloading the Subscripting[] Operator in C++</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making OOP out of Functions]]></title>
            <link>https://blog.devgenius.io/making-oop-out-of-functions-1f107295b320?source=rss-e55b34a5129a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f107295b320</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Eric Breyer]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 15:08:55 GMT</pubDate>
            <atom:updated>2022-07-14T16:39:47.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Objects with Functions</h3><p>Using closures to build objects using the functional programming paradigm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*Q_8Hu3QpiZ5Gdn-d" /></figure><h3>Closures</h3><p>A closure is a functional pattern which results from a different set of variable scoping rules. In C and many other languages, a variable is only valid in the block of code it is defined in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/625eeb7d56e54f880a7bec6154154968/href">https://medium.com/media/625eeb7d56e54f880a7bec6154154968/href</a></iframe><p>Because the variable is only valid within the bracket, its lifespan is dictated by the text on the screen, so we call this lexical scoping.</p><p>Another type of scoping — dynamic scoping — allows us to capture variables in the context of where a function is defined. The code’s access to local variables depends on the definition context, not the plain text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5966270cea5e60e95f7a0ba9bf58c286/href">https://medium.com/media/5966270cea5e60e95f7a0ba9bf58c286/href</a></iframe><p>again in scheme (racket)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d29e547366a00c9f1e6c63f5d59603f/href">https://medium.com/media/9d29e547366a00c9f1e6c63f5d59603f/href</a></iframe><p>A function which returns another function in this way is called a closure. It packages (closes around) the currently scoped local variables, and allows the returned function valid access to them even after the calling function has returned.</p><p>If we think the local variables as a property, and the returned function as a method, and the outer function as a constructor, these closures almost look like objects! We can actually get the same behavior of the count closure using objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25f93450a99abee48918358456fa8f6f/href">https://medium.com/media/25f93450a99abee48918358456fa8f6f/href</a></iframe><h3>Building a Functional Stack Class</h3><p>A stack is a data structure that can be easily represented with a class that has methods operating on a list. I will continue with c# as our object oriented language here. C# already has a stack in its collections library but we will roll our own here using an array list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1a0ca0a62c4ebc59bca1a52fd763bc3/href">https://medium.com/media/f1a0ca0a62c4ebc59bca1a52fd763bc3/href</a></iframe><p>This is a pretty simple class, and does not cover all error cases, but it will do as a proof of concept. Lets implement the same concepts functionally. First we’ll do scheme with a pure functional implementation and then javascript where we can use a few tricks to make it work exactly like a class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57ea5901aa95440614d0bbd698889a50/href">https://medium.com/media/57ea5901aa95440614d0bbd698889a50/href</a></iframe><p>First we create a list in the outer function, the inner function will keep a reference to this list as long as it needs. The inner function takes two arguments: an operation and an optional number. The operation tells the function which method to call, and if that method (push in this case) requires an argument you can give it one. This is very similar usage and the same functionality of our c# class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f88af81482d960307150fcb4664b1ff/href">https://medium.com/media/9f88af81482d960307150fcb4664b1ff/href</a></iframe><p>The javascript method is similar, except that we have access to javascript objects. These allow us to create sets of key/value pairs and use dot notation to access them. The notation to use the stack closure is exactly the same as how you would use a class, it is just functionally defined. Classes in javascript are actually just syntactic sugar for closures like this.</p><p>Using only functions and some differnet scoping rules, we are able to create classes and objects. I think a lot of the time we are taught about object oriented programing first and as the “best” style. However, it is often used as a crutch and sometimes functional or procedural aproches can be simpler and more powerful. It is just important to think about the problem before we blindly throw classes and endless layers of fancy abstration at the problem.</p><h3>About the author</h3><p>Eric Breyer is a computer science undergrad at Rice University. You can find him at his <a href="http://www.ericbreyer.com/">website</a>, as well as on <a href="https://github.com/ericbreyer">GitHub</a> and <a href="https://www.linkedin.com/in/eric-breyer/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f107295b320" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/making-oop-out-of-functions-1f107295b320">Making OOP out of Functions</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infinite Data Structures: Part 2]]></title>
            <link>https://blog.devgenius.io/infinite-data-structures-part-2-6662f143e3b9?source=rss-e55b34a5129a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6662f143e3b9</guid>
            <category><![CDATA[scheme]]></category>
            <category><![CDATA[infinity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Eric Breyer]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 03:37:34 GMT</pubDate>
            <atom:updated>2022-11-01T00:15:42.468Z</atom:updated>
            <content:encoded><![CDATA[<p>More infinite lists in scheme</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*V4AF5ojpXI6gmqkh.gif" /></figure><p>This is a continuation of my previous story that can be found <a href="https://eric-breyer.medium.com/infinite-data-structures-9c193789dae6">here</a>.</p><h3>Stream Combine</h3><p><a href="https://eric-breyer.medium.com/infinite-data-structures-9c193789dae6">Last time</a> we made a few interesting streams using stream-add. I want to now introduce a more versatile function that will let us create some more interesting streams.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaf0acaa52fa736cbd218549f4da7656/href">https://medium.com/media/eaf0acaa52fa736cbd218549f4da7656/href</a></iframe><p>This function is almost exactly the same as stream-add, except that we can pass any operation to it, not just +. stream-add and (stream-combine +) are equivalent.</p><h4>New Powers</h4><p>We can create some fun new streams with this new way of combining. We created the natural numbers by adding two streams together, so it follows that we could create the powers of two by multiplying two streams.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48f990199fddb48cbad3f058109cc645/href">https://medium.com/media/48f990199fddb48cbad3f058109cc645/href</a></iframe><p>Like with the natural numbers let&#39;s assume that the stream of powers of two, powsOf2 exists. This stream is &#39;(1 2 4 8 16 32 ...), when we stream combine multiply this with &#39;(2 2 2 2 2 2 ...) we get &#39;(2 4 6 8 16 32 64 ...). So like before, ((stream-combine *) twos powsOf2)) is the tail of our list and we just need to kick things off with a 1.</p><p>Another stream that is now trivial to construct is the sequence of squares.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5e8dcf685efc316819a6b308314db23/href">https://medium.com/media/f5e8dcf685efc316819a6b308314db23/href</a></iframe><p>And the factorials</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bc353958df1a1f623ea357495aa8384/href">https://medium.com/media/5bc353958df1a1f623ea357495aa8384/href</a></iframe><p>Again notice that the factorials: &#39;(1 2 6 24 120 720 …), times the naturals: &#39;(1 2 3 4 5 6), equals the cdr of the factorials: &#39;(2 6 24 120 720 5040 …). Since we already have the cdr of the factorials we just have to explicitly kick it off with the first one and combine the two.</p><p>If this is still a bit confusing, I highly encourage you to work through the underlying processes at work as I showed in the previous post.</p><h3>Towards Primes</h3><p>One of the most classical and elegant examples of infinite lists is constructing the list of primes. This is not obviously possible with our only tool being stream-combine, so let’s introduce one last function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b47fb5cc731d1808e548f13938be6a80/href">https://medium.com/media/b47fb5cc731d1808e548f13938be6a80/href</a></iframe><p>stream-filter takes a predicate and a stream. It then goes down the list and only keeps items that satisfy the predicate, if an item evaluates to false, it is skipped. Since this is all lazily evaluated, stream-filter works on-demand: only executing up to what is necessary for what we ask for.</p><h4>Simple uses</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5e4121d0a346533ec581d7012b22a30/href">https://medium.com/media/a5e4121d0a346533ec581d7012b22a30/href</a></iframe><p>One of the (many) ways to construct the odd numbers is to filter all the even numbers out of the natural numbers.</p><h4>The Sieve of Eratosthenes</h4><p>The Sieve of Eratosthenes is an ancient algorithm for finding prime numbers. Essentially, you take the list of natural numbers starting with 2 (the first prime). Any multiple of two is by definition not prime, so remove them from the list. Now move on to the next prime number and remove all of its multiples from the list and so on. This process will remove all numbers with factors other than one or itself. (<a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">further reading</a>)Normally this process needs an upper bound, but we have found a way to play with infinity. Once again lazy evaluation saves the day by only filtering when we need it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*A-yqRmRgD6iEm7is.gif" /><figcaption>sieve visualization</figcaption></figure><h4>Primes to Infinity</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afbc3a66cbefa17f91467357f6916108/href">https://medium.com/media/afbc3a66cbefa17f91467357f6916108/href</a></iframe><p>The sieve function simply implements the algorithm described above. It takes the first element of the stream as a prime, filters out all factors of it, and repeats the process for the next (prime) number. Passing the stream of natural numbers starting at 2 yields the primes.</p><p>It is amazing that we can create effectively infinite data structures within a finite memory space. It shows some of the power and beauty of lazy evaluation. As for actual uses of these lists, I won’t get into that here, but I found this <a href="https://stackoverflow.com/questions/5284458/what-are-some-compelling-use-cases-of-infinite-data-structures">stack overflow thread</a> had some interesting points. Some languages like Haskell have infinite lists built-in, so this concept is far from just theoretical.</p><h3>About the author</h3><p>Eric Breyer is a computer science undergrad at Rice University. You can find him at his <a href="http://www.ericbreyer.com/">website</a>, as well as on <a href="https://github.com/ericbreyer">GitHub</a> and <a href="https://www.linkedin.com/in/eric-breyer/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6662f143e3b9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/infinite-data-structures-part-2-6662f143e3b9">Infinite Data Structures: Part 2</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infinite Data Structures]]></title>
            <link>https://blog.devgenius.io/infinite-data-structures-9c193789dae6?source=rss-e55b34a5129a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c193789dae6</guid>
            <category><![CDATA[scheme]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[infinite]]></category>
            <dc:creator><![CDATA[Eric Breyer]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 19:37:41 GMT</pubDate>
            <atom:updated>2022-07-01T07:08:24.998Z</atom:updated>
            <content:encoded><![CDATA[<p>Using scheme and lazy evaluation to form infinite lists</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5KlQtw0CRrWRqMtwvyPXA.jpeg" /></figure><h3>Tools</h3><p>I will be using the Racket programming language in this guide. It is a much-expanded dialect of scheme, but most of this code should be directly transferable to R5RS-R7RS scheme. I believe concepts can be useful and implemented outside of scheme, it is just the tool I have chosen to use. Haskell has infinite lists built-in, other Lisps and functional languages like Javascript can certainly be used to implement infinite lists. Even <a href="https://stackoverflow.com/questions/13910259/list-with-infinite-elments">Python</a> can make infinite lists using similar or completely different methods.</p><h3>Lazy Evaluation and Streams</h3><p>Obviously, computers don’t have infinite memory, so an entire infinite data structure can not simply be stored in memory. Some elements can be evaluated in memory but some must be left unevaluated until we need them. Delaying expression evaluation until the value is needed is called lazy evaluation.</p><h4>Delaying Evaluation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5b86a5880ce9fc1c2915d0e3031dcad/href">https://medium.com/media/a5b86a5880ce9fc1c2915d0e3031dcad/href</a></iframe><p>If we want to delay the evaluation of an expression, we can wrap it in a lambda. Then it won’t be evaluated until we evaluate the lambda and force its body to evaluate. This can be achieved by defining a freeze macro, which just wraps an expression in a lambda to delay its expansion. Thaw then takes an expression wrapped in a lambda (a frozen expression) and forces evaluation.</p><p>Note: These functions are often referred to as delay and force but I have chosen different names here so as not to conflict with built-ins and to provide a visual image.</p><h4>Streams</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d211954ba0dcba834ccda003623a8005/href">https://medium.com/media/d211954ba0dcba834ccda003623a8005/href</a></iframe><p>A stream is a cons list where the tail’s evaluation is delayed/frozen until it needs to be evaluated — a lazy list. We will always have the head available to us, with the evaluation of the tail frozen. The moment we ask for the tail, it will thaw and give us a value. This could very well be another stream, with a value in the head and frozen expression in the tail. This allows us to create infinite lists. The definitions of various list functions for streams are given above, they act like the list functions of the same name, but freeze and thaw the evaluation of the tail as needed.</p><h3>Infinite Lists!</h3><p>the simplest infinite stream is a stream of all ones. This is defined as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5bd670aa990b1de7295dbefc84ed3fa/href">https://medium.com/media/c5bd670aa990b1de7295dbefc84ed3fa/href</a></iframe><p>ones is effectively an infinite list. There are two ways I have found to reason through what is happening.</p><h4>The declarative approach</h4><p>This approach is arguably the most beautiful but requires some trust and is a bit mind-bending at first. Looking at the problem through a declarative lens entails looking at what we tell the computer to do, not necessarily how it does it.</p><p>Assume the stream of infinite ones exists. Let&#39;s call it ones.This stream’s head has to be a 1 by definition. So we get (define ones (stream-cons 1 _)) fairly easily, but now we need to figure out what its tail is. If the stream has infinite ones, its tail must be a stream of infinite ones. Lucky us, we already have a stream of ones: ones ! So we get (define ones (stream-cons 1 ones))</p><h4>The imperative approach</h4><p>Looking at the problem through an imperative lens entails looking at how the computer actually evaluates the expression.</p><p>Let’s look at the definition of ones :(define ones (stream-cons 1 ones)) . This definition is recursive — it references itself. What if we replace ones in the expression with its definition. Since we are only swapping a variable with its definition this will produce an equivalent expression.</p><p>(equal? ones (stream-cons 1 ones)) — by definition<br>(equal? ones (stream-cons 1 <em>(stream-cons 1 ones)</em>)) — by definition of ones<br>(equal? ones (stream-cons 1 (stream-cons 1 <em>(stream-cons 1 ones)</em>))) — by definition of ones</p><p>This expansion can go on to infinity, luckily the list is lazy so it will only go to infinity if we ask it to. But it becomes obvious by working through it that this will produce a list of infinite ones.</p><h3>Stream-add</h3><p>Let&#39;s define a function stream-add, which scans down two streams, adds the corresponding elements together, and returns the new stream.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18c2621cd7e81bc8cccb3996917d01e7/href">https://medium.com/media/18c2621cd7e81bc8cccb3996917d01e7/href</a></iframe><p>Now a stream of twos is</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2e242e12ba549ed81e6fbf326f613a3/href">https://medium.com/media/b2e242e12ba549ed81e6fbf326f613a3/href</a></iframe><p>Reasoning declaratively, adding two streams of one&#39;s results in all twos. Reasoning imperatively, stream-add adds the head of each stream together (1 + 1 = 2), and then adds the tails. The tails are also ones so it’s just 1 + 1 = 2 all the way down.</p><h3>Increasing complexity</h3><p>So far our infinite lists, though infinite, are not very interesting. Let&#39;s try to make a stream of natural numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d8e5bea0245e53ccbe47e4a01151781/href">https://medium.com/media/1d8e5bea0245e53ccbe47e4a01151781/href</a></iframe><h4>Declarative reasoning</h4><p>Assume the stream of natural numbers exists. Let&#39;s call it nats.This stream’s head has to be a 1 by definition. So we get (define nats (stream-cons 1 _)) fairly easily, but now we need to figure out what its tail is. The tail of the list now has to be &#39;(2 3 4 5 6 7 8 …). This list is the stream addition of the natural numbers and the stream of ones. Lucky for us we already have both of these. Thus we end up with (define nats (stream-cons 1 (stream-add ones nats)))</p><h4>Imperative reasoning</h4><p>Let’s look at the definition of nats:(define nats (stream-cons 1 (stream-add ones nats))) . This definition is recursive — it references itself. What if we replace (stream-add ones nats))) in the expression with its definition. This will produce an equivalent expression.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b41c5b5f5b8ab3e66e4557d9f81a2bdf/href">https://medium.com/media/b41c5b5f5b8ab3e66e4557d9f81a2bdf/href</a></iframe><p>This results in a stream of natural numbers being formed. Again, since this is a stream the tail doesn’t expand to infinity like this, it only evaluates when we ask for it. In this way, the list truly is infinite in practice, but we don’t need infinite memory to store it.</p><h3>Fibonacci numbers</h3><p>This is where I think this concept gets taken to the next level. A stream of Fibonacci numbers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08c88ca1ea52cef98b1185d727f3efa3/href">https://medium.com/media/08c88ca1ea52cef98b1185d727f3efa3/href</a></iframe><p>Let&#39;s take a look at why this works. Once again, Assume the stream of Fibonacci numbers exists. Let&#39;s call it fibs. Fibs is the infinite list<br> &#39;(0 1 1 2 3 5 8 13 21 ...). Let&#39;s also look at (stream-cdr fibs) :<br>&#39;(1 1 2 3 5 8 13 21 34 ...). When we add these two streams together we get &#39;(1 2 3 5 8 13 21 34 55). So (equal? (stream-add fibs (stream-cdr fibs)) (stream-cdr (stream-cdr fibs))).</p><p>The first two elements of fibs are 0 and 1 by definition, hence (define fibs (stream-cons 0 (stream-cons 1 _))). Now we just need to figure out what the tail of this stream is; In other words what (stream-cdr (stream-cdr fibs)). We already have a definition for this though! Let&#39;s plug the property we previously discovered about fibs. We get (define fibs (stream-cons 0 (stream-cons 1 (stream-add fibs (stream-cdr fibs))))). This stream is quite beautiful in my opinion, and it gives a glimpse into the potential power and elegance of functional programming and lazy evaluation.</p><p>If this declarative reasoning is still confusing (which it was to me at first), you can also prove to yourself that this is correct using imperative reasoning. I will leave this as an exercise to the reader.</p><h3>Continued</h3><p>This story is a part one. Part two is now up <a href="https://eric-breyer.medium.com/infinite-data-structures-part-2-6662f143e3b9">here</a>. It goes further into more infinite lists and the grand finale of an infinite list of prime numbers.</p><h3>About the author</h3><p>Eric Breyer is a computer science undergrad at Rice University. You can find him at his <a href="http://www.ericbreyer.com/">website</a>, as well as on <a href="https://github.com/ericbreyer">GitHub</a> and <a href="https://www.linkedin.com/in/eric-breyer/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c193789dae6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/infinite-data-structures-9c193789dae6">Infinite Data Structures</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nondeterministic Sudoku Solver]]></title>
            <link>https://blog.devgenius.io/nondeterministic-sudoku-solver-1922a7ebfa3d?source=rss-e55b34a5129a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1922a7ebfa3d</guid>
            <category><![CDATA[sudoku]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[scheme]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Eric Breyer]]></dc:creator>
            <pubDate>Sun, 26 Jun 2022 03:34:37 GMT</pubDate>
            <atom:updated>2022-07-01T07:08:26.581Z</atom:updated>
            <content:encoded><![CDATA[<p>Using the amb special form to solve sudoku in racket/scheme</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nkYJD2kbfjzS8bOc8k-9-A.gif" /><figcaption>Solving sudoku using the amb form and a logical programming style</figcaption></figure><p>Accompanying code can be found <a href="https://github.com/ericbreyer/NondeterministicSudoku">here</a></p><h3>Inspiration</h3><p>I came across this <a href="https://www.youtube.com/watch?v=iOJD7nd7cyY">video</a> in which I was introduced to the Amb operator. It immediately looked like black magic, so I researched how it works and its implementations.</p><h3>Amb</h3><p>amb is the ambiguous choice (nondeterminism) operator. It takes a list of possibilities and evaluates to an option that allows the program to succeed. In practice, `amb` usually tries its options left to right but theoretically, the evaluation order doesn&#39;t matter - hence &quot;nondeterminism&quot;.<br><br>assert, also sometimes require, defines a predicate the program has to satisfy. If the predicate fails, the current branch of the program is abandoned and new possibilities of amb forms are tried until the assertion holds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a4dce8fe43425936ad8da397219cc79/href">https://medium.com/media/9a4dce8fe43425936ad8da397219cc79/href</a></iframe><p>This is the implementation of amb I have chosen to use.<br>It defines 2 continuations, a success (sk) and a fail (fk). The success continuation is for passing the next possibility of the amb to. The fail continuation is created to capture the state of the program before a path is tried. If the program fails under this possibility, it abandons everything and restores the program to this point in time, ready to move on to the next possibility to try (note the ..., a call/cc/fk &quot;block&quot; is created for each possibility to allow amb to try the next possibility after it returns from a failure.<br><br>Because of this nature of trying all possibilities of an amb before calling the fail for a previous amb, the actual underlying logic to find a valid set of options for the amb form is a depth-first search. This is useful to understand when determining the efficiency of this strategy for solving problems (though an iterative or traditionally recursive depth-first search will probably be more efficient than all the call/cc overhead amb requires).<br><br>Further readings and implementations I consulted:<br>- <a href="http://community.schemewiki.org/?amb">http://community.schemewiki.org/?amb</a><br>- <a href="http://www.sfu.ca/~tjd/383summer2019/scheme-amb.html">http://www.sfu.ca/~tjd/383summer2019/scheme-amb.html</a><br>- <a href="http://wiki.c2.com/?AmbSpecialForm">http://wiki.c2.com/?AmbSpecialForm</a><br>- <a href="https://gist.github.com/Liudx1985/11308921">https://gist.github.com/Liudx1985/11308921</a></p><h3>Logical Programming</h3><p>Logical programming is a style of programming in which the programmer:<br>1. States facts about the problem domain (like the possible values of sudoku squares)<br>2. Makes assertions about the facts of the domain (that the numbers in the squares must satisfy sudoku constraints)<br>3. Queries, or asks questions, about the facts of the domain (give a valid sudoku)<br><br>This is a declarative rather than imperative programming paradigm: telling the computer <strong>what</strong> to do instead of <strong>how</strong> to do it.<br><br>amb lends itself to this style.<br>- amb statements are the facts about the domain<br>- assert statements are assertions about the domain<br>- asking for the value of a variable is a query</p><h3>Solving Sudoku</h3><p>This style should make solving a sudoku simple. It is literally called a <strong>logic </strong>puzzle. Theoretically, we just need to populate all empty squares with (amb 1 2 3 4 5 6 7 8 9), assert that rows should have unique numbers, etc., and then ask for the board. <br>This will work, but it will take forever. Declaring all the `amb`s first and then asserting will search a lot of dead ends that don&#39;t need to be searched (and wouldn&#39;t be in a proper DFS algorithm). A better way is to go square by square.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5797a342f7c43874a30efb75abed8d6e/href">https://medium.com/media/5797a342f7c43874a30efb75abed8d6e/href</a></iframe><p>Checking and asserting square by square cuts off a lot of searching through paths that could never work, as if the square doesn&#39;t work, it will never search further. Declaring all the ambs all at once always starts the search at the very bottom of the tree of possibilities and turns this into more of a brute force algorithm.<br><br>Then we just need to run this function on every unsolved square. The logical programming is still here:<br>1. First declare the fact that the square has to be an integer 1-9<br>2. Then assert that it must satisfy the sudoku rules<br>3. We query the final board after solving every square<br><br>This is the whole algorithm needed to solve a sudoku. The rest of the code is there to build a sudoku board in the correct format, apply solveSquare, and create a GUI.<br><br>I find amb fascinating and it still almost feels like magic. You just have to tell the program what you want, and it will create and destroy universes and rewind time until it magically produces a valid result.</p><h3>About the author</h3><p>Eric Breyer is a computer science undergrad at Rice University. You can find him at his <a href="http://www.ericbreyer.com/">website</a>, as well as on <a href="https://github.com/ericbreyer">GitHub</a> and <a href="https://www.linkedin.com/in/eric-breyer/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1922a7ebfa3d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/nondeterministic-sudoku-solver-1922a7ebfa3d">Nondeterministic Sudoku Solver</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Call with Current Continuation as Recursive Return]]></title>
            <link>https://blog.devgenius.io/call-with-current-continuation-as-recursive-return-ac58244c445?source=rss-e55b34a5129a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac58244c445</guid>
            <category><![CDATA[racket]]></category>
            <category><![CDATA[scheme]]></category>
            <category><![CDATA[continuation]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Eric Breyer]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 22:32:49 GMT</pubDate>
            <atom:updated>2022-12-19T08:41:58.194Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use of Call/CC in Scheme to “return” early from recursive definitions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*KvExxPTUtVKEcVNUE2_zoQ.png" /></figure><h4>What is a Continuation</h4><p>When a function calls another function, it waits for a return value to do something with. For example, in the expression (+ 1 (f x)) ,(+ 1 _)is the continuation for the execution of (f x). The continuation is what is going to handle and what is waiting on the return value from (f x).</p><h4>Call/CC</h4><p>call/cc takes a lambda expression with a single argument, and passes the current continuation to the function as its argument.</p><pre>(+ 1 (call/cc <br>       (lambda (cont)<br>         (cont 5))))</pre><p>This code is fairly simple, but we can see the current continuation ( + 1 _) gets passed to the lambda expression as cont.</p><p>cont is itself a lambda expression, if we call it with an argument it will take that argument as the argument to the continuation and execute the continuation. We can use this almost like returning from a function. We can pass a value straight to the function’s continuation instead of waiting for the function to exit normally.</p><p>In the example above, we simply pass 5 to cont . ( + 1 5) then gets executed and this snippet exits with a value of 6.</p><p>Lets look at another 2 code snippets</p><pre>(+ 1 (call/cc <br>       (lambda (cont)<br>         (+ 3 3))))</pre><p>And</p><pre>(+ 1 (call/cc <br>       (lambda (cont)<br>         (cont 5)<br>         (+ 3 3))))</pre><p>The first snippet simply exits with a value of 7, doing nothing with the continuation. The second however, passes 5 straight to the lambda’s continuation immediately when cont 5 is executed. Thus, this lambda will never actually execute (+ 3 3) , and the snippet will exit with value 6. In this case, cont 5 is similar to <strong>return</strong> 5 in another language. We have effectively returned from the function early.</p><p>There are various uses of continuations, but one interesting one is an early return from a recursive function.</p><h4>Application with Multiplying Elements of a List</h4><p>First define a function multListNoCC which takes a list of numbers and multiplies them together recursively.</p><pre>(define multListNoCC <br>  (lambda (lat)<br>    (cond<br>      ((null? lat) 1)<br>      (#t (* (car lat) (multListNoCC (cdr lat)))))))</pre><p>However, this algorithm can be made more efficient. If any element in the list is a zero, we know the final product must be zero. Therefore we can stop multiplying the elements and just return zero as the product, rather than continuing to traverse the list. However, if we just add a case in the function to return zero, it the zero will just get passed back up the recursive stack. We can use call/cc to “pop out” of all the recursive calls and return a 0 to the original caller. For example:</p><pre>(define multList <br>  (lambda (lat)<br>    (call/cc (lambda (cont)<br>      (letrec ((helper (lambda (x)<br>        (cond<br>          ((null? x) 1)<br>          ((eq? (car x) 0) (cont 0))<br>          (#t (* (car x) (helper (cdr x))))))))<br>        (helper lat))))))</pre><p>In the function multList, helper is almost exactly the same as multListNoCC. We wrap helper in a few lambdas that let it have access to the original CC that the function was called from as well as the list we want to multiply. We can then add another condition to helper: when the current element equals zero, immediately stop the recursion and pass a zero to the original continuation. ie: ((eq? (car x) 0) (cont 0))<br>cont is the CC before the recursion started — the original caller, so passing a value to cont effectively stops the recursion and returns a value straight back.</p><p>If a zero is never encountered, the function will return normally by passing values all the way back up the recursive stack.</p><h4>More examples and applications</h4><pre>(define isNumInList<br>  (lambda (lat num)<br>    (call/cc (lambda (cont)<br>      (letrec ((helper (lambda (l n)<br>        (cond<br>          ((null? l) #f)<br>          ((eq? (car l) n) (cont #t))<br>          (#t (helper (cdr l) n ))))))<br>        (helper lat num))))))</pre><p>If we have found an instance of the number, there is no need to continue traversal.<br>If we get all the way down to the end of the list and haven’t found the element, pass an #f all the way back up to signal that we haven’t found the number.</p><pre>(define findFirstNumInList<br>  (lambda (lat num)<br>    (call/cc (lambda (cont)<br>      (letrec ((helper (lambda (l n index)<br>        (cond<br>          ((null? l) -1)<br>          ((eq? (car l) n) (cont index))<br>          (#t (helper (cdr l) n (+ index 1)))))))<br>          (helper lat num 0))))))</pre><p>Much like isNumInList but returns the index of the found element (or -1 if the element is not in the list.</p><h4>About the author</h4><p>Eric Breyer is a computer science undergrad at Rice University. You can find him at his <a href="http://www.ericbreyer.com/">website</a>, as well as on <a href="https://github.com/ericbreyer">GitHub</a> and <a href="https://www.linkedin.com/in/eric-breyer/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac58244c445" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/call-with-current-continuation-as-recursive-return-ac58244c445">Call with Current Continuation as Recursive Return</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>