<?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 James Carlson on Medium]]></title>
        <description><![CDATA[Stories by James Carlson on Medium]]></description>
        <link>https://medium.com/@jxxcarlson?source=rss-5de01b007190------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aEPGuJfuwCdd27kvU4KVOQ.png</url>
            <title>Stories by James Carlson on Medium</title>
            <link>https://medium.com/@jxxcarlson?source=rss-5de01b007190------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:51:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jxxcarlson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Text-to-Drumbeat App]]></title>
            <link>https://jxxcarlson.medium.com/a-text-to-drumbeat-app-23064b9760bd?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/23064b9760bd</guid>
            <category><![CDATA[drums]]></category>
            <category><![CDATA[functional-program]]></category>
            <category><![CDATA[computer-music]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 17:02:17 GMT</pubDate>
            <atom:updated>2023-11-01T17:57:14.364Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://jxxcarlson.github.io/app/drumlanguage.html">https://jxxcarlson.github.io/app/drumlanguage.html</a></p><figure><img alt="slit drum" src="https://cdn-images-1.medium.com/max/700/1*hBPICSIInqEN8twYAd6Z8A.jpeg" /></figure><p>Some time ago, I read James Gleick’s book <em>The Information: a History, a Theory, a Flood.</em> In the first chapter, he recounts a remarkable discovery by John F. Carrington, an English missionary, who took up residence in the Congo in 1938, working for the Baptist Missionary Society. On a trip from the Society’s Yakutsu station on the Upper Congo River through the Bambole Forest, he realized that the local people were able to use drums to send detailed messages over long distances. Here is a short extract of a funeral announcment:</p><blockquote><em>La nkesa laa mpombolo, tofolange benteke biesala, tolanga bonteke bolokolo bole nda elinga l’enjale baenga, basaki l’okala bopele pele. Bojende bosalaki lifeta Bolenge wa kala kala, tekendake tonkilingonda, tekendake beningo la nkaka elinga l’enjale. Tolanga bonteke bolokolo bole nda elinga l’enjale, la nkesa la mpombolo.</em></blockquote><blockquote>In the morning at dawn, we do not want gatherings for work, we want a meeting of play on the river. Men who live in Bolenge, do not go to the forest, do not go fishing. We want a meeting of play on the river, in the morning at dawn.</blockquote><p>It took Carrington some time to decipher the secret of the drums. The key fact was that the local language was a tonal one, with two tones, high and low. The drummers, using slit drums, would sound the tones of the words to be sent. Thus <em>alambaka boili</em>, meaning “he watched the riverbank,” was rendered as <strong>H L H H L L L</strong>, where <strong>H</strong> is a high-pitched sound and <strong>L</strong> is low-pitched. While much information is lost in this pitch encoding, that which remains, plus the context, plus the use of many conventional formulae, gives the listener enough information to reconstruct the original sentence.</p><h3>A Drum App</h3><p>Inspired by this story, I decided to make a little app to do something similar. You can see a screen shot below. There are two windows, Voice 1 and Voice 2. The first plays in quarter notes, the second in eighth notes. Text in each window is translated into notes via an algorithm we describe later. For example, the text <em>,,,Hey jude</em> is translated as <em>Rest Rest Rest G3 C3 C3 Rest D4 C3 Bf3 C3,</em> where spaces and commas are mapped to rests. The notes <em>G3 </em>and <em>G4</em> are the note <em>G</em> in different octaves, and <em>Bf </em>is <em>B</em>-flat. Etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXZgm1dOwRog0s8zSh5mhg.png" /><figcaption><a href="https://jxxcarlson.github.io/app/drumlanguage.html">https://jxxcarlson.github.io/app/drumlanguage.html</a></figcaption></figure><p>Note the period of the two voices taken together. In the case of the voices in the screenshot, the period is 1800 eighth note beats — the least common multiple of twice the length of voice 1 and the length of voice 2 (For this purpose we count in eighth notes). In this way two short fragments, one for each voice, can produce music with a long period — the smallest number of eighth notes before the music repeats.</p><h4>Mapping text to sound</h4><p>My approach for generating sound was to map each letter a–z to a phonetic class, then map phonetic classes to musical pitches. The phonetic class of <em>a, e, i, o, u</em> is VOWEL. Consonants are divided into various classes, e.g., <em>m, </em>and<em> n</em> are of class NASAL. Each class is assigned a pitch, and so we can map any string of characters to a sequence of pitch names. For example, <em>Hello</em> is assigned the sequence <strong>G3 G2 C3 C3 G2</strong>. Here the numerical part of a pitch name refers to its octave, and so G3 is one octave higher than G2. The pitches used to represent the pitch classes are <strong>G2 C3, E3, F3, G3, Bb3, D</strong> — a dominant ninth chord. This choice of mapping makes the drumming sound relatively harmonious.</p><h3>Postscript</h3><p>Gleick writes that Carrington eventually learned to drum, mainly in Kele, a Bantu language in what is now Eastern Zaire. He recounts this story:</p><blockquote>A Lokele villager said of Carrington “He is not really European, despite the color of his skin. He used to be from our village, one of us. After he died, the spirits made a mistake and sent him off far away to a village of whites to enter the body of a little baby who was born of a white woman instead of one of ours. But he belongs to us, he could not forget where he came from, and so he came back. If he is a bit awkward on the drums, this is because of the poor education that the whites gave him.”</blockquote><p>There is much more in Gleick’s book. It is a really good read.</p><h3>More info</h3><p>For more information, see the (open source) code and the README document at</p><p><a href="https://github.com/jxxcarlson/DrumLanguage">https://github.com/jxxcarlson/DrumLanguage</a></p><p>The code for the app itself — user interface, parsing of the input, translating the input into a form that Tone.js can understand —is written in Elm, a language of pure functions (https://elm-lang.org).</p><p>The Tone.js library is used for sound generation. Take a look at the README file at <a href="https://github.com/jxxcarlson/DrumLanguage">https://github.com/jxxcarlson/DrumLanguage</a> for more details.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23064b9760bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experiments with OpenAI]]></title>
            <link>https://jxxcarlson.medium.com/experiments-with-gpt-b93819ac4c03?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/b93819ac4c03</guid>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[abstract-art]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Sun, 07 May 2023 21:28:20 GMT</pubDate>
            <atom:updated>2023-05-26T19:09:47.848Z</atom:updated>
            <content:encoded><![CDATA[<p><em>See the app at </em><a href="https://imagemachine.io/"><em>imagemachine.io</em></a><em>.</em></p><p>The past few weeks, like many, I’ve been drawn to experiment with OpenAI’s offerings. My test project wast to build a little app to make images using DALL-E. Below is one image, created by asking “make an abstract painting mixing the styles of Braque and Klee; use blues, reds, a little orange and warm grays.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*OvKK3mTSHQ1rARUEshATzA.jpeg" /></figure><p>Below is another, generated by asking DALL-E to “make an abstract painting blending the styles of Braque and Signac. Use mostly pastel colors but some with strong values.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*U-ecj1Hs2SnBJwsl9loWPg.jpeg" /></figure><p>Writing the app turned out to be surprisingly easy. OpenAI, the company behind ChatGPT, has very <a href="https://platform.openai.com/docs/introduction">good documentation</a>. Browsing it, I found an <a href="https://platform.openai.com/docs/api-reference/images/create">explanation of how to generate images</a>. Here is the key piece of code, a shell script:</p><pre>url https://api.openai.com/v1/images/generations \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer $OPENAI_API_KEY&quot; \<br>  -d &#39;{<br>    &quot;prompt&quot;: &quot;A cute baby sea otter&quot;,<br>    &quot;n&quot;: 2,<br>    &quot;size&quot;: &quot;1024x1024&quot;<br>  }</pre><p>I signed up for an API key, tried out the shell script, and with it as a guide, built a small web app<em>. </em>Below is a screenshot of the first version, which you can find at <a href="https://imagemachine.io/"><em>imagemachine.io</em></a>. It is written in <a href="https://elm-lang.org/">Elm, a pure functional language</a>, using <a href="https://package.elm-lang.org/packages/choonkeat/elm-openai/latest/">choonkeat’s Elm library for working with the OpenAI API</a>. There will be some upgrades coming in the next few weeks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*1npuMXRZS-trOHkA4WNZ1Q.jpeg" /></figure><p>PS. While I’ve used the app mostly for generating abstract art, you can of course prompt it to create any kind of image. Here is one such example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*xI8nmK8UhFgyKoi_j2psmg.jpeg" /></figure><p>Here is one more image, with a fairly long prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeTafGPyvZfmJmk-coHY_w.png" /></figure><p>Prompt for the above: <em>An abstract composition with one large shape, two medium-sized shapes, and a few smaller ones. Make it two-dimensional. Add a network of lines. The background should be reminiscent of Australian aboriginal paintings. Keep the colors only partially saturated, with lots of grays and earth tones.</em></p><p><strong>Remark</strong>. In its current incarnation, the app generates 10 images per prompt. My experience is that one has to look through at least that many images on average to find one that has satisfying esthetics. The other knob to turn, of course, is tuning the prompt itself, using it to guide DALL-E in the direction you want to go (and discovering or at least refining that direction as you proceed).</p><h4>Addendum, May 13, 2023</h4><p>I’ve added a number of features to <a href="https://imagemachine.io/"><em>imagemachine.io</em></a>: (a) users can store generated images that they like in a private searchable library, (b) images can be displayed as a “gallery,” as in the example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCa2h_T2R5nbnviVemfLUA.png" /></figure><p>Public galleries can be accessed by url without sign-in. Try <a href="https://imagemachine.io/gallery/jxxcarlson">imagemachine.io/gallery/jxxcarlson</a> or <a href="https://imagemachine.io/gallery/zeno">imagemachine.io/gallery/zeno</a>.</p><h4>Addendum, May 26, 2023</h4><p>The best way to see what people are doing with <a href="https://imagemachine.io/exhibit">ImageMachine.io</a>. Just go to <a href="https://imagemachine.io/exhibit">https://imagemachine.io/exhibit</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIW2BeeUX6gRtdvI3ipzYA.png" /><figcaption>Exhibit Space @ ImageMachine.io</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b93819ac4c03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elm + Tauri]]></title>
            <link>https://jxxcarlson.medium.com/elm-tauri-befa59eab403?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/befa59eab403</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[tauri]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 20:33:41 GMT</pubDate>
            <atom:updated>2023-01-10T14:16:24.991Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/jxxcarlson/scripta-tauri/releases">Download Scripta Desktop</a></p><h3>Introduction</h3><p>Want to develop a desktop app with <a href="http://elm-lang.org/">Elm</a>? Use <a href="https://tauri.app/">Tauri</a>!</p><p>Elm is an amazing language for building web apps: a stable platform with no churn, no worries about runtime errors, and best of all, safe refactoring. Even major refactoring of core program structures is something you can do without fear. <em>You’ve decided that xyz needs to be reworked completely but you are concerned about breaking things. Not to worry! Just go for it — the compiler with its static type system has your back.</em></p><p>What Elm lacks, however, is way to build desktop apps. One solution is to use Electron. But my number one choice is Tauri: it builds small binaries, has a nice workflow, and apps can be compiled for Linux, MacOS (universal binaries), or Windows. Support on the Tauri Discord channel has been excellent.</p><p>In this article, the first of a short series, I’ll describe the development process used for Scripta Desktop, a desktop version of the web app <a href="https://scripta.io/">scripta.io</a>. (We describe it below). You can find the source code on <a href="https://github.com/jxxcarlson/scripta-tauri">Github</a>. The latest universal binary for MacOS is available <a href="https://github.com/jxxcarlson/scripta-tauri/releases">here</a>.</p><p>Part 2 will discuss how to use the Tauri API for file system access. Part 3 deals with integration of the app with the Codemirror 6 editor. Part 4 will discuss the dreaded task of codesigning the installer.</p><h4>What is Scripta Desktop?</h4><p><em>If you are interested in what Scripta can do, read this … otherwise skip to the next section.</em></p><p>Scripta Desktop provides a real-time interactive editing environment for MicroLaTeX, a version of LaTeX, as well as a couple of other markup languages. As you type in the editor (left window in image below), the source text is instantly rendered into HTML (right window).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PHEnGCUKeJOX7sVa4-NJg.png" /><figcaption>MicroLaTeX document in Scripta Desktop</figcaption></figure><p>The Scripta Desktop app requires no internet access, so you can work on a plane, on a mountaintop, or in a cave. Scripta documents are saved automatically and stored in ~/Desktop/scripta; the app will export them to standard LaTeX or PDF if you need these.</p><h3>Setting things up</h3><p>Below is an outline of the setup procedure on MacOS for turning an existing Elm web app into a desktop app using <a href="https://tauri.app/">tauri.app</a>. As an example, we use the <a href="https://guide.elm-lang.org/architecture/buttons.html">counter app</a> from the Elm guide. The code for the Tauri desktop version is on <a href="https://github.com/jxxcarlson/counter-tauri">Github</a>. In Part 2, we use the same procedure to make Scripta Desktop. The new elements in Part 2 will be (a) adding fonts, CSS styles, and Javascript code from <a href="https://katex.org/">KaTeX.org</a> to render mathematical equations; (b) Using the Tauri fsAPI to access the host computer’s file system so as to open and save files.</p><p>For more info and for the procedure for other operating systems, see the T<a href="https://tauri.app/v1/guides/getting-started/setup/integrate">auri docs</a>.</p><p><strong>Procedure (MacOS)</strong></p><ul><li>Make sure xcode tools are installed: run xcode-select --install</li><li>Install Rust:</li></ul><pre>curl --proto &#39;=https&#39; --tlsv1.2 https://sh.rustup.rs -sSf | sh</pre><ul><li>Install the Tauri toolchain: cargo install tauri-cli.</li><li>Set up the Elm + Tauri project. Make a new directlry, say counter, and cd into it. Then run cargo tauri init. This command will lead you through a series of questions and make a skeleton Tauri project for you.</li></ul><pre>$ cargo tauri init<br>✔ What is your app name? · Counter<br>✔ What should the window title be? · Counter<br>✔ Where are your web assets (HTML/CSS/JS) located, relative to the &quot;&lt;current dir&gt;/src-tauri/tauri.conf.json&quot; file that will be created? · ../src<br>✔ What is the url of your dev server? · <a href="http://localhost:4000/">http://localhost:4000</a><br>✔ What is your frontend dev command? · sh dev.sh<br>✔ What is your frontend build command? · sh build.sh</pre><p>My dev.sh command is a one-liner:</p><pre>elm make src/Main.elm --output=public/main.js</pre><p>The build.sh script is the same, but with the --optimize flag. Usenpm install serve to install the dev server.</p><p>The directory in which you issued the cargo tauri init command will now look like the below.</p><pre>└── src-tauri<br>    ├── Cargo.toml<br>    ├── build.rs<br>    ├── icons<br>    │   ├── 128x128.png<br>    │   ...<br>    │   └── icon.png<br>    ├── src<br>    │   └── main.rs<br>    └── tauri.conf.json</pre><p>The tauri.conf.json file is the one that you will mostly work with. For this project, it starts out like this:</p><pre>{ &quot;build&quot;: {<br>  &quot;beforeBuildCommand&quot;: &quot;sh build.sh&quot;,<br>  &quot;beforeDevCommand&quot;: &quot;sh dev.sh&quot;,<br>  &quot;devPath&quot;: &quot;http://localhost:4000&quot;,<br>  &quot;distDir&quot;: &quot;../public&quot;,<br>  &quot;withGlobalTauri&quot;: true<br>},<br>...</pre><p>The &quot;withGlobalTauri&quot;: true line is needed because I’m not using a bundler (more on this in Part 2, using the Tauri file system API). You will need to change the &quot;identifier&quot; field from its default value, e.g., to &quot;identifer&quot;: io.counter-tauri. I also set the&quot;height&quot; and &quot;width&quot; in the &quot;windows&quot; section of tauri.conf.json.</p><p><strong>Your files</strong></p><p>Make two new directories, src and public. They are siblings of src-tauri. Put your Elm code in src and put your index.html file in public. In this example, the only resident of src is Main.elm. Also put whatever assets your app needs (Javascript, CSS, font folders, etc) in public. Below is the publicfolder. The index.html is the usual one for an Elm app for which Main.elm is compiled tomain.js .</p><pre># folder: public<br>index.html<br>main.js<br>&lt;.js and .css files, font folders, etc&gt;</pre><h3>Development</h3><p>Once things are set up, run npx server public -l 4000 and then cargo tauri dev. This will (1) bring your Elm app up on localhost:4000, and (2) bring up a native version your app. It should look like this:</p><figure><img alt="Tauri version of the counter app." src="https://cdn-images-1.medium.com/max/494/1*jYlF-S34iYNmcqXC5cZWKQ.png" /><figcaption>Scripta version of the Elm counter app</figcaption></figure><p><strong>Notes</strong>: (1) the app running on localhost won’t have access to features that require the Tauri API’s, e.g., access to the file system. (2) For live reload of the Elm app, I use npx elm-watch hot. See <a href="https://github.com/lydell/elm-watch">this link</a>.</p><p>To debug the native app, right-click on it and choose inspect. This will bring up your dev tools (console, network, etc.)</p><h3>Distribution</h3><p>Use cargo tauri build. On MacOS, if you want a universal binary, say cargo tauri build --target universal-apple-darwin. You may get an error message telling you to install some Rust code. Go for it!</p><p>After you issue the build command, Tauri while work for a little while, after which you will be presented with a window with the new app. Move it into the Applications folder.</p><p>For distribution (without codesigning), you need a .zip file. For the moment, I do something like the below for Scripta Desktop.</p><pre># zip.sh<br>cp -r /Applications/scripta-desktop.app .<br>zip -r scripta-desktop.zip scripta-desktop.app<br>rm -r scripta-desktop.app</pre><p>The resulting scripta-desktop.zip can be distributed for users to expand to scripta-desktop.app.</p><h3>Next</h3><p><strong>Part 2: </strong>Using the Tauri APIs. I’ll discuss how to open and save files using ports (Elm) and the Tauri APIs .</p><p><strong>Part 3</strong>: Integration with the Codemirror 6 editor.</p><p><strong>Part 4:</strong> Codesigning the installer</p><h3>Acknowledgements</h3><p>Many thanks to FabianLars on the <a href="https://tauri.app/">Tauri </a>dev team for help getting started with the fs API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=befa59eab403" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda Calculus: an Elm CLI]]></title>
            <link>https://jxxcarlson.medium.com/lambda-calculus-an-elm-cli-fd537071db2b?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd537071db2b</guid>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[lambda-calc]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 17:37:51 GMT</pubDate>
            <atom:updated>2022-01-17T13:57:38.379Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gkFVaSBARqlwmjnjut8EEg.png" /></figure><h4>Introduction</h4><p>The lambda calculus, sometimes described as the world’s smallest programming language, was devised by Alonzo Church in 1932–33 as new foundation for logic. A <em>term</em> (think “phrase”) in the lambda calculus is made up of just three grammatical entities: <em>variables</em>, <em>abstractions</em>, and <em>applications</em>. Variables are things like x, y, z, ... . An abstraction <em>(λx.E), </em>where E is a lambda term,<em> </em>defines a function of <em>x. </em>For example,<em> (λx.2x + 1) </em>is the function that doubles whatever x is, then adds 1. The expression <em>(λx.2x + 1) (3) </em>is an application. Its meaning is given by the <em>rule of substitution</em>: in the body of the abstraction, namely the expression <em>2x + 1</em>, replace every occurrence of <em>x</em> by <em>3, </em>obtaining 7<em>.</em></p><p>To summarize: we have variables, abstractions, used to define functions, and applications, used to apply functions to data. Application is carried out by the rule of substitution.</p><p>In the pure lambda calculus, we have only variables, abstractions, and applications. An expression like 2x + 1 is therefore not part of the pure lambda calculus. It is made up of the integers 1 and 2 and the operations of addition and multiplication. Nonetheless, it is possible to encode the integers in the lambda calculus and with these encodings to define addition, multiplication, and all the rest of arithmetic. Even more is true: anything that can be computed can be expressed in the lambda calculus. This is the Church-Turing thesis. Another way of stating the Church-Turing thesis is that the operation of a universal Turing machine may be encoded in the lambda calculus and, conversely, that one can write a program for a Turing machine that carries out arbitrary computations in the lambda calculus.</p><h4>A Lambda Calculator</h4><p>As a tool to use in my quest to understand the lambda calculus, I wrote a small program in <a href="https://elm-lang.org/">Elm</a> to “run” the lambda calculus. Easier than writing for a Turing machine. Here is a sample session:</p><pre>$ lambda<br>Welcome! type :help for help<br>&gt; (\x.x) (\y.y)<br>λy.y</pre><p>Here the text \x.x is the way we write λx.x at the keyboard. We apply this lambda expression to the lambda expression λy.y when we say (\x.x) (y.y). The rule of substitution says “in the body of λx.x, namely x, replace all occurrences of x by λy.y. If we do that, we get λy.y. The lambda term λx.x is the identity function: apply it to anything, and it returns what you give it.</p><p>As with any good calculator, we can store things for later use:</p><pre>&gt; :let id = \x.x<br>added id as λx.x</pre><pre>&gt; id id<br>λx.x</pre><p>Our lambda calculator comes with a “standard library,” as displayed below. The Boolean values of true and false are encoded as λx.λy.x and λx.λy.y, respectively. Encodings of the natural numbers zero, one, two, and three are also given. Working by hand or with the lambda calculator, one finds that succ zero = one, succ one = two, etc. Thussucc is the successor function: the function that adds one to any natural number.</p><pre># Standard Libary</pre><pre># Booleans<br>true      \x.\y.x<br>false     \x.\y.y<br>and       \p.\q.p q p<br>or        \p.\q.p p q<br>not       \p.p (false) true<br><br># Church numerals<br>zero      \s.\z.z<br>one       \s.\z.s z<br>two       \s.\z.s s z<br>three     \s.\z.s s s z<br>isZero    \n.n (\x.zero) true<br>succ      \n.\f.\x.f(n f x)</pre><p>Let’s check out the standard library by doing some Boolean algebra computations</p><pre>&gt; and true true<br>λx.λy.x</pre><pre>&gt; and true false<br>λx.λy.y</pre><pre>&gt; and false false<br>λx.λy.y</pre><h4>Implementing the Calculator in Elm</h4><p>To implement the calculator in Elm, we begin with a definition that captures the notion of a lambda term:</p><pre>type Expr<br>    = Var <strong>String<br>    </strong>| Lambda <strong>String Expr<br>    </strong>| Apply <strong>Expr Expr</strong></pre><p>Some examples where we parse a string representation of a lambda term to a value of type Expr:</p><pre>&gt; :parse x<br>Ok (Var &quot;x&quot;)</pre><pre>&gt; :parse \x.x<br>Ok (Lambda &quot;x&quot; (Var &quot;x&quot;))</pre><pre>&gt; :parse (\x.x) \y.y<br>Ok (Apply (Lambda &quot;x&quot; (Var &quot;x&quot;)) (Lambda &quot;y&quot; (Var &quot;y&quot;)))</pre><p>The relevant code can be found at <a href="https://package.elm-lang.org/packages/jxxcarlson/elm-lambda/latest/">jxxcarlson/elm-lambda</a>: a package and an app that runs on the command line. There is also the <a href="https://github.com/jxxcarlson/elm-lambda">GitHub repo</a>.</p><p>Brief summary of the various modules:</p><p><strong>Lambda.Expression</strong>: the type Expr and the function beta : Expr -&gt; Expr that does beta reduction, aka computation.</p><p><strong>Lambda.Parser</strong>: parse strings to Exprs.</p><p><strong>Lambda.Defs</strong>: the machinery for setting up a dictionary mapping names to string representations of lambda terms so that we can say and true false instead of</p><pre>(\p.\q.p q p) (\x.\y.x) (\x.\y.y)</pre><p><strong>Lambda.Eval</strong>: the function eval: Dict String String -&gt; String -&gt; String that is used to run the calculator in the app folder.</p><h4>References</h4><p><a href="https://iep.utm.edu/lambda-calculi/">Lambda Calculi, in Internet Encyclopedia of Philosophy</a></p><p><a href="https://en.wikipedia.org/wiki/Lambda_calculus">Lambda Calculus (Wikipedia)</a></p><p>Church, Alonzo. 1932. “A Set of Postulates for the Foundation of Logic (Part I).” <em>Annals of Mathematics</em>, 33(2):346–366.</p><p>Church, Alonzo. 1933. “A Set of Postulates for the Foundation of Logic (Part II).” <em>Annals of Mathematics</em>, 34(4):839–864.</p><h3>Addenda</h3><h4>Output options</h4><p>I’ve added some additional output options. The default is :pretty. Switch between options using :named, :pretty, and :raw:</p><pre>&gt; and true false<br>false<br><br>&gt; :pretty<br>&gt; and true false<br>λx.λy.y<br><br>&gt; :raw<br>&gt; and true false<br>\x.\y.y<br><br>&gt; :named<br>&gt; and true false<br>false</pre><p>Recall that when you type in a lambda expression with no :command, the expression is beta-reduced.</p><h4>:beta command</h4><p>The :beta command checks for beta-equivalence of two terms:</p><pre>&gt; :beta (succ zero) one<br>true</pre><p>It does alpha-conversion, aka renaming variables:</p><pre>&gt; :beta (\x.x) (\a.a)<br>true</pre><p>And it has some guards against divergent expressions. Let omega = λx.x x and let Omega = (λx.x x)(λx.x x). Then we have</p><pre>&gt; Omega<br>TOO MANY SUBSTITUTIONS (size2 &gt; 100000). Term may be divergent</pre><pre>&gt; :beta Omega Omega<br>LHS may be divergent</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd537071db2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Trees with Elm]]></title>
            <link>https://jxxcarlson.medium.com/building-trees-with-elm-75e0dc5da35d?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/75e0dc5da35d</guid>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[rose-tree]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Sun, 05 Dec 2021 05:14:12 GMT</pubDate>
            <atom:updated>2021-12-05T05:14:12.286Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is about trees — the computer science kind, as illustrated in Figure 1 below. Our goal is to see how trees can be derived from text and, conversely, how trees can be turned back into text. Along the way, we will see how to display trees graphically, as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*hndVis9luoEqA4eDiH499g.png" /></figure><p>Let’s establish some terminology. In the Figure, we see blue dots — nodes—labeled by integers and some more text. The node labeled 1 is the <em>root</em> of the tree. It has two <em>children</em>, the <em>subtrees</em> with roots labeled 3 and 4. We say that the node labeled 1 is the <em>parent</em> of the nodes labeled 3 and 4. Etc. Our tree is a <em>rose</em> tree because a node can have any number of children. Nodes without children are called <em>leaf</em> nodes. If all nodes have either zero or two children, the tree is called <em>binary</em> tree .</p><p>A tree can be represented as outline, where indentation expresses the parent-child relationship. Here is the outline corresponding to the tree of our figure:</p><pre>1 Home<br>  2 Important things (according to Cicero)<br>    3 Library<br>    4 Garden<br>      5 Pond<br>      6 Grasses<br>      7 Flowers</pre><pre>                             Figure 2</pre><p>In addition to outlines for essays, as above, trees can be used to represent genealogies, the “tree of life,” which expresses the relationship among species both living and extinct, the file system of a computer, etc.</p><h4>Representing Trees in Elm</h4><p>We will use the package<a href="https://package.elm-lang.org/packages/zwilias/elm-rosetree/latest/"> zwilias/elm-rosetree</a> for our work. Consider a tree whose nodes are of type a. The root of such a tree has a label of type a and has zero, one, two, or many children. We express the node + children nature of trees like this:</p><pre>type Tree a = Tree a (List (Tree a))</pre><p>By way of example, the tree pictured in the Figure 3 below is given by</p><pre>Tree 1 [Tree 2 [Tree 3 [],Tree 4 []]]</pre><p>The root node is labeled by the integer 1; the list of children of this node has just one element, the tree Tree 2 [Tree 3 [], Tree []]. Its root is labeled 2, and its children are given by two-element list with elements Tree 3 [] and Tree 4 []. The latter two nodes are leaves; they have no children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*5m50w5aU_A7qhlKh7tQo6g.png" /><figcaption>Figure 3</figcaption></figure><p>What we would like is a function</p><pre>Build.fromString : node -&gt; (String -&gt; node) -&gt; String -&gt; Result Error (Tree node)<br>forestFromString defaultNode makeNode renderNode str = ...</pre><p>that operates like this:</p><pre>&gt; Build.fromString &quot;?&quot; identity &quot;1\n 2\n  3\n  4&quot;<br>  Ok (Tree &quot;1&quot; [Tree &quot;2&quot; [Tree &quot;3&quot; [],Tree &quot;4&quot; []]])</pre><p>You can find the code for these on <a href="https://github.com/jxxcarlson/elm-tree-builder">GitHub</a>; the code is also published in <a href="https://package.elm-lang.org/packages/jxxcarlson/elm-tree-builder/latest/">jxxcarlson/elm-tree-builder</a> as an <a href="https://elm-lang.org/">Elm</a> package.</p><h4>Blocks</h4><p>To build a tree from an outline, we first transform it into list of blocks, where</p><pre>type alias Block = { indent : Int, content: String }</pre><p>While content is given by a single line, here by a single line, one can also have multi-line blocks. Here we have</p><pre>blocks = [  {indent = 0, content = &quot;1&quot;}<br>          , {indent = 1, content = &quot;2&quot; }<br>          , {indent = 1, content = &quot;3&quot; }<br>          , {indent = 2 , content = &quot;4&quot;}<br>          ]</pre><h4>Zippers</h4><p>To transform the list of blocks into a tree, we use the notion of a <em>zipper</em>, which is a tree with a <em>focus</em>: the subtree which we currently interested in. In module Tree.Zipper of <a href="https://package.elm-lang.org/packages/zwilias/elm-rosetree/latest/"><em>zwilias/elm-rose-tree</em></a> you will find functions for moving the focus, e.g., <em>parent</em> and <em>lastChild</em>. Using Tree and Tree.Zipper, one can rig up a function for attaching a new tree at the focus of a given zipper:</p><pre>attachAtFocus : Tree a -&gt; Zipper a -&gt; Zipper a</pre><p>The function call attachAtFocus t z replaces the subtree of z defined by the focus with the tree t. This function, combined with the moves just mentioned, provide the ingredients for the fromBlocksfunction.</p><p>Now to the heart of the matter. Our goal is to grow the tree beginning with the root, then attach nodes in preorder — 1, 2, 3, … as shown below. Each time we move to a lower level of the tree, we move the focus of the zipper using the lastChild function. Moving down corresponds to an increase in indentation level. No move of focus is needed when we stay at the same level, so no move is needed after attaching node 4 to the tree before we attach node 5. But for node 6, we move up a level, corresponding to a decrease in indentation level. For this we apply the parent function. It can happen that one has to move the focus back several levels.</p><p>You can find the code for building the tree <a href="https://github.com/jxxcarlson/elm-tree-builder/blob/master/src/Tree/Build.elm#L87-L103"><em>right here</em>.</a> We use the kind of functional loop described in <a href="https://jxxcarlson.medium.com/loops-in-functional-languages-63cd104a192a">this article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*PLyqQotTjdSm_yVkjDfVBA.png" /></figure><h4>Rendering and Testing</h4><p>In module Tree.Render one finds the function</p><pre>toString : <strong>Int </strong>-&gt; (<strong>a </strong>-&gt; <strong>String</strong>) -&gt; <strong>Tree a </strong>-&gt; <strong>String<br></strong>toString quantum renderNode tree =</pre><p>where renderNode tells how to convert a label of type a to a string. If a is of type String, the identity function will do. The toString function is useful for testing. Take an outline and use it to build a tree. Convert the tree back into a string. You should end up with the original string. We call this an <em>identity test, </em>since the composite of fromStringand toString quantum renderNode is the identity function.</p><p>To take this a step further, in module Tree.Random, there are functions</p><pre>generateOutline : Int -&gt; Int -&gt; String<strong><br></strong>generateOutline maxEntries seed = ...</pre><p>and</p><pre>generate : Int -&gt; Int -&gt; Result Error (Tree String)<br>generate maxNodes seed = ...</pre><p>which can be used to generate random outlines and random trees. Thus one can run “identity tests” as described above on large numbers of random outlines and trees, e.g., 18.5 seconds for tests of trees with 1000 nodes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75e0dc5da35d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Haskell Microservice]]></title>
            <link>https://jxxcarlson.medium.com/a-haskell-microservice-19c6bf314303?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c6bf314303</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[haskell]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 05:37:04 GMT</pubDate>
            <atom:updated>2021-02-18T13:02:16.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*H6XS8-CaWh0muZWPAhnOvg.jpeg" /></figure><p>The other day I needed a little server app that would receive data as an HTTP request and save it on disk in a specified directory. Each data record consisted of a file path and the the file contents in the form</p><pre>{ fileName: String, contents: String }</pre><p>The request was to be a POST request with url <a href="http://localhost/save">http://localhost:8077/save</a>. There was to be one other endpoint, GET <a href="http://localhost:8077/hello.">http://localhost:8077/hello.</a> The server would respond with “Yes, I am here.” Useful for checking on whether the server was alive. Let’s name this app filingService.</p><p>I had written two other Haskell microservices before, e.g, pdfServer, which receives LaTeX files via POST request, saves the file to disk, converts it to PDF, and replies with a link to the PDF file. Again, a single-purpose program.</p><p>It was a simple matter to reshape the code of pdfServer to make filingService. The reshaping consisted mostly of deleting code, an activity that I’ve come to greatly enjoy. Starting with 171 lines of code in three files, I ended up with 58 lines in two files, Main.hs and Document.hs. Here is the code for the principle function of module Main:</p><pre>main = scotty 8077 $ do<br>   middleware corsPolicy<br>   middleware logStdoutDev</pre><pre>   get &quot;/hello&quot; $ do<br>      html $ mconcat [&quot;Yes, I am still here\n&quot;]</pre><pre>   post &quot;/save&quot; $ do <br>      document &lt;- jsonData :: ActionM Document<br>      liftIO $ Document.write document</pre><pre>   middleware $ staticPolicy (noDots &gt;-&gt; addBase &quot;filingService&quot;)</pre><p>Short, to the point, with a clear statement of the program’s intention. The other module, Document, defines the type of a document and sets forth what one can do with one, namely convert to and from JSON or write it to a file. Just 20 lines of code here, excluding import statements.</p><h4>Simplicity and Clarity</h4><p>What I like best about such programs is their simplicity and clarity. Very short, they do just one thing, and one can easily see how the code relates to the problem solved. The code for filingService, which is on <a href="https://github.com/jxxcarlson/filingService">GitHub</a>, uses the <a href="https://github.com/scotty-web/scotty">Scotty</a> library. Not as sophisticated as Servant, but simpler to use (IMHO) and more than adequate for the task at hand.</p><h4>Note</h4><p>I’ve used both filingService and pdfServer to support <a href="https://elm-lang.org/">Elm</a> apps that I’ve been working on. One of these is <a href="https://minilatex.lamdera.app/">minilatex.lamdera.app</a>, illustrated in the figure below. It is for creating, editing, and distributing LaTeX docs on the web. Real time rendering! Give it a try and let me know if it works for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G05CKInxFORsDm5ajv_2og.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c6bf314303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parser Tooling]]></title>
            <link>https://jxxcarlson.medium.com/parser-tooling-600b82be643b?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/600b82be643b</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[parser]]></category>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 03:34:23 GMT</pubDate>
            <atom:updated>2020-12-22T03:42:51.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qc73XzcgAMxNwSFipBc0Wg.png" /><figcaption>Parser Tool: Screenshot</figcaption></figure><p>For a while now, I’ve been working on a variant/subset of LaTeX which I call MiniLaTeX. The idea is to be able write MiniLaTeX documents in the browser and also to have them rendered there … indeed, to have them rendered in real-time as the user types. Good for writing <a href="https://minilatex.lamdera.app/g/35">class notes</a>, problem sets, etc. You can see MiniLaTeX in action</p><ul><li>here, in a <a href="https://demo.minilatex.app/">little demo app</a></li><li>and here, in a more capable <a href="https://minilatex.lamdera.app/">document-management app</a></li></ul><p>Both apps are written in <a href="https://elm-lang.org/">Elm</a>, with the second also using <a href="https://dashboard.lamdera.app/">Lamdera</a>, a technology which enables one to write both the front- and backend in Elm, with the two communicating via websockets (read that last word as <strong>fast</strong>).</p><p>As I’ve begun to devote more attention to expanding the scope of MinLaTeX, I realized that I needed a convenient tool for testing changes to the compiler. The compiler can be thought of as the composition of two functions, one of which consumes MiniLaTeX source text and produces a syntax tree, the other which consumes syntax trees and produces HTML, with formulas rendered by either <a href="https://mathjax.org/">MathJax</a> or <a href="https://katex.org/">KaTeX</a>. The Parser Tool you see in the figure above responds to this need. Enter MiniLaTeX source text in the top left pane and press “Parse.” The syntax tree in “raw” form is displayed in the middle left panel and the rendered text is displayed in the bottom left one.</p><p>The fun part is the graphical representation of the tree which you see on the right. It is an SVG image constructed using the library <a href="https://package.elm-lang.org/packages/alex-tan/elm-tree-diagram/latest/">alex-tan/elm-tree-diagram</a>. There is only one non-trivial step, which is in fact quite easy to carry out. This is implementing a function</p><pre>transform : <strong>LaTeXExpression </strong>-&gt; <strong>Tree String</strong></pre><p>which consumes a syntax tree and produces a tree whose nodes are labeled by strings. The latter is the kind of tree that <a href="https://package.elm-lang.org/packages/alex-tan/elm-tree-diagram/latest/">alex-tan/elm-tree-diagram</a> can further transform into an SVG image. The transform function looks like what you see below. At top level, it is a case analysis of the variants which make up aLaTeXExpression, the type of the syntax tree. The first three cases handle terminal nodes, whereas the next two handle non-terminal nodes using recursive calls to transform.</p><pre>transform : <strong>LatexExpression </strong>-&gt; <strong>Tree String<br></strong>transform expr =<br>    case expr of<br>        LXString str -&gt; TreeDiagram.node (&quot;S: &quot; ++ str) []<br>        InlineMath str -&gt; TreeDiagram.node (&quot;M1: &quot; ++ str) []<br>        DisplayMath str -&gt; TreeDiagram.node (&quot;M2: &quot; ++ str) []<br>        Macro name args optargs -&gt;<br>          TreeDiagram.node (&quot;MA: &quot; ++ name)<br>          [<br>               TreeDiagram.node &quot;args&quot; (List.map transform optargs)<br>             , TreeDiagram.node &quot;optargs&quot; (List.map transform args)<br><br>          ]<br>        LatexList list -&gt; <br>          TreeDiagram.node &quot;LaTeXList&quot; (List.map transform list)<br>        ...</pre><p>That is it — quite simple!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=600b82be643b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LaTeX in the Browser]]></title>
            <link>https://jxxcarlson.medium.com/latex-in-the-browser-92416920850a?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/92416920850a</guid>
            <category><![CDATA[tex]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Fri, 06 Nov 2020 09:38:10 GMT</pubDate>
            <atom:updated>2020-11-06T22:33:24.248Z</atom:updated>
            <content:encoded><![CDATA[<p>I’d like to announce the Alpha4 Release of <a href="https://minilatex.lamdera.app/"><strong>minilatex.lamdera.app</strong></a>, an app for doing LaTeX in the browser—a great way to <a href="https://minilatex.lamdera.app/g/78">publish class notes,</a> problem sets, etc., along with many other uses.</p><p>I’ve used the app a good deal myself, but now, to make it fulfill its purpose, I need feedback from real users. The app has a chat feature (<strong>Chat</strong> button, lower right, see screen shot at end). You can use the chat to report bugs, make suggestions, and ask questions. And yes, you can write equations in LaTeX in the chat!</p><p><strong>Some features</strong></p><ul><li><strong>No setup.</strong> Just start typing and see LaTeX rendered before your eyes.</li><li><strong>Fast.</strong> To say instantaneous would be to violate Einstein’s Theory of Relativity, but rendering documents is almost that fast.</li><li><strong>Collaborate</strong>. You can share both reading and editing with one or more people.</li><li><strong>Work anywhere</strong> you have an internet connection and a web browser.</li><li><strong>Share</strong>. Press the “public” button and your document is accessible to all. Email links to students. Or make a home page on the app and post links there.</li><li><strong>Export</strong> to a standard LaTeX file ready to use with pdflatex. Or export to PDF.</li></ul><p><strong>Getting started</strong></p><ul><li>Sign up at <a href="https://minilatex.lamdera.app/"><strong>minilatex.lamdera.app</strong></a></li><li>Press control-N or the <strong>New</strong> button to create a document, then start typing.</li><li>Note that documents are saved automatically, roughly twice per second.</li></ul><p>If you are new to LaTeX, try the <a href="https://minilatex.lamdera.app/g/273">Learning LaTeX</a> tutorial. Below is a screenshot of some physics class notes. Note that (as in the screenshot) one can make a “book” with table of contents, chapters, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2Jf6a28Iry5m8bC6if73w.png" /><figcaption>minilatex.lamdera.app</figcaption></figure><p>More features coming soon.</p><p><strong>Technical note.</strong> The app is written in <a href="https://elm-lang.org/">Elm</a> and uses <a href="https://dashboard.lamdera.app/">Lamdera</a>, an integrated all-Elm front-to-backend solution. The app can also render Math-Markdown: like Markdown, but you can do the usual TeX-LaTeX thing with formulas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92416920850a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Typed Lisp in Elm]]></title>
            <link>https://jxxcarlson.medium.com/a-typed-lisp-in-elm-e5c733f63931?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c733f63931</guid>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[parser]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Fri, 04 Sep 2020 16:17:23 GMT</pubDate>
            <atom:updated>2020-09-05T14:47:31.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH4MiwVc9v64tdTcda0ffA.png" /><figcaption>by XKCD</figcaption></figure><p>As a fun exercise, I decided to try to make a Lisp using <a href="https://elm-lang.org/">Elm</a> … not the whole deal, of course, but just a little piece to see what is possible and how one would do it. The result, which I will describe here, is <a href="https://github.com/jxxcarlson/elm-lisp">a skeleton of a very small typed Lisp</a>. Of course Lisp itself doesn’t have types, so this is a different beast. In any case, one needs to construct two functions, parse and eval. Here is how the parser works:</p><pre>&gt; parse &quot;(+ 1 2)&quot;<br>Just (LIST [Str &quot;+&quot;,Num 1,Num 2])<br>    : Maybe AST</pre><p>And here is eval:</p><pre>&gt; eval &quot;(+ 1 2)&quot;<br>VNum 3 : Value</pre><p>Note that nonsense inputs produce the value Undefined:</p><pre>&gt; eval &quot;(+ 1 a)&quot;<br>Undefined : Value</pre><p>You can find the code for all of this on <a href="https://github.com/jxxcarlson/elm-lisp">GitHub</a>.</p><h4>Constructing the Parse Function</h4><p>The first step in constructing the parse function is to define the type of the abstract syntax tree (AST):</p><pre>type AST<br>    = Str String<br>    | Num Int<br>    | LIST (List AST)</pre><p>Thus, in this little Lisp, there are two primitive types, one for strings, one for integers. The type is recursive, so lists can be nested within lists:</p><pre>&gt; parse &quot;(1 2 (3 4))&quot;<br>Just (LIST [Num 1,Num 2,LIST [Num 3,Num 4]])</pre><p>The top-level parser, which is built out of combinators using the <a href="https://package.elm-lang.org/packages/elm/parser/latest/">elm/parser library</a>, is a one-liner:</p><pre>parser : Parser AST<br>parser =<br>    oneOf [ lazy (\_ -&gt; list), string, integer ]</pre><p>TheoneOf combinator chooses among the alternative parsers, list, string, and integer : one parser for each part of the definition of the AST type. The lazy phrase is needed for recursion to work.</p><p>The list parser is defined this way, out of the sequencing combinators (|.) and (|=):</p><pre>list : Parser AST<br>list =<br>    (succeed identity<br>        |. symbol &quot;(&quot;<br>        |. spaces<br>        |= many parser<br>        |. spaces<br>        |. symbol &quot;)&quot;<br>        |. spaces<br>    )<br>        |&gt; map LIST</pre><p>The resulting parser pipeline works by first recognizing a left parenthesis, then spaces, if any. The many combinator is then applied to the top-level parser so as to run it as many times as necessary to consume the input. Finally, the pipeline, taking care of whitespace as needed, recognizes the final trailing parenthesis.</p><p>In more detail, the combinator (|.) says “ignore the result of running the following parser,” while the combinator (|=) says “keep the result of running the following parser.” The output of the pipeline is fed as a bunch of arguments into succeed whatever, where whatever is a function that can accept those arguments. In the case at hand, there is just one argument, and the function used is the identity function. If running the pipeline is successful, its output is piped into the function LIST so that the type of the output is AST. That’s it!</p><p>For more details on construction of the parser, please, please see the <a href="https://github.com/jxxcarlson/elm-lisp/blob/master/src/Parse.elm">GitHub repo</a>.</p><h4>Constructing the Eval Function</h4><p>First, the type, which is eval : String -&gt; Value . Recall that we will be doing things like the below:</p><pre>&gt; eval &quot;(+ 1 2)&quot;<br>VNum 3 : Maybe Lisp.Value</pre><pre>&gt; eval &quot;(if (&gt; 4 1) bigger smaller)&quot;<br>Just (VStr &quot;bigger&quot;) : Maybe Lisp.Value</pre><p>Thus the Value type enumerates the kind of values that eval can produce:</p><pre>type Value<br>    = VStr String<br>    | VNum Int<br>    | VList (List Value)<br>    | Undefined<br>    | ParseError</pre><p>The first two take care of primitive types — strings, and integers. The next one takes care of lists of values, while the last two deal with errors. Undefined is the value of an expression that was correctly parsed but which cannot be evaluated, as in eval (+ 1 a). Undefined can occur as a value because our Lisp, while it has types, does not do much in the way of type checking.</p><p>The eval function is essentially the composite of parse : String -&gt; AST and evalAst: AST -&gt; Value, as in the below:</p><pre>eval : String -&gt; Value<br>eval str =<br>    case str |&gt; parse |&gt; Maybe.map evalAst of<br>        Just val -&gt;<br>            val</pre><pre>        Nothing -&gt;<br>            ParseError</pre><p>The eval function itself is implemented as a huge case statement, which in outline form looks like this:</p><pre>evalAst : AST -&gt; Value<br>evalAst ast =<br>    case ast of<br>        Num k -&gt;<br>            VNum k</pre><pre>        Str s -&gt;<br>            VStr s</pre><pre>        LIST list -&gt;<br>            case List.head list of<br>                Just (Str &quot;+&quot;) -&gt;<br>                   code to handle addition</pre><pre>                Just (Str &quot;-&quot;) -&gt;<br>                    code to handle subtraction</pre><pre>                ...</pre><pre>                _ -&gt;<br>                    List.map evalAst list |&gt; VList</pre><p>As an example of how we might handle addition, we could say this:</p><pre>Maybe.map2 (-) (getNumArg 1 list) (getNumArg 2 list) |&gt; wrapVNum</pre><p>The getNumArg function grabs a value form the given position in list and unwraps it, converting, say Num 5 into Just 5 . In this way the arguments are prepared for the standard (+) function, except that we have to apply Maybe.map2 because the values are now wrapped as Maybe values. Note that if the argument in position 1 were Str &quot;haha!&quot;, then getNumArg 1 would return Nothing, as would Maybe.map2. If successful, the Maybe.map2 call produces Just someInteger. In accord with the type signature of evalAst, it must be converted to something of type Value, which is what wrapVNum does. You can find the code for all these details in <a href="https://github.com/jxxcarlson/elm-lisp/blob/master/src/Lisp.elm">Lisp.elm on GitHub</a>.</p><p>I’ve kept the code for Lisp.elm as simple as possible, so the eval function defined there does very little. Slightly more capable is List2.elm, which features things like the below:</p><pre>&gt; eval &quot;(if (&gt; 4 2) bigger smaller)&quot;<br>Just (VStr &quot;bigger&quot;) : Maybe Lisp2.Value</pre><pre>&gt; eval &quot;(element 2 red green blue white black)&quot;<br>Just (VStr &quot;blue&quot;) : Maybe Lisp2.Value</pre><pre>&gt; eval &quot;(a b 1 2)&quot;<br>Just (VList [VStr &quot;a&quot;,VStr &quot;b&quot;,VNum 1,VNum 2])</pre><h4>Comments</h4><p>In a future post, I’ll discuss some other ways of writing a small Lisp in Elm. The present approach has the advantage of simplicity, but the disadvantage of inflexibility: the kinds of things that can be evaluated are hardcoded into the design.</p><p>I wish to thank Andrew Thompson for comments on a draft of this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c733f63931" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Elm as a Blackbox]]></title>
            <link>https://jxxcarlson.medium.com/running-elm-as-a-blackbox-b1930592054b?source=rss-5de01b007190------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1930592054b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[headless]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[elm-lang]]></category>
            <dc:creator><![CDATA[James Carlson]]></dc:creator>
            <pubDate>Sat, 23 May 2020 18:02:17 GMT</pubDate>
            <atom:updated>2020-05-23T18:16:09.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EX5MngY5EUpr_7fpeFG2Fw.jpeg" /></figure><p>The functional programming language <a href="https://elm-lang.org/">Elm</a> is best known for writing web apps. You can also use Elm to write a headless “black box” app that you talk to via the terminal. Here is a sample session:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*NZ1o_H8Ks7nVmOQJI0LxfQ.png" /></figure><p>Start the program with the command elm-bb, then type your own commands. In this example, the commands are integers which the black box factors into primes. The set-up I will describe here has the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*royWh-UA7Mfg7omgmk5-Qg.jpeg" /></figure><p>On the left is the terminal, where you type your commands. Next is a 29-line Javascript program that talks to both the terminal and Main.elm. Main.elm imports a module Blackbox that exposes a function</p><pre>   transform : String -&gt; String</pre><p>When Main.elm receives a string input from the terminal, it computes output = transform input and sends this string back to the terminal. Thus, to change the behavior of the system, it suffices to change the black box. In the example above, we installed the black box using</p><pre>    import Factor as Blackbox</pre><p>in Main.elm. To do statistics instead of factoring integers, we would say</p><pre>    import Statistics as Blackbox</pre><p>then recompile. Here is a session that results from this change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8Wf6xlummMZPwmrLMO_9g.png" /></figure><p>There is also a :help command, whose text is defined by helpString in whatever black box module you import. And here is is the help screen that one includes with most black box apps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JONwv70hKgXgVxDzp5Au-g.png" /></figure><p>Note that there are a number of operations for working with files. These are defined in Main.elm, and so are available to any black box app. The command :get FILE loads a file and stores it in memory. The command :calc applies transform to the contents of memory. This command can take arguments. Thus :calc col=5 calculates statistics for column 5 of the data stored in memory, while :calc col=5 rows=100:200 does the same, but only for rows 100 through 200. You can also bypass file operations entirely, applying transform directly to data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*lLKO2G7DgObQPsXRGUSI4Q.png" /></figure><p>The code for all this is on <a href="https://github.com/jxxcarlson/elm-blackbox">GitHub</a>. Just clone it, import the black box of your choice (or better, write your own). Compile with sh make.sh Link to the global command elm-bb with</p><pre>    ln -s PATH_TO/src/repl.js /usr/local/bin/elm-bb</pre><p>where of course you have to set PATH_TO. That is all there is to it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1930592054b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>