<?xml version='1.0' encoding='UTF-8'?>
<rss version='2.0' xmlns:atom='http://www.w3.org/2005/Atom'>
<channel>
<atom:link href='https://www.rooijakkers.software' rel='self' type='application/rss+xml'/>
<title>
Rooijakkers Software
</title>
<link>
https://www.rooijakkers.software
</link>
<description>
Programming and life
</description>
<lastBuildDate>
Sat, 11 Apr 2026 22:46:19 +0200
</lastBuildDate>
<generator>
clj-rss
</generator>
<item>
<guid>
https://www.rooijakkers.software/posts/2024-06-09-quote-of-the-week/
</guid>
<link>
https://www.rooijakkers.software/posts/2024-06-09-quote-of-the-week/
</link>
<title>
Quote of the week #3
</title>
<description>
&lt;p&gt;The Buddha in &lt;a href='https://photodharma.net/Posters/Dhammapada-08-14/images/Dhammapada-183-185-Original.jpg'&gt;&lt;em&gt;Dhammapada&lt;/em&gt;&lt;/a&gt; on debugging.&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt; Patient endurance is the supreme practice for freeing the heart from unwholesome states.&lt;br&gt; &amp;ndash; The Buddha &lt;/p&gt;&lt;/blockquote&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Sun, 09 Jun 2024 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2023-11-06-kijkje-in-de-keuken-van-team-clojure/
</guid>
<link>
https://www.rooijakkers.software/posts/2023-11-06-kijkje-in-de-keuken-van-team-clojure/
</link>
<title>
Een kijkje in de keuken van team Clojure
</title>
<description>
&lt;p&gt;Bij Mediquest zijn er twee DevOps-teams: team DBA, vernoemd naar het administreren van databases; en team Clojure, vernoemd naar het programmeren met Clojure. In deze blogpost belichten we het programmeren met Clojure.&lt;/p&gt;&lt;p&gt;Mediquest is één van de ongeveer twintig bedrijven in Nederland die werken met deze programmeertaal. Waarom Clojure? Wat is het? Hoe is het om ermee te werken? Onze collega Erwin is softwareontwikkelaar in team Clojure en neemt ons mee.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;waarom&amp;#95;kiest&amp;#95;mediquest&amp;#95;voor&amp;#95;clojure?&quot;&gt;&lt;/a&gt;Waarom kiest Mediquest voor Clojure?&lt;/h2&gt;&lt;p&gt;Software begint bij code. In het algemeen geldt: hoe minder code hoe minder fouten. Clojure is een taal die ontwikkelaars in staat stelt om met relatief weinig code veel uit te drukken. Clojure-code beschrijft de essentiële complexiteit, inherent aan het op te lossen probleem, terwijl de onnodige complexiteit (de technologische overhead) wordt beperkt tot een minimum. &lt;/p&gt;&lt;p&gt;Met Clojure kan je op veel plaatsen minder code schrijven: in browsers met ClojureScript, op servers via Clojure en ClojureCLR tot scripting op besturingssystemen via de Clojure-variant Babashka. Zo schrijf je van voor- tot achterkant in dezelfde taal.&lt;/p&gt;&lt;p&gt;Deze uitdrukkingskracht en dit bereik stelt Clojure-teams in staat om met een relatief klein ontwikkelteam veel software te beheren.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;wat&amp;#95;ontwikkelt&amp;#95;mediquest&amp;#95;zoal&amp;#95;in&amp;#95;clojure?&quot;&gt;&lt;/a&gt;Wat ontwikkelt Mediquest zoal in Clojure?&lt;/h2&gt;&lt;p&gt;Clojure is tien jaar geleden in Mediquest geïntroduceerd door oud-collega Cees van Kemenade die een low-code platform maakte genaamd de ‘Business Process Engine’. Met dit platform kunnen procesflows (e.g. als deze data wordt aangeleverd, doe dan deze controles, verstuur deze e-mails, sla het hier versleuteld op) visueel worden gedefinieerd. Die plaatjes leiden tot uitvoerbare code. Zo kunnen mensen met weinig programmeerervaring processen programmeren. Sommige van die flows draaien nog steeds, maar vanaf vijf jaar geleden kwamen er in Mediquest meer Clojure-ontwikkelaars, ontstond team Clojure en verschoof de aandacht naar ontwikkeling van het portaal.&lt;/p&gt;&lt;p&gt;Dankzij Clojure biedt Mediquest nu een portaal vol applicaties met componenten (gecertificeerd op gebied van &lt;a href='https://home.mediquest.nl/over-ons/kwaliteit-privacy/'&gt;kwaliteit en privacy&lt;/a&gt;) voor dashboards, voor het maken en distribueren van vragenlijsten en om bestanden te uploaden en downloaden. Elk van deze bouwstenen kan worden geconfigureerd om aan specifieke klantwensen te voldoen. Zo wordt het portaal ingezet voor onder meer &lt;a href='https://home.mediquest.nl/onze-oplossingen/positieve-gezondheid'&gt;Mijn Positieve Gezondheid&lt;/a&gt;, &lt;a href='https://youtu.be/C3VRnnDv-9M'&gt;mijnPerined&lt;/a&gt; en &lt;a href='https://home.mediquest.nl/onze-oplossingen/ervaringen-meten/'&gt;PREM&lt;/a&gt;.&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt; ‘Volgens mij worden sinds Clojure dingen sneller ontwikkeld.’ – Corine Horsch, Data Scientist (team Datalab) &lt;/p&gt;&lt;/blockquote&gt;&lt;h2&gt;&lt;a name=&quot;wat&amp;#95;is&amp;#95;het&amp;#95;verhaal&amp;#95;achter&amp;#95;de&amp;#95;haakjes?&quot;&gt;&lt;/a&gt;Wat is het verhaal achter de haakjes?&lt;/h2&gt;&lt;p&gt;Een uniek kenmerk van Clojure (of beter gezegd van de programmeertaal Lisp, waar Clojure een variant van is) zijn de ‘verkeerd geplaatste’ haakjes. Waar andere programmeertalen vaak lezen als &lt;code&gt;doSomething&amp;#40;1, 2&amp;#41;&lt;/code&gt; lees je in Clojure &lt;code&gt;&amp;#40;do-something 1 2&amp;#41;&lt;/code&gt;. Ja, zeker voor programmeurs, is dat even schrikken. Maar gelukkig, deze haakjes tezamen met de syntax voor lijsten &lt;code&gt;‘&amp;#40;&amp;#41;&lt;/code&gt;, &lt;code&gt;&amp;#91;&amp;#93;&lt;/code&gt; voor reeksen, &lt;code&gt;#{}&lt;/code&gt; voor sets en &lt;code&gt;{}&lt;/code&gt; voor dictionaries vormen tachtig procent van de Clojure-regels.&lt;/p&gt;&lt;p&gt;Met die haakjes is Clojure-code zelf ook een datastructuur in Clojure, namelijk een lijst. Daarom &lt;a href='https://youtu.be/oGkCwSdZBds?t=93'&gt;noemen Clojure-programmeurs code ook wel data&lt;/a&gt;. Dit maakt het mogelijk voor programmeurs om code te schrijven die code aanpast. En zo als het ware een eigen programmeertaal binnen Clojure te ontwikkelen, die specifiek aansluit op het domein. (Mocht je als programmeur deze zogenaamde macro’s beter willen begrijpen, de blogpost &lt;a href='https://www.defmacro.org/ramblings/lisp.html'&gt;&lt;i&gt;The Nature of Lisp&lt;/i&gt;&lt;/a&gt; legt het uitgebreid uit.) Zo is een groot deel van de expressiviteit en kracht van Clojure dankzij deze onconventionele haakjesplaatsing.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://imgs.xkcd.com/comics/lisp_cycles.png&quot; alt=&quot;xkcd I've just received word that the Emperor has dissolved the MIT computer science program permanently.&quot;/&gt; &lt;/p&gt;&lt;p&gt;_Bron: &lt;a href='https://xkcd.com/297/'&gt;xkcd_&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;dus&amp;#95;jullie&amp;#95;hebben&amp;#95;nooit&amp;#95;bugs?&quot;&gt;&lt;/a&gt;Dus jullie hebben nooit bugs?&lt;/h2&gt;&lt;p&gt;Uiteraard kun je ook in Clojure complexe en moeilijk te onderhouden code schrijven. Echter, de taal is zo ontworpen dat dit wordt ontmoedigd. De meeste programmeerproblemen kunnen uiteindelijk worden uitgedrukt met die paar eerder genoemde basisdatastructuren zoals lijsten, sets en dictionaries, en Clojure blinkt uit in het hanteren van deze datastructuren. &lt;/p&gt;&lt;blockquote&gt;&lt;p&gt; ‘Het is beter om honderd functies te hebben die opereren op één data-abstractie, dan tien functies op tien datastructuren.’ – &lt;a href='https://youtu.be/cPNkH-7PRTk?t=2244'&gt;Rich Hickey&lt;/a&gt;, maker van Clojure (in navolging van computerwetenschapper Alan Perlis) &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;De datastructuren zijn namelijk onveranderlijk (dit maakt het makkelijk erover te redeneren), mocht je parallel code willen aanspreken zijn daar faciliteiten voor en er zijn allerlei functies die opereren op al deze lijsten, sets en dictionaries (en ook de datastructuren van het hostplatform), omdat die alle de zogenaamde sequence-interface implementeren. Dit voorkomt een hoop bugs veroorzaakt door een taal zelf.&lt;/p&gt;&lt;p&gt;Bugs die optreden komen meestal voort uit fouten in het ontwerp zelf (de essentiële complexiteit), en niet dankzij programmeerfouten door de taal (onnodige complexiteit).&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;en&amp;#95;verder?&quot;&gt;&lt;/a&gt;En verder?&lt;/h3&gt;&lt;p&gt;Een groot deel van wat Clojure zo prettig maakt om mee te werken komt door de haakjes aan de buitenkant: je hebt als ontwikkelaar toegang tot draaiende code via een REPL; je kan vragen stellen aan draaiende code en deze wijzigen, en je kan Clojure op eenvoudige wijze uitbreiden met nieuwe concepten.&lt;/p&gt;&lt;p&gt;De haakjes wennen overigens wel, voor nieuwe Clojure-programmeurs is vaak het werken met onveranderlijke datastructuren (het zogenoemde functioneel programmeren) het lastigst om te leren. Hoewel er meer programmeertalen de functionele kant op zijn gegaan de afgelopen jaren.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;kortom?&quot;&gt;&lt;/a&gt;Kortom?&lt;/h3&gt;&lt;p&gt;Goed, ik denk dat het Clojure-evangelie nu genoeg is verkondigd. Al met al is het als ontwikkelaar prettig werken met Clojure vanwege de robuuste datastructuren, dezelfde code kunnen schrijven op voor- en achterkant, het gemak van redeneren en de krachtige abstractiemogelijkheden. Clojure speelt een essentiële rol bij het tijdig opleveren van kwalitatief hoogstaande software bij Mediquest.&lt;/p&gt;&lt;p&gt;Erwin – softwareontwikkelaar team Clojure&lt;/p&gt;&lt;p&gt;Deze blog verscheen eerst op de Mediquest-website. Zie &lt;a href='https://home.mediquest.nl/een-kijkje-in-de-keuken-van-team-clojure/'&gt;https://home.mediquest.nl/een-kijkje-in-de-keuken-van-team-clojure/&lt;/a&gt;.&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Mon, 06 Nov 2023 00:00:00 +0100
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2018-09-08-gdpr---compliant-sharing-of-smart-meter-data-on-the-iota-tangle/
</guid>
<link>
https://www.rooijakkers.software/posts/2018-09-08-gdpr---compliant-sharing-of-smart-meter-data-on-the-iota-tangle/
</link>
<title>
GDPR-compliant smart meter data on the IOTA Tangle — four lessons learned while putting the consumer in control
</title>
<description>
&lt;p&gt;This blog post &lt;a href='https://medium.com/@erwinrooijakkers/gdpr-compliant-smart-meter-data-on-the-iota-tangle-four-lessons-learned-while-putting-the-dea852a5b2aa'&gt;originally appeared on Medium&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*mbDe-SwRCyGF_OSD0U-SSA.jpeg&quot; width=&quot;100%&quot; alt=&quot;Smart meter&quot;&gt;&lt;/img&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;TL;DR: We created a proof of concept where smart meter data is obtained via a Raspberry Pi and published via IOTA Masked Authenticated Messaging. A consumer can proof he owns the Raspberry Pi, and the consumer can give and revoke consent to service providers to access the smart meter measurements for a specific goal. All on the IOTA Tangle.&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;a href='https://www.alliander.com'&gt;Alliander&lt;/a&gt; is a Dutch energy grid operator that ensures 6 million citizens have access to energy. At Alliander R&amp;D we research technologies that will improve our infrastructure and lead to a more sustainable future.&lt;/p&gt;&lt;p&gt;Sharing &lt;a href='https://en.wikipedia.org/wiki/Smart_meter'&gt;smart meter&lt;/a&gt; data with service providers can help the energy transition. For example, in the UK energy usage was reduced after providing citizens an app with usage insights connected their smart meter. If anyone can access energy usage data it can help balance the grid and more.&lt;/p&gt;&lt;p&gt;At the same time smart meter data is &lt;strong&gt;privacy-sensitive&lt;/strong&gt;. Power consumption can be associated with appliances used and with measurements every 0.5 seconds it is possible &lt;a href='https://www.nds.rub.de/media/nds/veroeffentlichungen/2012/07/24/ike2012.pdf'&gt;to see what television channel is being watched&lt;/a&gt;!&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*gTOCPmIvTdRnRzGnAhLMfg.png&quot; width=&quot;100%&quot; alt=&quot;Power patterns&quot;&gt;&lt;/img&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;Power consumption peaks can be associated with individual appliances. (Source: &lt;a href='https://www.splunk.com/blog/2011/05/27/smart-grid-data-the-wild-west-of-privacy-rights.html'&gt;Privacy Issues Related to Smart Grid Technologies, Megan J. Hertzler&lt;/a&gt;)&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;p&gt;You can ponder if we should care about privacy in the face of the &lt;a href='https://www.ipcc.ch/report/ar5/wg2/'&gt;slow-moving climate change apocalypse&lt;/a&gt;. But it's the law. Energy usage data cannot be legally shared without adhering to it.&lt;/p&gt;&lt;p&gt;The &lt;a href='https://ec.europa.eu/commission/priorities/justice-and-fundamental-rights/data-protection/2018-reform-eu-data-protection-rules_en'&gt;General Data Protection Regulation&lt;/a&gt; (GDPR) came into effect May 25. It provides data and privacy protection for European citizens. When dealing with personal identifiable information (like the measurements of a smart meter) a service provider has to:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;State the goal for data usage clearly (and only use the data for that goal)&lt;/li&gt;&lt;li&gt;Have consent of the consumer to access the data&lt;/li&gt;&lt;li&gt;Stop collecting data when consent is revoked&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;(Ignoring other parts of the GDPR that cannot be encoded in software, but that need to be enforced juridically, like right of erasure).&lt;/p&gt;&lt;p&gt;So, for open usage of smart meter measurements a solution needs to be provided that adheres to the requirements of the GDPR. Two goals of this solution are:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Energy data goes &lt;strong&gt;directly&lt;/strong&gt; from the smart meter to the service provider.&lt;/li&gt;&lt;li&gt;Consent (authorizations to access data) are stored &lt;strong&gt;decentrally&lt;/strong&gt;.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;When data or consent is stored centrally, for example in a cloud, there are privacy concerns. A cloud is a &lt;a href='https://www.theregister.co.uk/2016/03/23/npm_left_pad_chaos/'&gt;&lt;strong&gt;single point of failure&lt;/strong&gt;&lt;/a&gt; (what if consent is irrevocable because a server is down?), that is susceptible to &lt;a href='https://translate.google.com/translate?sl=nl&amp;tl=en&amp;js=y&amp;prev=_t&amp;hl=nl&amp;ie=UTF-8&amp;u=https%3A%2F%2Fnos.nl%2Fartikel%2F2131879-energiedata-twee-miljoen-nederlandse-huishoudens-gestolen.html'&gt;&lt;strong&gt;misuse&lt;/strong&gt;&lt;/a&gt; and &lt;a href='https://www.independent.ie/irish-news/news/exclusive-eirgrid-targeted-by-state-sponsored-hackers-leaving-networks-exposed-to-devious-attack-36003502.html'&gt;&lt;strong&gt;hacks&lt;/strong&gt;&lt;/a&gt;. Central storage can also lead to &lt;strong&gt;vendor lock in&lt;/strong&gt;, where the owner of the smart meter data reader determines what service providers can use the data, instead of creating a level playing field where you can authorize anyone to access the data. Distributed ledger technology could address these issues.&lt;/p&gt;&lt;p&gt;Dutch Smart meters have a P1 port which gives consumers access to real time measurements with a high resolution. We investigated how distributed ledger technology can be used to provide open access to P1 energy measurements where the consumer is in control. Because it scales and has no transaction fees (who wants to pay to give consent?) we use the &lt;a href='https://www.iota.org/'&gt;IOTA Tangle&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*OT7i8GL4GguH5JQYsfRxoA.png&quot; alt=&quot;Smart Meter with Raspberry Pi&quot; style=&quot;width: 50%&quot;/&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;A Raspberry Pi running IOTA interfacing software connected via a P1 cable (USB to RJ11) to a Dutch smart meter&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;p&gt;IOTA aims to be the backbone for the Internet of Things whereby devices can communicate and transact with each other. E.g., your washing machine buys energy from the solar panels of the neighbours while your self-driving car is instructed to pick up your kids. To read more about IOTA Tangle see &lt;a href='https://blog.iota.org/the-tangle-an-illustrated-introduction-4d5eae6fe8d4'&gt;The Tangle: an Illustrated Introduction&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;!&amp;ndash; &lt;img src=&quot;https://steemitimages.com/0x0/https://steemitimages.com/DQmc5Hzg5kij71mJ5kq79eAqQv6qQJK7gQJ6fAoDsKx28rX/iotanglerrrr.gif&quot; alt=&quot;IOTA Tangle visualization&quot; /&gt; &amp;ndash;&gt;&lt;/p&gt;&lt;p&gt;&lt;!&amp;ndash; &lt;sub&gt;&lt;em&gt;Every data or value transaction on the IOTA Tangle must validate two earlier transactions by solving a cryptographical puzzle that takes computing power (proof of work). This way all nodes agree with each other on the state of the Tangle. For more information on how IOTA works see &lt;a href='https://blog.iota.org/the-tangle-an-illustrated-introduction-4d5eae6fe8d4'&gt;The Tangle: an Illustrated Introduction&lt;/a&gt;. (&lt;a href='https://steemit.com/iota/@steemhoops99/in-tangle-we-trust-10-amazing-facts-about-iota-1000000-token-giveaway-faucet'&gt;Image source&lt;/a&gt;)&lt;/em&gt;&lt;/sub&gt; &amp;ndash;&gt;&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;now&amp;#95;follow&amp;#95;four&amp;#95;lessons&amp;#95;we&amp;#95;learned&amp;#95;implementing&amp;#95;gdpr-compliant&amp;#95;energy&amp;#95;data&amp;#95;streams&amp;#95;on&amp;#95;the&amp;#95;iota&amp;#95;tangle&quot;&gt;&lt;/a&gt;Now follow four lessons we learned implementing GDPR-compliant energy data streams on the IOTA Tangle&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='#the-difficulty-in-providing-access-is-handing-out-the-keys'&gt;The difficulty in providing access is handing out the keys.&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#encryption-is-needed'&gt;Encryption is needed when sharing keys.&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#mam-channels-can-be-used-as-decentralized-storage-of-consent-in-an-encrypted-immutable-event-log-but-you-now-have-an-encrypted-immutable-event-log'&gt;MAM channels can be used as decentralized storage of consent with an encrypted immutable event log, but... you now have an encrypted immutable event log.&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#mam-proof-of-work-is-too-slow-for-smart-meter-measurements-on-standard-hardware'&gt;Masked Authenticated Messaging on standard hardware is unsuited for smart meter measurements.&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*3JpMk706DUg_QlXB1QVweQ.png&quot; alt=&quot;Components&quot; width=&quot;100%&quot; /&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;Component diagram&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;the&amp;#95;difficulty&amp;#95;in&amp;#95;providing&amp;#95;access&amp;#95;is&amp;#95;handing&amp;#95;out&amp;#95;the&amp;#95;keys&quot;&gt;&lt;/a&gt;The difficulty in providing access is handing out the keys&lt;/h3&gt;&lt;p&gt;&lt;a href='https://blog.iota.org/introducing-masked-authenticated-messaging-e55c1822d50e'&gt;IOTA Masked Authenticated Messaging&lt;/a&gt; (MAM) is a feature of the IOTA Tangle that allows to publish and fetch encrypted messages. In &lt;em&gt;restricted mode&lt;/em&gt; both the address of a data stream as well as a side key (with which the data is encrypted) needs to be known to read and decrypt the data. MAM can be used for data integrity and access control.&lt;/p&gt;&lt;p&gt;When I first heard about MAM I thought that it would solve all GDPR issues. Then we stumbled upon the problem of exchanging keys...&lt;/p&gt;&lt;h4&gt;&lt;a name=&quot;an&amp;#95;authorized&amp;#95;service&amp;#95;provider&amp;#95;needs&amp;#95;to&amp;#95;receive&amp;#95;the&amp;#95;root&amp;#95;and&amp;#95;side&amp;#95;key&amp;#95;of&amp;#95;restricted&amp;#95;mam&amp;#95;channel&amp;#95;(key&amp;#95;exchange)&quot;&gt;&lt;/a&gt;An authorized service provider needs to receive the root and side key of restricted MAM channel (key exchange)&lt;/h4&gt;&lt;p&gt;After you have paired with the Raspberry Pi (see &lt;a href='https://github.com/Alliander/decentralized-auth/blob/master/docs/scenarios.md#pairing-with-a-device'&gt;Scenario: Pairing with a Device&lt;/a&gt; for a way how ownership can be proved via IOTA using a secret on the Pi itself), when you give a service provider consent to access your data (you do this in a type of IOTA wallet that manages your paired devices and consent policies), the service provider has to receive the restricted MAM channel's root and side key. How can this be done?&lt;/p&gt;&lt;p&gt;In our solution, the service provider can request access to data by sending its address and the goal for usage (for what reason energy data access is required as per the GDPR) to the consent wallet (called My Home). Then when a Raspberry Pi owner gives consent to access the data, the Raspberry Pi sends the access keys to the service provider's IOTA address.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*m4K9SylmmHYbQLEDxOhHhw.png&quot; alt=&quot;Communication of MAM root and side key in IOTA transaction&quot; width=&quot;100%&quot;&gt;&lt;/img&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;From the console output of the Raspberry Pi we see the creation of a zero value IOTA transaction containing the Pi's MAM root and side key to an authorized service provider's IOTA address&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;p&gt;In the IOTA transaction above the MAM root and side key in the IOTA transaction are encrypted. Why?&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;encryption&amp;#95;is&amp;#95;needed!&quot;&gt;&lt;/a&gt;Encryption is needed!&lt;/h3&gt;&lt;p&gt;Because on the IOTA Tangle all communication is public, the above key exchange needs to be encrypted. Otherwise eavesdroppers can see the IOTA transaction and obtain the root and side key as well. When an attacker has the keys, he has access to your privacy-sensitive energy usage data.&lt;/p&gt;&lt;p&gt;As stated, when using restricted MAM between two parties a key exchange needs to take place: the root and side key of the restricted MAM channel need to be communicated to the authorized service provider. IOTA has no asymmetric encryption. IOTA only has signing. So you cannot encrypt data with, for example, an IOTA address, and only decrypt it if you have the seed. So for asymmetric encryption we need something outside IOTA.&lt;/p&gt;&lt;p&gt;Since one of the benefits of IOTA is that its secure against quantum computers (IOTA's signing and proof of work are quantum proof), we don't want to lose this benefit by using classical asymmetric encryption algorithms like &lt;a href='https://en.wikipedia.org/wiki/RSA_(cryptosystem'&gt;RSA&lt;/a&gt;). These &lt;a href='https://arxiv.org/abs/quant-ph/9508027v2'&gt;are broken once quantum computers arrive&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;The author of the CHIOTA health care chat application helped us. CHIOTA came up with a &lt;a href='https://github.com/Noc2/Chiota/wiki/NTRU-Key-Exchange-for-IOTA]'&gt;quantum proof key exchange&lt;/a&gt; for IOTA. A method to deterministically generate a key pair using an IOTA seed and address. We use a similar approach, but &lt;a href='https://github.com/Alliander/decentralized-auth/tree/master/shared-libs/ntru'&gt;in JavaScript&lt;/a&gt; instead of &lt;a href='https://github.com/Noc2/Chiota/blob/master/Chiota/Chiota/Services/NTRUKex.cs'&gt;C&amp;#35;&lt;/a&gt;. Using this method and an IOTA seed you can generate a public and private key.&lt;/p&gt;&lt;p&gt;I think it would be helpful if quantum-proof asymmetric encryption is integrated in IOTA as an IXI module. Since you cannot encrypt with someone's IOTA address itself, a directory of public keys is needed somewhere. CHIOTA stores the public key on a user's first IOTA address. Perhaps we will see asymmetric encryption integrated in the IOTA Tangle or in MAM in the future.&lt;/p&gt;&lt;h4&gt;&lt;a name=&quot;encrypting&amp;#95;the&amp;#95;mam&amp;#95;root&amp;#95;and&amp;#95;side&amp;#95;key&quot;&gt;&lt;/a&gt;Encrypting the MAM root and side key&lt;/h4&gt;&lt;p&gt;By using the quantum proof encryption described, the MAM root and side key can be encrypted with the public key of the service provider. This way, although communication is public, only the service provider can decrypt it.&lt;/p&gt;&lt;p&gt;In our solution a tryte-encoded public key is sent along with the data access request, but a possible solution could also be that the public key is available in a central place. Something like an energy data usage app store where consumers can vouch for the trustworthiness of service providers.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*KIWTpzDtUER-Nv1Z_RT8NQ.png&quot; alt=&quot;Service Provider can show data&quot; width=&quot;100%&quot;&gt;&lt;/img&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;The service provider &lt;a href='https://www.wattt.nl'&gt;wattt.nl&lt;/a&gt; receives the MAM data (root and side key) from the device and decrypts it&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;h4&gt;&lt;a name=&quot;revoking&amp;#95;access&quot;&gt;&lt;/a&gt;Revoking access&lt;/h4&gt;&lt;p&gt;Thanks to &lt;a href='https://blog.iota.org/@harmvandenbrink'&gt;Harm van den Brink&lt;/a&gt; for sharing this idea.&lt;/p&gt;&lt;p&gt;Asymmetric encryption is also used in the case of access revocation. Multiple service providers can read the same MAM data stream with P1 energy data. When the software on the Raspberry Pi is instructed that a service provider's access is revoked (see next issue), it changes its side key and sends out a key rotation message. This message is published on the same MAM stream as the energy data, so service provider's only need to listen to that. The published message contains the &lt;strong&gt;new side key&lt;/strong&gt;, encrypted with the public keys of the remaining authorized service providers (&lt;a href='https://github.com/Alliander/decentralized-auth/blob/eac1cd1a6da0a9dc152d617deac7447c27922fb4/raspberry-pi-client/src/device-client.js#L216'&gt;click here for the code&lt;/a&gt;). This way all service providers that are listening that are still authorized can decrypt the message and update the side key, but the service provider of which consent is revoked cannot.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*NdU_TumCpOK25yf25oqFHw.png&quot; alt=&quot;Authorization revoked&quot; width=&quot;100%&quot;&gt;&lt;/img&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;The service provider shows plots earlier received data, but is not included in the KEY_ROTATION message, so is no longer authorized and is unable to fetch new data&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;mam&amp;#95;channels&amp;#95;can&amp;#95;be&amp;#95;used&amp;#95;as&amp;#95;decentralized&amp;#95;storage&amp;#95;of&amp;#95;consent&amp;#95;in&amp;#95;an&amp;#95;encrypted&amp;#95;immutable&amp;#95;event&amp;#95;log,&amp;#95;but...&amp;#95;you&amp;#95;now&amp;#95;have&amp;#95;an&amp;#95;encrypted&amp;#95;immutable&amp;#95;event&amp;#95;log&quot;&gt;&lt;/a&gt;MAM channels can be used as decentralized storage of consent in an encrypted immutable event log, but... you now have an encrypted immutable event log&lt;/h3&gt;&lt;p&gt;Once the Raspberry Pi (connected to the smart meter) is paired, it starts listening to the consent management front-end's MAM channel (&lt;a href='https://github.com/Alliander/decentralized-auth/blob/eac1cd1a6da0a9dc152d617deac7447c27922fb4/raspberry-pi-client/src/device-client.js#L376'&gt;click here for the code&lt;/a&gt;). Every time an event of type &lt;code&gt;AUTHORIZED&lt;/code&gt; is published on this channel by the front end, the Raspberry Pi will communicate its current root and side key (encrypted with the service provider's public key) to the service provider in the message (via an IOTA transaction). And when an event of type &lt;code&gt;AUTHORIZATION&amp;#95;REVOKED&lt;/code&gt; is published on the MAM channel the Raspberry Pi will publish a message of type &lt;code&gt;KEY&amp;#95;ROTATION&lt;/code&gt; on the MAM channel. So the Raspberry Pi can handle authorizations via this MAM channel.&lt;/p&gt;&lt;p&gt;The front-end uses the same channel to obtain its state, but it creates another view (&lt;a href='https://github.com/Alliander/decentralized-auth/blob/eac1cd1a6da0a9dc152d617deac7447c27922fb4/my-home/backend/src/modules/device/devices.js#L23'&gt;click here for a code example&lt;/a&gt;) from the events (for example show a consent policy when an event of type &lt;code&gt;AUTHORIZED&lt;/code&gt; has taken place).&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*Xd0BNpu&lt;i&gt;yd&lt;/i&gt;D0JHK6kU9qQ.png&quot; alt=&quot;Give Service Provider consent&quot; width=&quot;100%&quot;&gt;&lt;/img&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;In My Home's consent management wallet a paired device can be selected that the service provider can then access. The device is obtained from an event on the MAM channel (type of &lt;code&gt;DEVICE&amp;#95;ADDED&lt;/code&gt;). And when access is given an event of type &lt;code&gt;AUTHORIZED&lt;/code&gt; is published to which the paired Raspberry Pi will respond.&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;p&gt;Using an immutable log of events as a backend is called &lt;a href='https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing'&gt;event sourcing&lt;/a&gt;. Event sourcing works as a backend for both the consent management front-end and the Raspberry Pi.&lt;/p&gt;&lt;p&gt;The MAM channel root is communicated to an authorized service provider. This way all parties involved (Raspberry Pi, the consumer, and the service provider, see &lt;a href='#now-follow-four-lessons-we-learned-implementing-gdpr-compliant-energy-data-streams-on-the-iota-tangle'&gt;component diagram above&lt;/a&gt;) have access to the immutable audit trail and can show whom had consent and when to use the data.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/1600/1*xGVrHFPqv9sBlvnv50k6zg.png&quot; alt=&quot;MAM events&quot; width=&quot;100%&quot;&gt;&lt;/img&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;Events that are published on the consent and devices wallet (My Home)'s MAM channel. A user has added a device, provided consent, revoked consent and deleted the device.&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;p&gt;Very nice. But now we have an immutable audit log only accessible by parties involved. On &lt;a href='https://blog.iota.org/iota-development-roadmap-74741f37ed01#c5cf'&gt;permanodes&lt;/a&gt;, this will never be erased. The same goes for the published energy measurement data by the way, it is just like the policies, forever stored on permanodes in the IOTA Tangle.&lt;/p&gt;&lt;p&gt;Is this a problem? Although it is encrypted now, data might later be decryptable with new technologies or exploits. Other than that I don't see much difference between publicly storing encrypted data and handing out keys, or sending data in another way. For a malicious service provider it might be a bit more convenient to give someone else access when using keys. Instead of sending the raw received data they only have to send the keys. But raw data can also be easily send. It might be a problem in the future &lt;em&gt;if&lt;/em&gt; the encryption is hacked, the rest of the argument against public storing of encrypted data seems based on emotion (although this needs to be addressed in the case of widespread adoption).&lt;/p&gt;&lt;p&gt;In relation to the GDPR's right to erasure, is it enough for a service provider to delete the root and side key? The GDPR does not address what erasure precisely means. I personally think it is fine to have publicly available encrypted data with removed keys in a cloud or on a distributed ledger. It's similar to the practice of &lt;a href='https://en.wikipedia.org/wiki/Crypto-shredding'&gt;crypto-shredding&lt;/a&gt;. But in a larger scale roll out of distributed ledger software for GDPR, will citizens feel the same? We will see what interpretation of the legislation will dominate.&lt;/p&gt;&lt;p&gt;What is a problem with MAM is that it is unsuited for high frequency smart meter measurements.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;mam&amp;#95;proof&amp;#95;of&amp;#95;work&amp;#95;is&amp;#95;too&amp;#95;slow&amp;#95;for&amp;#95;smart&amp;#95;meter&amp;#95;measurements&amp;#95;(on&amp;#95;standard&amp;#95;hardware)&quot;&gt;&lt;/a&gt;MAM proof of work is too slow for smart meter measurements (on standard hardware)&lt;/h3&gt;&lt;p&gt;MAM's proof of work is a problem for publishing high frequency smart meter data on MAM. MAM is, with the current speed of proof of work on nodes, unsuited for P1 energy data. Even when offloading the proof of work from the Raspberry Pi to a node, it is too slow. On the main net one P1 energy data MAM message can be published roughly every 40 seconds. On the testnet it does work for smart meters that send data once every 10 seconds (&lt;a href='https://github.com/Alliander/decentralized-auth/blob/f16d46eb0503e2dae0eaf56cc799fcb87b058e39/raspberry-pi-client/src/device-client/p1.js'&gt;click here for the P1 data publishing code&lt;/a&gt;). Newer Dutch smart meter models, however, send data every second!&lt;/p&gt;&lt;p&gt;In its current state IOTA is not suited for the IoT industry (see &lt;a href='https://medium.com/konfid-io-blockchain-reports/iota-report-decoding-the-tangle-part-4-4-939543ac0050'&gt;this IOTA Report Overview&lt;/a&gt;). At the moment, the energy required for the proof of work for data publishing, is higher than the estimated energy savings from usage of the data (back-of-the-envelope calculation: it takes &lt;a href='(https://twitter.com/dantherealm4n/status/1009847828259143680'&gt;0.00005 kWh&lt;/a&gt;) per IOTA transaction, three transactions per MAM message is 0.00015 kWh per message, one message every 10 seconds for older smart meters is 473 kWh proof of work (PoW) per year per household. On average &lt;a href='https://www.energiesite.nl/veelgestelde-vragen/wat-is-een-gemiddeld-energieverbruik/'&gt;3500 kWh and 16000 kWh gas energy usage&lt;/a&gt; per household, insight into energy usage leads to &lt;a href='https://publications.parliament.uk/pa/cm201617/cmselect/cmsctech/161/161.pdf#page=18'&gt;2% energy savings&lt;/a&gt; by a conservative estimate, and 2% of the energy usage is 0.02 * (3500 + 16000) is roughly 390 kWh, so with current IOTA transaction speed for an average household more energy is used for the proof of work (473 kWh) than the expected savings (390 kWh)).&lt;/p&gt;&lt;p&gt;It is possible to move to an off-Tangle protocol like MQTT, but in that case the service provider is required to host an MQTT broker or similar. You lose the ease of access of an &lt;a href='https://github.com/iotaledger/mam.client.js#fetch&amp;mdash;async'&gt;&lt;code&gt;MAM.fetch&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;The PoW problem, however, can be solved. There are advancements where dedicated hardware can run proof of work much quicker. For example, an FPGA for the Raspberry Pi can run proof of work for &lt;a href='https://twitter.com/green_protocol/status/1010442578523664387'&gt;one transaction in 18 milliseconds&lt;/a&gt;! This uses much less energy. This does mean that people wanting to share their energy data for the energy transition must buy such dedicated hardware, or it must be provided in smart meters.&lt;/p&gt;&lt;p&gt;Proof of work speed needs to be improved for IOTA to be suitable for the IoT industry. This will happen once more devices start using the IOTA Tangle and the IoT industry starts using hardware that is optimized for IOTA's proof of work.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;in&amp;#95;practice&quot;&gt;&lt;/a&gt;In practice&lt;/h2&gt;&lt;p&gt;Examples of the software connected to the IOTA test net are deployed. Below we go through the flow on a laptop.&lt;/p&gt;&lt;p&gt;&lt;blockquote class=&quot;embedly-card&quot;&gt;&lt;h4&gt;&lt;a href=&quot;https://streamable.com/7e4oo&quot;&gt;Energy data on IOTA with consent&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;Check out this video on Streamable using your phone, tablet or desktop.&lt;/p&gt;&lt;/blockquote&gt; &lt;script async src=&quot;//cdn.embedly.com/widgets/platform.js&quot; charset=&quot;UTF-8&quot;&gt;&lt;/script&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;&lt;em&gt;Here we see the pairing of a Raspberry Pi, requesting consent from a service provider to access its data via the consent wallet My IOTA Home, consent (key exchange) for two service providers (wattt.nl from localhost and wattt.nl from domain), viewing the data once consent is given, and revoking the consent for one of the two service providers (key rotation). Note that this video is sped up.&lt;/em&gt;&lt;/sub&gt;&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;remarks&quot;&gt;&lt;/a&gt;Remarks&lt;/h2&gt;&lt;p&gt;In the future IOTA's &lt;a href='https://qubic.iota.org/'&gt;Qubic protocol&lt;/a&gt; can possibly be integrated. Its oracles might be useful for storing consent. Also the next version of MAM called &lt;a href='https://blog.iota.org/whats-next-current-iota-r-d-projects-eeb8cc03adb5'&gt;MAM+ will probably contain a public key infrastructure&lt;/a&gt; with possibly a key exchange mechanism. And in the future identity management system like &lt;a href='https://sovrin.org'&gt;Sovrin&lt;/a&gt; or &lt;a href='https://youtu.be/q6IihEQFPys'&gt;IRMA&lt;/a&gt; can be integrated to proof that you own a smart meter without revealing anything else about yourself, and for signing the consent.&lt;/p&gt;&lt;p&gt;The code is open source and available on &lt;a href='www.github.com/alliander/decentralized-auth'&gt;GitHub&lt;/a&gt;. It's a proof of concept and it's frail, but the happy flow (publishing energy data, pairing a Raspberry Pi, authorizing a service provider, viewing the data, revoking consent) has been tested and works.&lt;/p&gt;&lt;p&gt;If you have a Dutch smart meter, a Raspberry Pi and a RJ11 P1 cable you can &lt;a href='https://github.com/Alliander/decentralized-auth/tree/master/raspberry-pi-client#production'&gt;download and install the software&lt;/a&gt; and connect yourself! Those who want to create their own service provider can do so and interface with the My Home consent management wallet as well.&lt;/p&gt;&lt;p&gt;For more technical information check the &lt;a href='https://github.com/Alliander/decentralized-auth/tree/master/docs'&gt;documentation&lt;/a&gt;. The ideas are possibly applicable to other fields where personally identifiable information is used. For example in health care when a patient wants to share his medical records.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;conclusion&quot;&gt;&lt;/a&gt;Conclusion&lt;/h2&gt;&lt;p&gt;We hope this will be a step towards a privacy-preserving infrastructure that opens smart meter data to the world. Where energy data can be used by everyone who you trust. This way smart meter owners can be in control of their data, and everyone can create services that use it.&lt;/p&gt;&lt;p&gt;The infrastructure for sharing energy data while adhering to the GDPR, can be realized using a decentralized consent protocol on the IOTA Tangle. Although IOTA has some open issues like:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Improving the speed of proof of work for publishing MAM data messages (for example with dedicated hardware).&lt;/li&gt;&lt;li&gt;Legally clarifying if removal of keys of encrypted data on a distributed ledger adheres to the GDPR's right to erasure.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Thanks to my colleagues at Alliander and IOTA users for their help. And thank you for reading. Let me know what you think.&lt;/p&gt;&lt;p&gt;This blogpost was originally published at &lt;a href='https://medium.com/@erwinrooijakkers/gdpr-compliant-smart-meter-data-on-the-iota-tangle-four-lessons-learned-while-putting-the-dea852a5b2aa'&gt;https://medium.com/@erwinrooijakkers/gdpr-compliant-smart-meter-data-on-the-iota-tangle-four-lessons-learned-while-putting-the-dea852a5b2aa&lt;/a&gt;&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Sat, 08 Sep 2018 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2017-03-31-debug-panel/
</guid>
<link>
https://www.rooijakkers.software/posts/2017-03-31-debug-panel/
</link>
<title>
Simple but effective
</title>
<description>
&lt;pre&gt;&lt;code&gt;&amp;#40;defn debug-panel
  &amp;quot;Debug panel, pretty prints any data you pass in on the screen.&amp;quot;
  &amp;#91;d&amp;#93;
  &amp;#91;:pre
   &amp;#40;with-out-str &amp;#40;cljs.pprint/pprint d&amp;#41;&amp;#41;&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&amp;#91;debug-panel &amp;lt;data structure&amp;gt;&amp;#93;.
&lt;/code&gt;&lt;/pre&gt;Lovely.
</description>
<enclosure>

</enclosure>
<pubDate>
Fri, 31 Mar 2017 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-11-26-why-hellodata-is-written-in-clojure/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-11-26-why-hellodata-is-written-in-clojure/
</link>
<title>
Four reasons why HelloData is written in Clojure
</title>
<description>
&lt;p&gt;The &lt;a href='https://www.hellodata.org/'&gt;HelloData platform&lt;/a&gt; aims to connect smart meters, apps and consumers with one another, while still ensuring consumers retain ownership and control of their data. Technically speaking, this creates challenges when it comes to data streams (scalability), security (access rights; protection against malicious users), and the interface between the source (e.g. the smart meter) and services (the apps that use the data).&lt;/p&gt;&lt;p&gt;Because the first version of HelloData, written in Ruby on Rails, had performance issues, we decided to (re)build the platform in Clojure.&lt;/p&gt;&lt;p&gt;But why Clojure? In this blog post I explain four reasons behind this decision:&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;reason&amp;#95;1.&amp;#95;clojure&amp;#95;is&amp;#95;a&amp;#95;dialect&amp;#95;of&amp;#95;lisp&quot;&gt;&lt;/a&gt;REASON 1. Clojure is a dialect of Lisp&lt;/h2&gt;&lt;p&gt;I first came across Lisp at the outset of my career as a software developer in the article &lt;a href='https://www.paulgraham.com/avg.html'&gt;&lt;em&gt;Beating the Averages&lt;/em&gt;&lt;/a&gt; by Paul Graham (2001). In it, Graham describes how his startup (Viaweb, later Yahoo Stores) became successful thanks to a &quot;secret weapon&quot;. &lt;/p&gt;&lt;p&gt;This secret weapon was Lisp: a family of programming languages &lt;a href='https://www-formal.stanford.edu/jmc/recursive.ps'&gt;that has its origins back in 1958&lt;/a&gt; and is characterized by extensive use of open and close parentheses.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://imgs.xkcd.com/comics/lisp_cycles.png&quot; alt=&quot;xkcd I've just received word that the Emperor has dissolved the MIT computer science program permanently.&quot;/&gt; &lt;/p&gt;&lt;p&gt;Graham’s article convinced me that Lisp is the most powerful model of computation in existence. And that by seeing things through my Java specs (Java is the world’s most widely-used programming language, and the one with which I, too, started out) I had been suffering from the ‘Blub Paradox’: as a programmer I always thought in the programming language Blub, and so could only understand languages that were less powerful than Blub. And my Blub-induced mindset had therefore led me to dismiss any languages more powerful than Blub, such as Lisp, as gibberish.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;and&amp;#95;so&amp;#95;began&amp;#95;my&amp;#95;quest&amp;#95;to&amp;#95;learn&amp;#95;lisp&quot;&gt;&lt;/a&gt;And so began my quest to learn Lisp&lt;/h3&gt;&lt;p&gt;I filled my evenings and weekends with mind-blowing exercises that rejigged my mind. Initially, I had to get used to the parentheses. But then... I got it!&lt;sup&gt;&lt;a href='#fn-1' id='fnref1'&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;the&amp;#95;power&amp;#95;of&amp;#95;lisp&amp;#95;lies&amp;#95;in&amp;#95;parentheses&quot;&gt;&lt;/a&gt;The power of Lisp lies in parentheses&lt;/h3&gt;&lt;p&gt;The fundamental data structure in Lisp (short for: &lt;strong&gt;LIS&lt;/strong&gt;t &lt;strong&gt;P&lt;/strong&gt;rocessor) is the list. Not only does the data that the Lisp programmer uses consist of lists enclosed by parentheses; so, too, does the code itself. This means that code can be treated as data, and data as code. This is called &lt;a href='https://en.wikipedia.org/wiki/Homoiconicity'&gt;homoiconicity&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Homoiconicity makes it possible to create transformations out of source code, to write programs that create programs (in Lisp these programs are known as &lt;a href='https://clojure.org/reference/macros'&gt;macros&lt;/a&gt;), and to introduce new syntax. This is what makes Lisp so powerful, and why Paul Graham described it as the &quot;secret weapon&quot;.&lt;/p&gt;&lt;p&gt;In the context of HelloData, we make use of Lisp’s power in two ways:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Within Clojure, we’re trying to write our ‘own language’ that describes our domain. The flexibility of the abstractions means that we are scarcely, if at all, hampered by the limitations of a programming language.&lt;/li&gt;&lt;li&gt;This same flexibility means it’s possible to integrate features of other languages into Lisp, so they are available as libraries (code shared by others, so that a developer doesn’t having to write them themselves). An example being Go routines from the Go programming language, which can be introduced into Clojure via the core.async library. The difference with Go itself is that, in Clojure, such language features are not a fundamental property of the language.&lt;/li&gt;&lt;/ol&gt;&lt;h3&gt;&lt;a name=&quot;so&amp;#95;is&amp;#95;everything&amp;#95;with&amp;#95;lisp&amp;#95;always&amp;#95;just&amp;#95;beer&amp;#95;and&amp;#95;skittles?&quot;&gt;&lt;/a&gt;So is everything with Lisp always just beer and skittles?&lt;/h3&gt;&lt;p&gt;No.&lt;/p&gt;&lt;p&gt;Precisely because Lisp is so powerful and flexible, we also have the phenomenon sometimes refered to as The Curse of Lisp (for more on this, see Rudolf Winestock’s essay &lt;a href='https://winestockwebdesign.com/Essays/Lisp_Curse.html'&gt;&lt;em&gt;The Lisp Curse&lt;/em&gt;&lt;/a&gt;): Lisp’s being so easy to extend means there are also many language extensions. Resulting in many different dialects and libraries that are only partially and poorly documented, and really only suitable for the specific domain of their creator.&lt;/p&gt;&lt;p&gt;Clojure is a Lisp dialect that is less affected by the Curse of Lisp, as in Clojure the consistency of the core libraries and the standard means of doing things are guarded by its author, Rich Hickey, and his company &lt;a href='https://cognitect.com/'&gt;Cognitect&lt;/a&gt;. &lt;/p&gt;&lt;p&gt;What’s more, Clojure has access to the Java Virtual Machine (JVM) and, in the form of ClojureScript, to JavaScript, on which many standard libraries are available. Which neatly brings us to the second reason for opting for Clojure.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;reason&amp;#95;2.&amp;#95;clojure&amp;#95;runs&amp;#95;on&amp;#95;the&amp;#95;jvm&amp;#95;and&amp;#95;javascript&amp;#95;runtime&quot;&gt;&lt;/a&gt;REASON 2. Clojure runs on the JVM and JavaScript runtime&lt;/h2&gt;&lt;p&gt;The JVM is a platform-independent environment (the JVM runs on Linux, Windows, macOS, etc.) for executing Java bytecode. The JVM has been around since the 90s, since when it has been optimized by many different people.&lt;/p&gt;&lt;p&gt;On the JVM you have access to a vast number of libraries. From web servers to user interfaces — you name it and there’s a library for it. Clojure is converted into Java bytecode, and thus benefits from the stability, popularity, speed and safety of the JVM.&lt;/p&gt;&lt;p&gt;All libraries on the JVM are simple to use from Clojure. For example, in our registration flow we wanted to use Macaroons: exchange keys described in this &lt;a href='https://research.google.com/pubs/pub41892.html'&gt;paper by Google&lt;/a&gt;. We don’t have to implement Macaroons ourselves, because a Java library already existed which  —aside from one spelling mistake — we could easily use. 	&lt;/p&gt;&lt;p&gt;Clojurescript does the same with Javascript that Clojure does on the JVM. JavaScript is the world’s most widely-used programming language and runs on pretty well all browsers.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;what’s&amp;#95;in&amp;#95;a&amp;#95;name?&quot;&gt;&lt;/a&gt;What’s in a name?&lt;/h3&gt;&lt;p&gt;Though their names may be very similar, Java and JavaScript have about as much in common as a car and a carp. Clojure and ClojureScript, on the other hand, are the same language. This means that, as long as you don’t use libraries specifically intended for the host, you can reuse Clojure code from the backend on the frontend. Letting you write an entire application in Clojure and, for example, use the validation code in both the frontend and backend.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;best&amp;#95;thing&amp;#95;about&amp;#95;clojurescript?&amp;#95;the&amp;#95;unique&amp;#95;development&amp;#95;experience.&quot;&gt;&lt;/a&gt;Best thing about ClojureScript? The unique development experience.&lt;/h3&gt;&lt;p&gt;Normally speaking, the development of websites involves the following two steps:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Adjust code.&lt;/li&gt;&lt;li&gt;Refresh the browser to see the changes.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Step 1 is unavoidable, but Step 2 is tedious and slows things down. The developer has to perform an extra act and the website loses its state. If, for example, there’s been a few clicks and fields have been filled in on the website for testing, following a browser refresh the developer is back to square one.&lt;/p&gt;&lt;p&gt;The Figwheel library offers a solution that makes this continual refreshing unnecessary, as it ensures that the code that has been modified is sent directly to the browser. If you have the browser displayed on the left of your screen and the code you are adapting on the right, when you make a code adjustment on the right, you immediately see on the left its effect on the website. In this video, Figwheel’s creator gives a demo:&lt;/p&gt;&lt;p&gt;&lt;iframe src=&quot;https://www.youtube.com/embed/KZjFVdU8VLI&quot; allowfullscreen=&quot;&quot; height=&quot;315&quot; frameborder=&quot;0&quot; width=&quot;560&quot;&gt;&lt;/iframe&gt;&lt;/p&gt;&lt;p&gt;This perfectly describes our development experience at HelloData and is one of the reasons &lt;a href='https://www.itworld.com/article/2693998/big-data/clojure-developers-are-the-happiest-developers.html'&gt;why the development team always looks so cheerful&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Although Clojure runs on the JVM, the code written does not look like Java - the most popular programming language on the JVM - at all. This is partly due to the parentheses, but mainly because of Clojure’s data orientation. What this is you’ll read in the third reason.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;reason&amp;#95;3.&amp;#95;clojure&amp;#95;is&amp;#95;data&amp;#95;oriented&quot;&gt;&lt;/a&gt;REASON 3. Clojure is data oriented&lt;/h2&gt;&lt;p&gt;In Clojure much less code is needed to say the same things as in Java. Code that is written is only about the problem that it’s solving. Syntax, design patterns, and other ceremonies that are not about the problem, disappear.&lt;/p&gt;&lt;p&gt;This is because Clojure treats data as data.&lt;/p&gt;&lt;p&gt;Treating data as data – what does that mean? Programmers work with data. In many other programming languages, like for example Java, data is not treated as data. Before it is used the data is first transformed to a, by the programmer created specific data structure (for example a class), only used for that specific use case, that is difficult to extend, and makes it difficult to create another implementation. &lt;/p&gt;&lt;p&gt;In Clojure the programmer often just uses Clojure datastructures (lists; vectors; hash-maps; sets).&lt;/p&gt;&lt;p&gt;In practice this means that the programmers makes transformations on Clojure datastructures with all the free functions that are available.&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures.  –- Alan Perlis (&lt;a href='https://www.cs.yale.edu/homes/perlis-alan/quotes.html_'&gt;Epigrams in Programming&lt;/a&gt;) &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;To drive the point home I can advise you to watch a few minutes of the &lt;em&gt;Clojure made Simple&lt;/em&gt; video below, from 51 minutes and 15 seconds onwards. This video contains a rant of Rich Hickey, the Clojure creator, where he compares a specific Java-datastructure with the same representation in Clojure.&lt;/p&gt;&lt;p&gt;&lt;iframe src=&quot;https://www.youtube.com/embed/VSdnJDO-xdg?t=51m15s&quot; allowfullscreen=&quot;&quot; height=&quot;315&quot; frameborder=&quot;0&quot; width=&quot;560&quot;&gt;&lt;/iframe&gt;&lt;/p&gt;&lt;p&gt;Clojure’s data-orientation (treatment of data as data) is – besides the level of abstraction that can be reached – the reason that Clojure code bases are relatively small. Smaller programs have fewer bugs. And almost all code is about the problem that is solved. Not about something else. This makes Clojure code simple and robust.&lt;/p&gt;&lt;p&gt;So, its flexibility, the host platforms and the treatment of data as data, are three reasons to use Clojure. Another important point is that Clojure is made for parallel and concurrent programming.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;reason&amp;#95;4.&amp;#95;clojure&amp;#95;embraces&amp;#95;concurrent&amp;#95;programming&quot;&gt;&lt;/a&gt;REASON 4. Clojure embraces concurrent programming&lt;/h2&gt;&lt;p&gt;According to Moore’s Law, the performance of processors doubles every 18 months. So taking account of physical limitations, Moore’s Law becomes this:&lt;/p&gt;&lt;p&gt;&lt;img alt=&quot;Moore's law&quot; src=&quot;https://i.imgur.com/q0Nb9gP.png&quot;/&gt; Source: &lt;a href='https://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;arnumber=5688147&amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5688147'&gt;IEEE Computer Society&lt;/a&gt;&lt;/p&gt;&lt;p&gt;In the graph above, we see how the limit on processor performance is reached. Right now, technologies are being developed to make computers even faster, namely:&lt;/p&gt;&lt;p&gt;1.	More processors on a chip (multi-core processors, see bottom line of graph); 2.	Utilizing multiple computers, for example in the cloud (distributed programming).&lt;/p&gt;&lt;p&gt;The future of programming is thus multi-core and distributed&lt;sup&lt;a href='#fn-2' id='fnref2'&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;&lt;p&gt;To make the most of multi-core processors and distributed machines, software developers should use &lt;em&gt;concurrent&lt;/em&gt; programming (writing code that does things in parallel). After all, when source code is sequential, you can’t run it on multiple computers or processors simultaneously.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;the&amp;#95;problem&amp;#95;with&amp;#95;concurrent&amp;#95;programming...?&quot;&gt;&lt;/a&gt;The problem with concurrent programming...?&lt;/h3&gt;&lt;p&gt;Quite simply, it’s difficult to do in most programming languages.&lt;/p&gt;&lt;p&gt;Concurrent programming is tricky due to so-called ‘race conditions’. Race conditions occur when two processes simultaneously want to read or write shared data and the sequence or timing of this is uncontrollable. They are the cause of many bugs and often difficult to trace.&lt;/p&gt;&lt;p&gt;Race conditions manifest themselves as &lt;em&gt;occasionally&lt;/em&gt; an erroneous situation.  &lt;/p&gt;&lt;p&gt;One way to avoid race conditions is to identify critical sections at points in the source code that may only be used by one process at a time. But programming these critical sections itself has its problems. Take, for example, deadlocks, where two processes both wait for each other and the software freezes. Or starvation, where a process never gets its turn and is simply kept waiting. As well as these problems, code with critical sections cannot be executed in parallel.&lt;/p&gt;&lt;p&gt;The creator of Clojure says in his presentation, &lt;a href='https://youtu.be/dGVqrGmwOAw?t=24m28s'&gt;&lt;em&gt;Clojure Concurrency&lt;/em&gt;&lt;/a&gt;, that we can learn two things from a famous Java book with techniques for concurrent programming:&lt;/p&gt;&lt;p&gt;1.	Concurrent Programming in Java is incredibly difficult. 2.	The immutability (unchangability) of values is repeatedly cited as the solution. 	&lt;/p&gt;&lt;p&gt;Race conditions are caused by changes: one process wants to write a value at precisely the moment that another process is reading it; or two processes want to write a value at the same time. But what if assigned values were immutable? Then there’d be no more racing.&lt;/p&gt;&lt;p&gt;Immutability of values makes critical sections redundant and race conditions impossible. So-called ‘functional programming languages’ are based on this principle. Just as with mathematical functions, the results of calculations in a functional programming language are always the same. In non-functional programming languages, you can’t be sure about outcomes and different processes or side effects can occur that change a value in the background. In functional programming languages, you can be certain (this is known as ‘referential transparency’); so it doesn’t matter in what order you execute code, which makes concurrency easy.&lt;/p&gt;&lt;p&gt;Clojure supplies tools to program functionally and immutable values are fundamentally built into the language. Once assigned, a value in Clojure is ‘persistent’. If you want to change something, you need to make copies of previous data structures with the changes added. In order to avoid all these data structures occupying too much space in the computer’s memory, Clojure uses a method called ‘structural sharing’. This ensures efficient, persistent data structures, as shown in this diagram:&lt;/p&gt;&lt;p&gt;&lt;img alt=&quot;Persistent datastructures&quot; src=&quot;https://i.imgur.com/ELNWnsa.png&quot;/&gt; Source: &lt;a href='https://jr0cket.co.uk/slides/functional-advantage-with-clojure.html'&gt;Functional Advantage with Clojure&lt;/a&gt;&lt;/p&gt;&lt;p&gt;In Clojure, it seems like the programmer is working with copies of data, but under the hood Clojure reuses everything that remains unchanged. So despite all the copies, Clojure still only uses minimal memory.&lt;/p&gt;&lt;p&gt;Sometimes you do need to change a value. After all, in the real world things change and in a pragmatic programming language you have to be able to work with variable values.&lt;/p&gt;&lt;p&gt;But happily, changes to variables are possible in Clojure, and so the language is not purely functional. Clojure provides constructs for change. There are mechanisms built into Clojure to change values which ensure that the system is always consistent. All without the need for the developer having to update the values manually, using error-prone critical sections.&lt;/p&gt;&lt;p&gt;Through this focus on functional programming, persistent data structures and language constructs, we can see how Clojure truly embraces concurrent programming.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;and&amp;#95;there’s&amp;#95;loads&amp;#95;more&amp;#95;reasons&amp;#95;to&amp;#95;love&amp;#95;clojure&quot;&gt;&lt;/a&gt;AND THERE’S LOADS MORE REASONS TO LOVE CLOJURE&lt;/h2&gt;&lt;p&gt;The origins in Lisp, the support of host platforms and the focus on concurrent programming are three of the reasons why HelloData is built in Clojure. And I’ve not even mentioned any of these others:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Clojure’s &lt;a href='https://www.braveclojure.com/getting-started/#Using_the_REPL'&gt;REPL&lt;/a&gt;, which allows the developer to communicate with their code&lt;/li&gt;&lt;li&gt;the many supporting programming paradigms - such as &lt;a href='https://github.com/clojure/core.logic'&gt;logic programming&lt;/a&gt;, where you can say: &quot;this is happening, give me a solution&quot;.&lt;/li&gt;&lt;li&gt;&lt;a href='https://www.ibm.com/developerworks/library/j-clojure-protocols/'&gt;practical polymorphism&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://github.com/syl20bnr/spacemacs'&gt;integrated editors&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://www.braveclojure.com/multimethods-records-protocols/'&gt;flexibility for change&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://clojure.org/about/spec'&gt;clojure.spec&lt;/a&gt;&lt;/li&gt;&lt;li&gt;the GPU (Graphical Processing Unit) &lt;a href='https://neanderthal.uncomplicate.org/articles/tutorial_opencl.html'&gt;tools&lt;/a&gt;&lt;/li&gt;&lt;li&gt;Adoption within the industry&lt;/li&gt;&lt;li&gt;the &lt;a href='https://leiningen.org/'&gt;build tool&lt;/a&gt;&lt;/li&gt;&lt;li&gt;and the friendly Clojure community.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;The future is parallel – and Clojure is ready for it!&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;there’s&amp;#95;just&amp;#95;one&amp;#95;problem&amp;#95;with&amp;#95;clojure.&amp;#95;and&amp;#95;only&amp;#95;you&amp;#95;can&amp;#95;solve&amp;#95;it.&quot;&gt;&lt;/a&gt;There’s just one problem with Clojure. And only you can solve it.&lt;/h2&gt;&lt;p&gt;Besides problems programmers with a different background have adapting to Clojure, there is the additional problem of actually finding good, experienced Clojure developers.&lt;/p&gt;&lt;p&gt;Are you an experienced Clojure developer? Do you want to contribute to a sustainable future? If so, we’d be delighted to welcome you to HelloData. &lt;/p&gt;&lt;p&gt;Simply get in touch with me, at erwin.rooijakkers@mpare.net, and I'll be happy to tell you more about HelloData.&lt;/p&gt;&lt;p&gt;This blog post originally appeared on the MPARE website. See &lt;a href='https://www.mpare.net/en/blog-drie-redenen-waarom-hellodata-wordt-gebouwd-in-clojure/'&gt;https://www.mpare.net/en/blog-drie-redenen-waarom-hellodata-wordt-gebouwd-in-clojure/&lt;/a&gt;. &lt;ol class='footnotes'&gt;&lt;li id='fn-1'&gt;This moment of enlightenment is wonderfully illustrated in a lecture by Gerald Jay Sussman at the point when he finishes writing out Lisp code (fitted onto a single school blackboard), in which any programming language can be expressed. See &lt;a href='https://youtu.be/0m6hoOelZH8?t=34m34s'&gt;https://youtu.be/0m6hoOelZH8?t=34m34s&lt;/a&gt;.&lt;a href='#fnref1'&gt;&amp;#8617;&lt;/a&gt;&lt;/li&gt;&lt;li id='fn-2'&gt;Extensive research is being done into quantum computers, with promising results. But to keep things to a reasonable length and not dive into areas where I have limited expertise,I’ve decided not to cover the quantum computer, and programming it, in this blog post.&lt;a href='#fnref2'&gt;&amp;#8617;&lt;/a&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Sat, 26 Nov 2016 00:00:00 +0100
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-10-03-quote-of-the-week/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-10-03-quote-of-the-week/
</link>
<title>
Quote of the week #2
</title>
<description>
&lt;p&gt;Steve McConnel in &lt;a href='https://amzn.to/2dVscng'&gt;&lt;em&gt;Code Complete&lt;/em&gt;&lt;/a&gt; on the &lt;strong&gt;personality&lt;/strong&gt; of expert software engineers.&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&lt;blockquote&gt;If you haven't spent at least a month working on the same program &amp;ndash; working 16 hours a day, dreaming about it during the remaining 8 hours of restless sleep, working several nights straight through trying to eliminate that &quot;one last bug&quot; from the program &amp;ndash; then you haven't really written a complicated computer program. And you may not have the sense that there is something exhilarating about programming.&lt;br&gt; &amp;ndash; Edward Yourdon&lt;/blockquote&gt; This lusty tribute to programming machismo is pure B.S. and an almost certain recipe for failure. Those all-night programming stints make you feel like the greatest programmer in the world, but then you have to spend several weeks correcting the defects you installed during your blaze of glory. By all means, get excited about programming. But excitement is no substitute for competency. Remember which is more important.&lt;br /&gt;&lt;/p&gt;&lt;/blockquote&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Mon, 03 Oct 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-09-22-quote-of-the-week/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-09-22-quote-of-the-week/
</link>
<title>
Quote of the week #1
</title>
<description>
&lt;p&gt;Alan Perlis on the first page of &lt;a href='https://amzn.to/29Jy8Ni'&gt;&lt;em&gt;Structure and Interpretation of Computer Programs&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;I think that it’s extraordinarily important that we in computer science keep fun in computing. When it started out, it was an awful lot of fun. Of course, the paying customers got shafted every now and then, and after a while we began to take their complaints seriously. We began to feel as if we really were responsible for the successful, error-free perfect use of these machines. I don’t think we are. I think we’re responsible for stretching them, setting them off in new directions, and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all, I hope we don’t become missionaries. Don’t feel as if you’re Bible salesmen. The world has too many of those already. What you know about computing other people will learn. Don’t feel as if the key to successful computing is only in your hands. What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more. &lt;br/&gt;&amp;ndash; Alan J. Perlis (April 1, 1922-February 7, 1990) &lt;/p&gt;&lt;/blockquote&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Thu, 22 Sep 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-09-17-paip-chapter4/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-09-17-paip-chapter4/
</link>
<title>
PAIP in Clojure Chapter 4
</title>
<description>
&lt;p&gt;The fourth chapter of &lt;a href='https://amzn.to/29CsgBt'&gt;Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp&lt;/a&gt; on the &lt;em&gt;General Problem Solver&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://amzn.to/29CsgBt&quot;&gt;&lt;img src=&quot;https://images-na.ssl-images-amazon.com/images/I/516h5FydqNL.&lt;i&gt;SX359&lt;/i&gt;BO1,204,203,200_.jpg&quot;&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;summary&quot;&gt;&lt;/a&gt;Summary&lt;/h2&gt;&lt;p&gt;The chapter starts with a quote by Herbert Simon, a Nobel Prize winner and one of the inventors of the &lt;em&gt;General Problem Solver&lt;/em&gt; (GPS):&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;There are now in the world machines that think.&lt;/em&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;This GPS machine that thought was the first useful Artificial Intelligence program. It was written to solve every problem using the same algorithm (reasoning).  &lt;a href='https://bitsavers.informatik.uni-stuttgart.de/pdf/rand/ipl/P-1584_Report_On_A_General_Problem-Solving_Program_Feb59.pdf'&gt;GPS was written in (1959)&lt;/a&gt; in a computer language created by the authors called &lt;em&gt;Information Processing Language&lt;/em&gt; (IPL):  an assembly language for manipulating lists. As can be imagined by looking at &lt;a href='https://en.wikipedia.org/wiki/Information_Processing_Language'&gt;IPL's Wikipedia page&lt;/a&gt; the code was complex.  Nowadays using a language at a higher level of abstraction a GPS can be written in a few lines of code and we can have a clearer grasp of the concepts at work. It turns out &lt;strong&gt;the program is not so general as it name suggests&lt;/strong&gt;. According to Norvig the exaggerated claims probably had to do with the complex code: if the code is complex the program must be doing something interesting. &lt;/p&gt;&lt;p&gt;GPS is a &lt;strong&gt;searching algorithm&lt;/strong&gt; that given various means with their pre- and postconditions finds means to a specific end.  Simon and his colleagues realized humans often use means-end analysis to solve a problem. Here's an example:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;I want to take my son to nursery school. What’s the difference between what I have and what I want? One of distance. What changes distance? My automobile. My automobile won’t work. What is needed to make it work? A new battery. What has new batteries? An auto repair shop. I want the repair shop to put in a new battery; but the shop doesn’t know I need one. What is the difficulty? One of communication. What allows communication? A telephone… and so on. — Newell and Simon’s example from their 1972 book Human Problem Solving &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;We can pose this problem when we structure it of consisting of various goals with starting conditions and operators.&lt;/p&gt;&lt;p&gt;In Clojure we can introduce a record called &lt;code&gt;Op&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defrecord Op &amp;#91;action preconds add-list del-list&amp;#93;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;Op&lt;/code&gt; consist of an action (goal), and sets of preconditions, additions once the action is executed and a list of things that are no longer the case (&lt;code&gt;del-list&lt;/code&gt;).&lt;/p&gt;&lt;p&gt;Now we can structure the taking our son to school problem posed above as consisting of the following operators:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def school-ops
  #{&amp;#40;Op. :drive-son-to-school
         #{:son-at-home :car-works}
         #{:son-at-school}
         #{:son-at-home}&amp;#41;
    &amp;#40;Op. :shop-installs-battery
         #{:car-needs-battery :shop-knows-problem :shop-has-money}
         #{:car-works}
         nil&amp;#41;
    &amp;#40;Op. :tell-shop-problem
         #{:in-communication-with-shop}
         #{:shop-knows-problem}
         nil&amp;#41;
    &amp;#40;Op. :telephone-shop
         #{:know-phone-number}
         #{:in-communication-with-shop}
         nil&amp;#41;
    &amp;#40;Op. :look-up-number
         #{:have-phone-book}
         #{:know-phone-number}
         nil&amp;#41;
    &amp;#40;Op. :give-shop-money
         #{:have-money}
         #{:shop-has-money}
         #{:have-money}&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;GPS can solve any problem that is posed this way when it is given an initial state, a goal and available operations:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;GPS #{:son-at-home :car-needs-battery :have-money :have-phone-book} ; initial state
     #{:son-at-school} ; goal
     school-ops&amp;#41; ; available operations
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Some problems, however, take too much time to solve in such a way. Computing the solution to these problems takes exponentially more time as the size of the problem grows.  It is generally assumed [citation needed] these problems cannot be solved by an algorithm:  there is simply not enough time to find a solution.  Problems like that are called NP-hard.  So GPS is not general since it fails to solve these problems in a reasonable amount of time.&lt;/p&gt;&lt;p&gt;&lt;em&gt;Intermezzo&lt;/em&gt; The physicist Arkardy Bolotin states in &lt;a href='https://arxiv.org/abs/1403.7686'&gt;Computational Solution to Quantum Foundational Problems&lt;/a&gt; that NP-hard problems can manifest itself in our physical reality (read in &lt;a href='https://medium.com/the-physics-arxiv-blog/the-astounding-link-between-the-p-np-problem-and-the-quantum-nature-of-universe-7ef5eea6fd7a#.kiby96b7i'&gt;this blog post&lt;/a&gt;). Quantum physics breaks down at a macroscopic level (i.e., we do not see people in superposition or tunneling through walls, but electrons do), but there is no reason why it should break down.  Bolotin argues that finding a solution to the quantum equations takes too much time (is NP-hard) and that therefore macroscopic objects in our world do not show quantum behaviour.&lt;/p&gt;&lt;p&gt;/edit: a computer scientist I respect called Scott Aaronson states the above is complete garbage and ignores basic physics and computer science:&lt;blockquote&gt;&lt;p&gt;It gives me no pleasure to respond to this sort of thing—it would be far better to let papers this gobsmackingly uninformed about the relevant issues fade away in quiet obscurity—but since that no longer seems to be possible in the age of social media Response: &lt;a href='https://www.scottaaronson.com/blog/?p=1767#comment-103591'&gt;https://www.scottaaronson.com/blog/?p=1767#comment-103591&lt;/a&gt;&lt;br /&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;em&gt;End intermezzo&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Here's, anyhow, the first implementation of &lt;a href='https://norvig.com/paip/gps1.lisp'&gt;the GPS algorithm in the book&lt;/a&gt; translated to Clojure:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def state
  &amp;quot;The current state: a list of conditions.&amp;quot;
  &amp;#40;atom #{}&amp;#41;&amp;#41;

&amp;#40;def ops
  &amp;quot;A list of available operators.&amp;quot;
  &amp;#40;atom #{}&amp;#41;&amp;#41;

&amp;#40;defrecord Op &amp;#91;action preconds add-list del-list&amp;#93;&amp;#41;

&amp;#40;defn appropriate?
  &amp;quot;An op is appropriate to a goal if it is in its add list.&amp;quot;
  &amp;#91;goal op&amp;#93;
  &amp;#40;some #&amp;#40;= % goal&amp;#41; &amp;#40;:add-list op&amp;#41;&amp;#41;&amp;#41;

&amp;#40;declare apply-op&amp;#41;
&amp;#40;defn achieve
  &amp;quot;A goal is achieved if it already holds,
  or if there is an appropriate op for it that is applicable.&amp;quot;
  &amp;#91;goal&amp;#93;
  &amp;#40;or &amp;#40;some #&amp;#40;= % goal&amp;#41; @state&amp;#41;
      &amp;#40;some apply-op
            &amp;#40;filter #&amp;#40;appropriate? goal %&amp;#41; @ops&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn apply-op
  &amp;quot;Print a message and update &amp;#42;state&amp;#42; if op is applicable.&amp;quot;
  &amp;#91;op&amp;#93;
  &amp;#40;when &amp;#40;every? achieve &amp;#40;:preconds op&amp;#41;&amp;#41;
    &amp;#40;println &amp;quot;Executing&amp;quot; &amp;#40;:action op&amp;#41;&amp;#41;
    &amp;#40;reset! state &amp;#40;clojure.set/difference @state &amp;#40;:del-list op&amp;#41;&amp;#41;&amp;#41;
    &amp;#40;reset! state &amp;#40;clojure.set/union @state &amp;#40;:add-list op&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn GPS
  &amp;quot;General Problem Solver: achieve all goals using &amp;#42;ops&amp;#42;.&amp;quot;
  &amp;#91;state' goals ops'&amp;#93;
  &amp;#40;reset! state state'&amp;#41;
  &amp;#40;reset! ops ops'&amp;#41;
  &amp;#40;if &amp;#40;every? achieve goals&amp;#41; :solved&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When we execute GPS for the son to school problem&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;GPS #{:son-at-home :car-needs-battery :have-money :have-phone-book}
     #{:son-at-school}
     school-ops&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;this is the result:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Executing :look-up-number&lt;br/&gt; Executing :telephone-shop&lt;br/&gt; Executing :tell-shop-problem&lt;br/&gt; Executing :give-shop-money&lt;br/&gt; Executing :shop-installs-battery&lt;br/&gt; Executing :drive-son-to-school&lt;br/&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;GPS finds the means to an end.&lt;/p&gt;&lt;p&gt;NP-hardness is not the only problem of the current GPS algorithm.  Norvig explains numerous other problems with it in PAIP.  In the exercises he wants us to solve some of them.  I'll do my best, but I am not sure I have enough time.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;exercises&quot;&gt;&lt;/a&gt;Exercises&lt;/h2&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;4.2&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 4.2 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a function that generates all permutations of its input.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;(This is probably useful for improving GPS later.)&lt;/p&gt;&lt;p&gt;Seems like a good idea to use a &lt;strong&gt;recursive strategy&lt;/strong&gt;. The permutations of zero elements is only the element itself. Permutations of a list are the permutations of the rest plus the first element added at every position in its permutations.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn add-all-positions
  &amp;quot;Creates collection where element elem is added at every position of coll.&amp;quot;
  &amp;#91;elem coll&amp;#93;
  &amp;#40;let &amp;#91;size &amp;#40;count coll&amp;#41;&amp;#93;
    &amp;#40;loop &amp;#91;n 0 acc &amp;#91;&amp;#93;&amp;#93;
      &amp;#40;if &amp;#40;&amp;gt; n size&amp;#41; acc
          &amp;#40;let &amp;#91;&amp;#91;before after&amp;#93; &amp;#40;split-at n coll&amp;#41;
                permutation &amp;#40;concat before &amp;#91;elem&amp;#93; after&amp;#41;&amp;#93;
            &amp;#40;recur &amp;#40;inc n&amp;#41; &amp;#40;conj acc permutation&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn permutations
  &amp;quot;Generates permutations of input bag.&amp;quot;
  &amp;#91;bag&amp;#93;
  &amp;#40;if &amp;#40;empty? bag&amp;#41; &amp;#91;&amp;#91;&amp;#93;&amp;#93;
      &amp;#40;conj &amp;#40;mapcat &amp;#40;partial add-all-positions &amp;#40;first bag&amp;#41;&amp;#41;
                    &amp;#40;permutations &amp;#40;rest bag&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Testing:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;count &amp;#40;permutations &amp;#91;1 2 3 4&amp;#93;&amp;#41;&amp;#41;
;; =&amp;gt; 24
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This algorithm is O(N&lt;sup&gt;2&lt;/sup&gt;) since it loops over all previous permutations.  According to Norvig finding permutations can be improved to O(N), but I do not see how.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;4.3&amp;#95;[h]&quot;&gt;&lt;/a&gt;Exercise 4.3 [h]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;GPS does not recognize the situation where a goal is accidentally solved as part of achieving another goal. Consider the goal of eating dessert. Assume that there are two operators available: eating ice cream (which requires having the ice cream) and eating cake (which requires having the cake). Assume that we can buy a cake, and that the bakery has a deal where it gives out free ice cream to each customer who purchases and eats a cake.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;(1) Design a list of operators to represent this situation.&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def dessert-ops
  #{&amp;#40;Op. :eating-ice-cream
         #{:having-ice-cream}
         #{:eating-dessert}
         #{:having-ice-cream}&amp;#41;
    &amp;#40;Op. :eating-cake
         #{:having-cake}
         #{:eating-dessert :having-ice-cream}
         #{:having-cake}&amp;#41;
    &amp;#40;Op. :buying-cake
         #{:able-to-buy-cake}
         #{:having-cake}
         nil&amp;#41;}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;em&gt;(2) give GPS the goal of eating dessert. Show that with the right list of operators, GPS will device to eat ice cream, then decide to buy and eat the cake in order to get the free ice cream, and then go ahead and eat the ice cream, even though the goal of eating dessert has already been achieved by eating the cake.&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;GPS #{:able-to-buy-cake}
     #{:eating-dessert}
     dessert-ops&amp;#41;
;; =&amp;gt; Executing :buying-cake
;;    Executing :eating-cake
;;    Executing :eating-ice-cream
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;em&gt;(3) Fix GPS so that it does not manifest this problem.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;This can be solved by adding a check to see if operations are already achieved:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn already-achieved?
  &amp;quot;Checks if new operations are not already achieved&amp;quot;
  &amp;#91;ops&amp;#93;
  &amp;#40;clojure.set/subset? ops @state&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And adding this check to &lt;code&gt;apply-op&lt;/code&gt; (and ensure to return true since the truthy return value is used in GPS):&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn apply-op
  &amp;quot;Print a message and update &amp;#42;state&amp;#42; if op is applicable.&amp;quot;
  &amp;#91;op&amp;#93;
  &amp;#40;when &amp;#40;every? achieve &amp;#40;:preconds op&amp;#41;&amp;#41;
    &amp;#40;when-not &amp;#40;already-achieved? &amp;#40;:add-list op&amp;#41;&amp;#41;
      &amp;#40;reset! state &amp;#40;clojure.set/difference &amp;#40;set @state&amp;#41; &amp;#40;:del-list op&amp;#41;&amp;#41;&amp;#41;
      &amp;#40;reset! state &amp;#40;clojure.set/union &amp;#40;set @state&amp;#41; &amp;#40;:add-list op&amp;#41;&amp;#41;&amp;#41;
      &amp;#40;println &amp;quot;Executing&amp;quot; &amp;#40;:action op&amp;#41;&amp;#41;&amp;#41;
    true&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This leads to:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;;; =&amp;gt; Executing :buying-cake
;;    Executing :eating-cake
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, there are various other problems that can be solved.  Norvig wants me to introduce a GPS that does: pattern matching; solves the problem of &quot;leaping before you look&quot; (e.g., when a subgoal is &lt;code&gt;:jump-of-cliff&lt;/code&gt; GPS has already jumped and cannot go back if it turns out to be a bad idea); can reorder goals; identifies problems that cannot be solved with reordering goals (&quot;Sussman anomaly&quot;), and solves mazes. I decided to only look at some solutions, and not implement them myself.&lt;/p&gt;&lt;p&gt;If you want to know more you can view Norvig's source code for GPS that solves some of these problems &lt;a href='https://norvig.com/paip/gps.lisp'&gt;at Norvig's website&lt;/a&gt;. More about the history and problems of the GPS can be found at &lt;a href='https://ai-su13.artifice.cc/gps.html'&gt;General Problem Solver (GPS)&lt;/a&gt;&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Sat, 17 Sep 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-08-22-paip-chapter3/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-08-22-paip-chapter3/
</link>
<title>
PAIP in Clojure Chapter 3
</title>
<description>
&lt;p&gt;This is the chapter of &lt;a href='https://amzn.to/29CsgBt'&gt;&lt;em&gt;Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp&lt;/em&gt;&lt;/a&gt; (PAIP) that dives into Common Lisp syntax.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://amzn.to/29CsgBt&quot;&gt;&lt;img src=&quot;https://images-na.ssl-images-amazon.com/images/I/516h5FydqNL.&lt;i&gt;SX359&lt;/i&gt;BO1,204,203,200_.jpg&quot;&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;summary&amp;#95;for&amp;#95;chapter&amp;#95;3:&amp;#95;overview&amp;#95;of&amp;#95;lisp&quot;&gt;&lt;/a&gt;Summary for Chapter 3: Overview of Lisp&lt;/h2&gt;&lt;p&gt;The chapter starts with a quote by Guy L. Steele, Jr.:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;No doubt about it. Common Lisp is a &lt;/em&gt;big&lt;em&gt; language&lt;/em&gt;. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;There is a lot to Common Lisp. In this chapter Norvig shows us the subset of Lisp he uses in his book.&lt;/p&gt;&lt;p&gt;There are six maxims every programmer should know about:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Be specific. (E.g., use &lt;code&gt;when&lt;/code&gt; instead of &lt;code&gt;if&lt;/code&gt; if there is only one clause.)&lt;/li&gt;&lt;li&gt;Use abstractions. (E.g., provide a &lt;code&gt;first-name&lt;/code&gt; method when dealing with a list of names.)&lt;/li&gt;&lt;li&gt;Be concise.&lt;/li&gt;&lt;li&gt;Use the provided tools.&lt;/li&gt;&lt;li&gt;Don't be obscure.&lt;/li&gt;&lt;li&gt;Be consistent. (Sometimes principles are in conflict with each other, then choose one and stick with it.)&lt;/li&gt;&lt;/ul&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.1&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.1 [m]&lt;/h3&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;let &amp;#91;x 6
      y &amp;#40;&amp;#42; x x&amp;#41;&amp;#93;
  &amp;#40;+ x y&amp;#41;&amp;#41; ; =&amp;gt; 42
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;em&gt;Show a &lt;code&gt;lambda&lt;/code&gt; expression that is equivalent to the above &lt;code&gt;let&amp;#42;&lt;/code&gt; expression. You may need more than one &lt;code&gt;lambda&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;&amp;#40;fn &amp;#91;x&amp;#93;
   &amp;#40;&amp;#40;fn &amp;#91;y&amp;#93; &amp;#40;+ x y&amp;#41;&amp;#41;
    &amp;#40;&amp;#42; x x&amp;#41;&amp;#41;&amp;#41;
 6&amp;#41; ; =&amp;gt; 42
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.2&amp;#95;[s]&quot;&gt;&lt;/a&gt;Exercise 3.2 [s]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;The function &lt;code&gt;cons&lt;/code&gt; can be seen as a special case of one of the other functions listed previously. Which one?&lt;/em&gt;&lt;/p&gt;&lt;p&gt;&lt;a href='https://clojuredocs.org/clojure.core/list*'&gt;&lt;code&gt;list&amp;#42;&lt;/code&gt;&lt;/a&gt;. See:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;= &amp;#40;list&amp;#42; 1 '&amp;#40;2 3 4&amp;#41;&amp;#41; 
   &amp;#40;cons 1 '&amp;#40;2 3 4&amp;#41;&amp;#41;&amp;#41; ; =&amp;gt; true
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.3&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.3 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a function that will print an expression in dotted pair notation. Use the built-in function &lt;code&gt;princ&lt;/code&gt; to print each component of the expression.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Note: &lt;code&gt;princ&lt;/code&gt; prints suitable output without escape characters and binds some values to special Common Lisp parameters. I use Clojure's &lt;code&gt;print&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Dotted pair notation is used in Lisps to show we are dealing with an &lt;em&gt;improper&lt;/em&gt; list: a linked list where the second element of a cell is not a list. This is notated with a dotted pair. E.g., &lt;code&gt;&amp;#40;cons 1 2&amp;#41; ; =&amp;gt; '&amp;#40;1 . 2&amp;#41;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Clojure has no dotted pair notation since it avoids the linked list data structure and uses the abstraction of the sequence. See &lt;a href='https: //clojure. org/reference/sequences'&gt;sequences&lt;/a&gt;:&lt;blockquote&gt;&lt;p&gt;A seq is a logical list, and unlike most Lisps where the list is represented by a concrete, 2-slot structure, Clojure uses the ISeq interface to allow many data structures to provide access to their elements as sequences.  &lt;/p&gt;&lt;/blockquote&gt;For a list (special type of sequence) we can introduce dotted pair notation. To do so we need a method that can check for elements that have a single value (e.g., 1, :a). Elements which are therefore not a sequence.&lt;/p&gt;&lt;p&gt;I used the following method from an &lt;a href='https://www.stackoverflow.com/questions/11782534/am-i-using-atom-wrong-or-there-is-something-else#11783268&quot;'&gt;answer on Stack Overflow&lt;/a&gt; to check if a method is single-valued (or an &lt;code&gt;atom&lt;/code&gt; in other Lisps than Clojure).&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn single-valued?
  &amp;quot;Checks if value is single-valued.&amp;quot;
  &amp;#91;x&amp;#93;
  &amp;#40;not &amp;#40;or &amp;#40;nil? x&amp;#41;
           &amp;#40;.. x getClass isArray&amp;#41;
           &amp;#40;some #&amp;#40;instance? % x&amp;#41; &amp;#91;clojure.lang.Counted
                                   clojure.lang.IPersistentCollection
                                   java.util.Collection
                                   java.util.Map&amp;#93;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next we can create a case analysis and recursively generate a dotted-pair representation of a sequence.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;declare create-dotted-pair&amp;#41;
&amp;#40;defn create-dotted-pair-rest
  &amp;quot;Creates dotted pair string representation for the rest of a list.&amp;quot;
  &amp;#91;lst&amp;#93;
  &amp;#40;str &amp;quot; . &amp;quot; &amp;#40;create-dotted-pair lst&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn create-dotted-pair
  &amp;quot;Creates dotted-pair string representation of list.&amp;quot;
  &amp;#91;lst&amp;#93;
  &amp;#40;cond &amp;#40;single-valued? lst&amp;#41; &amp;#40;str lst&amp;#41;
        &amp;#40;empty? lst&amp;#41; &amp;#40;str &amp;quot;'&amp;#40;&amp;#41;&amp;quot;&amp;#41;
        &amp;#40;seq? lst&amp;#41; &amp;#40;str &amp;quot;&amp;#40;&amp;quot;
                        &amp;#40;create-dotted-pair &amp;#40;first lst&amp;#41;&amp;#41;
                        &amp;#40;create-dotted-pair-rest &amp;#40;rest lst&amp;#41;&amp;#41;
                        &amp;quot;&amp;#41;&amp;quot;&amp;#41;
        :else &amp;#40;str lst&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn print-dotted-pair
  &amp;quot;Prints dotted-pair string representation of list.&amp;quot;
  &amp;#91;lst&amp;#93;
  &amp;#40;print &amp;#40;create-dotted-pair lst&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This works as follows for a list created by a chain of cons cells, the shorter notation for a list, and for a nested list:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;print-dotted-pair &amp;#40;cons 1 &amp;#40;cons 2 &amp;#40;cons 3 &amp;#40;cons 4 '&amp;#40;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
; =&amp;gt; &amp;#40;1 . &amp;#40;2 . &amp;#40;3 . &amp;#40;4 . '&amp;#40;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&amp;#40;print-dotted-pair '&amp;#40;1 2 3 4&amp;#41;&amp;#41;
; =&amp;gt; &amp;#40;1 . &amp;#40;2 . &amp;#40;3 . &amp;#40;4 . '&amp;#40;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&amp;#40;print-dotted-pair '&amp;#40;1 2 &amp;#40;3 4&amp;#41;&amp;#41;&amp;#41;
; =&amp;gt; &amp;#40;1 . &amp;#40;2 . &amp;#40;&amp;#40;3 . &amp;#40;4 . '&amp;#40;&amp;#41;&amp;#41;&amp;#41; . '&amp;#40;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.4&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.4 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a function that, like the regular &lt;code&gt;print&lt;/code&gt; function, will print an expression in dotted pair notation when necessary but will use normal list notation when possible.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Dotted pair notation is only necessary when the &lt;code&gt;rest&lt;/code&gt; of a list is not a list. To implement this we have to make changes to the &lt;code&gt;create-dotted-pair-rest&lt;/code&gt; method. Unfortunately it is impossible to create an improper list with native Clojure data structures.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;cons 2 3&amp;#41; ; =&amp;gt; IllegalArgumentException &amp;#40;because 3 is not a sequence&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This makes it impossible to write a test without implementing a linked list data structure in Clojure (like Max Countryman &lt;a href='https://macromancy.com/2014/01/16/data-structures-clojure-singly-linked-list.html'&gt;did&lt;/a&gt;). Therefore I'll skip this exercise.&lt;/p&gt;&lt;p&gt;Now the first hard exercise:&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.5&amp;#95;[h]&quot;&gt;&lt;/a&gt;Exercise 3.5 [h]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;(Exercise in altering structure.) Write a program that will play the role of guesser in the game Twenty Questions. The user of the program will have in mind any type of thing. The program will ask questions of the user, which must be answered yes or no, or &quot;it&quot; when the program has guessed it. If the program runs out of guesses, it gives up and asks the user what &quot;it&quot; was. At first the program will not play well, but each time it plays, it will remember the user's replies and use them for subsequent guesses.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;The idea seems to be that the program has a tree of questions and remembers the answer for each node.&lt;/p&gt;&lt;p&gt;To solve it we need state. For mutable state we create a map which we hold in an &lt;a href='https://clojure.org/reference/atoms'&gt;&lt;code&gt;atom&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I use the following map to build a tree of questions and answers:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def questions-and-answers
  &amp;quot;Questions and answers database atom.
  Keywords are used to traverse the tree.
  An answer needs to be non-existent &amp;#40;nil&amp;#41; or in the form of a string.&amp;quot;
  &amp;#40;atom
   {:is&amp;#95;it&amp;#95;a&amp;#95;programming&amp;#95;language?
    {:yes
     {:is&amp;#95;it&amp;#95;statically&amp;#95;typed?
      {:yes
       nil
       :no
       nil}}
     :no
     {:ca&amp;#95;va?
      {:yes
       nil
       :no
       nil}}}}&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The program could be made more interesting if it was possible to add new questions and answers. This way the database of questions and answers can keep growing. For now, we just ask the questions and update if the user has an answer.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn get-remaining
  &amp;quot;Gets the remaining questions and answers from the questions-and-answers database.
  previous should be a vector of the previous questions and answers.&amp;quot;
  &amp;#91;previous&amp;#93;
  &amp;#40;if &amp;#40;empty? previous&amp;#41; @questions-and-answers
      &amp;#40;get-in @questions-and-answers previous&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn get-next-question
  &amp;quot;Gets the next question from questions-and-answers
  previous should be a vector of the previous questions and answers.&amp;quot;
  &amp;#91;previous&amp;#93;
  &amp;#40;-&amp;gt; previous get-remaining ffirst&amp;#41;&amp;#41;

&amp;#40;defn further-questions?
  &amp;quot;True if there is an answer for a question. False if not.&amp;quot;
  &amp;#91;previous&amp;#93;
  &amp;#40;if &amp;#40;empty? previous&amp;#41; true
      &amp;#40;not &amp;#40;nil? &amp;#40;get-remaining previous&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn found-answer?
  &amp;quot;True if we have found the answer.&amp;quot;
  &amp;#91;previous&amp;#93;
  &amp;#40;string? &amp;#40;get-remaining previous&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn set-answer!
  &amp;quot;Sets the answer to the value provided.
  previous should be a vector of the previous questions and answers.&amp;quot;
  &amp;#91;previous answer&amp;#93;
  &amp;#40;swap! questions-and-answers assoc-in previous answer&amp;#41;&amp;#41;

&amp;#40;defn key-&amp;gt;string
  &amp;quot;Create a string of the answer of question key.&amp;quot;
  &amp;#91;key&amp;#93;
  &amp;#40;-&amp;gt; &amp;#40;name key&amp;#41; &amp;#40;clojure.string/replace &amp;quot;&amp;#95;&amp;quot; &amp;quot; &amp;quot;&amp;#41; clojure.string/capitalize&amp;#41;&amp;#41;

&amp;#40;defn string-&amp;gt;key
  &amp;quot;Create a key of the answer string.&amp;quot;
  &amp;#91;answer&amp;#93;
  &amp;#40;-&amp;gt; answer &amp;#40;clojure.string/replace &amp;quot; &amp;quot; &amp;quot;&amp;#95;&amp;quot;&amp;#41; clojure.string/lower-case keyword&amp;#41;&amp;#41;

&amp;#40;defn driver-loop
  &amp;quot;Asks the questions, updates the answers.
  previous is vector containing the previous questions.&amp;quot;
  &amp;#40;&amp;#91;&amp;#93; &amp;#40;driver-loop &amp;#91;&amp;#93;&amp;#41;&amp;#41; ; Start with no previous provided answers.
  &amp;#40;&amp;#91;previous&amp;#93;
   &amp;#40;let &amp;#91;question &amp;#40;get-next-question previous&amp;#41;
         ask-it &amp;#40;println &amp;#40;key-&amp;gt;string question&amp;#41;&amp;#41; ; ask-it is dummy variable to not create nested lets
         answer &amp;#40;read&amp;#41;
         print-answer &amp;#40;println answer&amp;#41; ; dummy, idem
         previous &amp;#40;conj previous question &amp;#40;string-&amp;gt;key answer&amp;#41;&amp;#41;&amp;#93;
     &amp;#40;cond &amp;#40;found-answer? previous&amp;#41;
           &amp;#40;let &amp;#91;found-answer &amp;#40;get-remaining previous&amp;#41;&amp;#93;
             &amp;#40;println &amp;#40;str &amp;quot;The answer is: &amp;quot; found-answer&amp;#41;&amp;#41;&amp;#41;
           &amp;#40;not &amp;#40;further-questions? previous&amp;#41;&amp;#41;
           &amp;#40;do &amp;#40;println &amp;quot;What was it?&amp;quot;&amp;#41;
               &amp;#40;let &amp;#91;given-answer &amp;#40;str &amp;#40;read&amp;#41;&amp;#41;&amp;#93;
                 &amp;#40;println given-answer&amp;#41;
                 &amp;#40;set-answer! previous given-answer&amp;#41;
                 &amp;#40;println &amp;quot;Thank you.&amp;quot;&amp;#41;&amp;#41;&amp;#41;
           :else &amp;#40;recur previous&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;

; &amp;#40;driver-loop&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Usage of the program looks like this:&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://i.imgur.com/JDVnLUs.png&quot; alt=&quot;Interacting with the program via the REPL.&quot;/&gt;&lt;/p&gt;&lt;p&gt;The node in the tree is updated after an answer is given. The next time the same sequence of questions are answered the program responds with the answer the user added earlier. The representation is shown by dereferencing the atom.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.6&amp;#95;[h]&quot;&gt;&lt;/a&gt;Exercise 3.6 [h]&lt;/h3&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def a 'global-a&amp;#41;
&amp;#40;def &amp;#94;:dynamic &amp;#42;b&amp;#42; 'global-b&amp;#41;
&amp;#40;def f &amp;#40;fn &amp;#91;&amp;#93; &amp;#42;b&amp;#42;&amp;#41;&amp;#41;

&amp;#40;let &amp;#91;a   'local-a
      &amp;#42;b&amp;#42; 'local-b&amp;#93;
  &amp;#40;list a &amp;#42;b&amp;#42; &amp;#40;f&amp;#41; &amp;#40;var-get #'a&amp;#41; &amp;#40;var-get #'&amp;#42;b&amp;#42;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;em&gt;Given the initialization for the lexical variable a and the special variable &amp;#42;b&amp;#42; above, what will be the value of the 1st form?&lt;/em&gt;&lt;/p&gt;&lt;p&gt;This returns &lt;code&gt;&amp;#40;local-a local-b global-b global-a global-b&amp;#41;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;I translated the Common Lisp example from the book to Clojure. That example had different behavior.  I hoped to see the dynamic scoping at work in &lt;code&gt;&amp;#40;var-get #'&amp;#42;b&amp;#42;&amp;#41;&lt;/code&gt; so that the shadowed &lt;code&gt;&amp;#42;b&amp;#42;&lt;/code&gt; was returned in the second position. I will probably figure out later how to do this.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.7&amp;#95;[s]&quot;&gt;&lt;/a&gt;Exercise 3.7 [s]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Why do you think the leftmost of two keys is the one that counts, rather than the rightmost?&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Quicker search to argument list and easier to cons up new value to the beginning of a list (in Common Lisp). The latter is not the case in Clojure with its vector argument lists.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.8&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.8 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Some versions of  Kyoto Common Lisp (KCL) have a bug wherein they use the rightmost value when more than one keyword/value pair is specified for the same keyword. Change the definition of find-all so that it works in KCL.&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn llast
  &amp;quot;Gets second to last value.&amp;quot;
  &amp;#91;coll&amp;#93;
  &amp;#40;-&amp;gt; coll butlast last&amp;#41;&amp;#41;

&amp;#40;defn get-value
  &amp;quot;Finds the value for a key from right to left. Returns value or nil if key not found.&amp;quot;
  &amp;#91;key coll&amp;#93;
  &amp;#40;cond &amp;#40;&amp;lt; &amp;#40;count coll&amp;#41; 2&amp;#41; nil
        &amp;#40;= key &amp;#40;llast coll&amp;#41;&amp;#41; &amp;#40;last coll&amp;#41;
        :else &amp;#40;recur key &amp;#40;drop-last 2 coll&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn find-all
  &amp;quot;Find all those elements of sequence that match item, according to the keywords.
  Doesn't alter sequence.&amp;quot;
  &amp;#91;item coll &amp;amp; options&amp;#93;
  &amp;#40;let &amp;#91;test-fn &amp;#40;or &amp;#40;get-value :test-fn options&amp;#41; '=&amp;#41;
        key-fn &amp;#40;or &amp;#40;get-value :key-fn options&amp;#41; 'identity&amp;#41;
        result &amp;#40;remove #&amp;#40;not &amp;#40;test-fn % item&amp;#41;&amp;#41; coll&amp;#41;
        final-result &amp;#40;map key-fn result&amp;#41;&amp;#93;
    final-result&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;&amp;#40;find-all 1 '&amp;#40;1 1 2 3 4 5 6&amp;#41; :test-fn = :key-fn inc :test-fn &amp;gt;&amp;#41;&lt;/code&gt; returns &lt;code&gt;'&amp;#40;3 4 5 6 7&amp;#41;&lt;/code&gt;. The rightmost &lt;code&gt;key-fn:&lt;/code&gt; is used (&lt;code&gt;&amp;gt;&lt;/code&gt;).&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.9&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.9 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a version of 1ength using the function reduce.&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn length
  &amp;quot;Finds the length of coll using the function reduce.&amp;quot;
  &amp;#91;coll&amp;#93;
  &amp;#40;reduce &amp;#40;fn &amp;#91;acc e&amp;#93; &amp;#40;inc acc&amp;#41;&amp;#41; coll&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.10&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.10 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Use a reference manual or describe to figure out what the functions lcm and nreconc do.&lt;/em&gt; &lt;code&gt;lcm&lt;/code&gt; finds the lowest common denominator and &lt;code&gt;nreconc&lt;/code&gt; does some sort of reversing. The first is available in Clojure contrib library, the second is not available in Clojure.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.11&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.11 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;There is a built-in Common Lisp function that, given a key, a value, and an association list, returns a new association list that is extended to include the key/value pair. What is the name of this function?&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Clojure's assoc does this:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;assoc {:other-key 'other-value} :key 'value&amp;#41; ; =&amp;gt; {:other-key other-value, :key value}
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;3.12&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 3.12 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a single expression using format that will take a list of words and print them as a sentence, with the first word capitalized and a period after the last word. You will have to consult a reference to learn new format directives.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;I think this cannot be done by format. It can for example be done via &lt;code&gt;clojure.string&lt;/code&gt; methods:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn as-sentence
  &amp;quot;Takes a list of words and creates a sentence with first word capitalized and period at end.&amp;quot;
  &amp;#91;word-list&amp;#93;
  &amp;#40;str &amp;#40;clojure.string/capitalize &amp;#40;clojure.string/join &amp;quot; &amp;quot; word-list&amp;#41;&amp;#41; &amp;quot;.&amp;quot;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That's it. In Chapter 4 we will built a General Problem Solver.&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Mon, 22 Aug 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-08-11-paip-chapter2/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-08-11-paip-chapter2/
</link>
<title>
PAIP in Clojure Chapter 2
</title>
<description>
&lt;p&gt;After some vacation and working on other things I finally got round to Chapter 2 of &lt;a href='https://amzn.to/29CsgBt'&gt;&lt;em&gt;Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp&lt;/em&gt;&lt;/a&gt; (PAIP).&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://amzn.to/29CsgBt&quot;&gt;&lt;img src=&quot;https://images-na.ssl-images-amazon.com/images/I/516h5FydqNL.&lt;i&gt;SX359&lt;/i&gt;BO1,204,203,200_.jpg&quot;&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;summary&amp;#95;for&amp;#95;chapter&amp;#95;2:&amp;#95;a&amp;#95;simple&amp;#95;lisp&amp;#95;program&quot;&gt;&lt;/a&gt;Summary for Chapter 2: A Simple Lisp Program&lt;/h2&gt;&lt;p&gt;The chapter starts with a quote by the Italian royal historiographer Giovanni Battista Vico (1668-1744):&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;Certum quod factum.&lt;/em&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;For those that do not speak Latin, this is the rough translation: &quot;&lt;strong&gt;One is certain only of what one builds.&lt;/strong&gt;&quot;&lt;/p&gt;&lt;p&gt;In this chapter we build a more elaborate Lisp program and therefore live a more certain life. The program we will build generates random English sentences. In fancy terms we call the program &lt;em&gt;generative syntax&lt;/em&gt; for a &lt;em&gt;context-free phrase-structure grammar&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;The original Common Lisp code from the book can be viewed &lt;a href='https://norvig.com/paip/simple.lisp'&gt;here&lt;/a&gt;. First I translated this code to Clojure below.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;ns paip.simple
  &amp;#40;:gen-class&amp;#41;&amp;#41;

; Clojure translation of the Common Lisp code in Chapter 2.
; Original: https://norvig.com/paip/simple.lisp

;;; Code translated from Paradigms of Artificial Intelligence Programming
;;; Copyright &amp;#40;c&amp;#41; 1991 Peter Norvig

&amp;#40;defn one-of
  &amp;quot;Pick one element of set, and make a list of it.&amp;quot;
  &amp;#91;set&amp;#93;
  &amp;#40;-&amp;gt; set rand-nth list&amp;#41;&amp;#41;

&amp;#40;def simple-grammar
  &amp;quot;A grammar for a trivial subset of English&amp;quot;
  {:sentence    &amp;#91;&amp;#91;:noun-phrase :verb-phrase&amp;#93;&amp;#93;
   :noun-phrase &amp;#91;&amp;#91;:article :noun&amp;#93;&amp;#93;
   :verb-phrase &amp;#91;&amp;#91;:verb :noun-phrase&amp;#93;&amp;#93;
   :article     #{&amp;quot;the&amp;quot; &amp;quot;a&amp;quot;}
   :noun        #{&amp;quot;man&amp;quot; &amp;quot;ball&amp;quot; &amp;quot;woman&amp;quot; &amp;quot;table&amp;quot;}
   :verb        #{&amp;quot;hit&amp;quot; &amp;quot;took&amp;quot; &amp;quot;saw&amp;quot; &amp;quot;liked&amp;quot;}}&amp;#41;

&amp;#40;def bigger-grammar
  &amp;quot;A somewhat bigger grammar for a trivial subset of English&amp;quot;
  {:sentence    &amp;#91;&amp;#91;:noun-phrase :verb-phrase&amp;#93;&amp;#93;
   :noun-phrase &amp;#91;&amp;#91;:article :adj&amp;#42; :noun :pp&amp;#42;&amp;#93; &amp;#91;:name&amp;#93; &amp;#91;:pronoun&amp;#93;&amp;#93;
   :verb-phrase &amp;#91;&amp;#91;:verb :noun-phrase :pp&amp;#42;&amp;#93;&amp;#93;
   :pp&amp;#42;         &amp;#91;&amp;#91;&amp;#93; &amp;#91;:pp :pp&amp;#42;&amp;#93;&amp;#93;
   :adj&amp;#42;        &amp;#91;&amp;#91;&amp;#93; &amp;#91;:adj :adj&amp;#42;&amp;#93;&amp;#93;
   :pp          &amp;#91;&amp;#91;:prep :noun-phrase&amp;#93;&amp;#93;
   :prep        #{&amp;quot;to&amp;quot; &amp;quot;in&amp;quot; &amp;quot;by&amp;quot; &amp;quot;with&amp;quot; &amp;quot;on&amp;quot;}
   :adj         #{&amp;quot;big&amp;quot; &amp;quot;little&amp;quot; &amp;quot;blue&amp;quot; &amp;quot;green&amp;quot; &amp;quot;adiabatic&amp;quot;}
   :article     #{&amp;quot;the&amp;quot; &amp;quot;a&amp;quot;}
   :name        #{&amp;quot;Pat&amp;quot; &amp;quot;Kim&amp;quot; &amp;quot;Lee&amp;quot; &amp;quot;Terry&amp;quot; &amp;quot;Robin&amp;quot;}
   :noun        #{&amp;quot;man&amp;quot; &amp;quot;ball&amp;quot; &amp;quot;woman&amp;quot; &amp;quot;table&amp;quot;}
   :verb        #{&amp;quot;hit&amp;quot; &amp;quot;took&amp;quot; &amp;quot;saw&amp;quot; &amp;quot;liked&amp;quot;}
   :pronoun     #{&amp;quot;he&amp;quot; &amp;quot;she&amp;quot; &amp;quot;it&amp;quot; &amp;quot;these&amp;quot; &amp;quot;those&amp;quot; &amp;quot;that&amp;quot;}}&amp;#41;

;;; ==============================

&amp;#40;def grammar
  &amp;quot;The grammar used by generate.  Initially, this is
  simple-grammar, but we can switch to other grammars.&amp;quot;
  simple-grammar&amp;#41;

;;; ==============================

&amp;#40;defn rule-lhs
  &amp;quot;The left hand side of a rule.&amp;quot;
  &amp;#91;rule&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; rule keys &amp;#40;apply concat&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn rule-rhs
  &amp;quot;The right hand side of a rule.&amp;quot;
  &amp;#91;rule&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; rule vals &amp;#40;apply concat&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn rewrites
  &amp;quot;Return a list of the possible rewrites for this category.&amp;quot;
  &amp;#91;category&amp;#93;
  &amp;#40;rule-rhs &amp;#40;select-keys grammar &amp;#91;category&amp;#93;&amp;#41;&amp;#41;&amp;#41;

;;; ==============================

&amp;#40;defn generate
  &amp;quot;Generate a random sentence or phrase&amp;quot;
  &amp;#91;phrase&amp;#93;
  &amp;#40;cond &amp;#40;vector? phrase&amp;#41;
        &amp;#40;mapcat generate phrase&amp;#41;
        &amp;#40;seq &amp;#40;rewrites phrase&amp;#41;&amp;#41;
        &amp;#40;generate &amp;#40;rand-nth &amp;#40;rewrites phrase&amp;#41;&amp;#41;&amp;#41;
        :else
        &amp;#40;list phrase&amp;#41;&amp;#41;&amp;#41;

&amp;#40;generate :sentence&amp;#41;
; =&amp;gt; &amp;#40;One example&amp;#41;
;    &amp;#40;&amp;quot;Kim&amp;quot; &amp;quot;saw&amp;quot; &amp;quot;Pat&amp;quot;&amp;#41;

;;; ==============================

&amp;#40;defn generate-tree
  &amp;quot;Generate a random sentence or phrase,
  with a complete parse tree.&amp;quot;
  &amp;#91;phrase&amp;#93;
  &amp;#40;cond &amp;#40;vector? phrase&amp;#41;
        &amp;#40;map generate-tree phrase&amp;#41;
        &amp;#40;seq &amp;#40;rewrites phrase&amp;#41;&amp;#41;
        &amp;#40;cons phrase
              &amp;#40;generate-tree &amp;#40;rand-nth &amp;#40;rewrites phrase&amp;#41;&amp;#41;&amp;#41;&amp;#41;
        :else &amp;#40;list phrase&amp;#41;&amp;#41;&amp;#41;

&amp;#40;generate-tree :sentence&amp;#41;
; =&amp;gt; &amp;#40;one example&amp;#41;
;    &amp;#40;:sentence &amp;#40;:noun-phrase &amp;#40;:Article &amp;quot;the&amp;quot;&amp;#41;
;                             &amp;#40;:Adj&amp;#42;&amp;#41;
;                             &amp;#40;:Noun &amp;quot;ball&amp;quot;&amp;#41;
;                             &amp;#40;:PP&amp;#42;&amp;#41;&amp;#41;
;               &amp;#40;:verb-phrase &amp;#40;:Verb &amp;quot;liked&amp;quot;&amp;#41;
;                             &amp;#40;:noun-phrase
;                              &amp;#40;:Name &amp;quot;Robin&amp;quot;&amp;#41;&amp;#41;
;                             &amp;#40;:PP&amp;#42;&amp;#41;&amp;#41;&amp;#41;

;;;; ==============================

&amp;#40;defn combine-all
  &amp;quot;Return a list of lists formed by appending a y to an x.
  E.g., &amp;#40;combine-all '&amp;#40;&amp;#40;a&amp;#41; &amp;#40;b&amp;#41;&amp;#41; '&amp;#40;&amp;#40;1&amp;#41; &amp;#40;2&amp;#41;&amp;#41;&amp;#41;
  -&amp;gt; &amp;#40;&amp;#40;A 1&amp;#41; &amp;#40;B 1&amp;#41; &amp;#40;A 2&amp;#41; &amp;#40;B 2&amp;#41;&amp;#41;.&amp;quot;
  &amp;#91;xlist ylist&amp;#93;
  &amp;#40;mapcat &amp;#40;fn &amp;#91;y&amp;#93;
            &amp;#40;map &amp;#40;fn &amp;#91;x&amp;#93; &amp;#40;concat x y&amp;#41;&amp;#41; xlist&amp;#41;&amp;#41;
          ylist&amp;#41;&amp;#41;

;; TODO: There is a bug in generate-all. For sentences that are constructed out of noun-phrase
;;       or verb-phrases the resulting sentences are displayed in characters.
&amp;#40;defn generate-all
  &amp;quot;Generate a list of all possible expansions of this phrase.
   Only works for non-recursive grammars.&amp;quot;
  &amp;#91;phrase&amp;#93;
  &amp;#40;cond &amp;#40;vector? phrase&amp;#41;
        &amp;#40;combine-all &amp;#40;generate-all &amp;#40;first phrase&amp;#41;&amp;#41;
                     &amp;#40;mapcat generate-all &amp;#40;rest phrase&amp;#41;&amp;#41;&amp;#41;
        &amp;#40;seq &amp;#40;rewrites phrase&amp;#41;&amp;#41;
        &amp;#40;mapcat generate-all &amp;#40;rewrites phrase&amp;#41;&amp;#41;
        :else
        &amp;#40;list phrase&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The translation between the different built-in methods and difference in behavior between Clojure and Common Lisp cost me quite some time, but it was worth it: I know more about Clojure than I did before, and I have a working sentence generator.&lt;/p&gt;&lt;p&gt;The lessons from the chapter are:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;code&gt;data-driven&lt;/code&gt; programming (where data drives what a program does next) makes it easy to extend functionality of a program just by adding new input data.In the parser above &lt;code&gt;simple-grammar&lt;/code&gt; and &lt;code&gt;bigger-grammar&lt;/code&gt; both work without having the program to change).&lt;/li&gt;&lt;li&gt;Code is also data, in what Norvig calls the one-data/multiple-program approach we can create slightly different versions of the same program which accomplish different tasks using the same data. &lt;code&gt;generate-tree&lt;/code&gt; and &lt;code&gt;generate-all&lt;/code&gt; programs are example of one-data/multiple-program: slight changes lead to different related functionality.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;code&gt;generate-all&lt;/code&gt; is not fully functional since somehow the words are cut down into characters when they are created by a &lt;code&gt;verb-phrase&lt;/code&gt; or &lt;code&gt;noun-phrase&lt;/code&gt;. Perhaps that problem will somehow be solved in the exercises.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;exercises&quot;&gt;&lt;/a&gt;Exercises&lt;/h2&gt;&lt;p&gt;The source code with unit tests is available at &lt;a href='https://www.github.com/transducer/paip'&gt;https://www.github.com/transducer/paip&lt;/a&gt;.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;2.1&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 2.1 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a version of &lt;code&gt;generate&lt;/code&gt; that uses &lt;code&gt;cond&lt;/code&gt; but avoids calling &lt;code&gt;rewrites&lt;/code&gt; twice.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Instead of checking it the rewrites are non-empty, in our way of defining the grammar (using the native Clojure map) we can perform the same check by checking if the phrase is a keyword:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn generate
  &amp;quot;Generate a random sentence or phrase&amp;quot;
  &amp;#91;phrase&amp;#93;
  &amp;#40;cond &amp;#40;vector? phrase&amp;#41; &amp;#40;mapcat generate phrase&amp;#41;
        &amp;#40;keyword? phrase&amp;#41; &amp;#40;generate &amp;#40;rand-nth &amp;#40;rewrites phrase&amp;#41;&amp;#41;&amp;#41;
        :else &amp;#40;list phrase&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;2.2&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 2.2 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a version of &lt;code&gt;generate&lt;/code&gt; that explicitly differentiates between terminal symbols (those with no rewrite rules) and non-terminal symbols.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Just extract a method and provide it with a meaningful name.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn non-terminal?
  &amp;quot;Determines if a phrase is non terminal.&amp;quot;
  &amp;#91;phrase&amp;#93;
  &amp;#40;keyword? phrase&amp;#41;&amp;#41;

&amp;#40;defn generate
  &amp;quot;Generate a random sentence or phrase&amp;quot;
  &amp;#91;phrase&amp;#93;
  &amp;#40;cond &amp;#40;vector? phrase&amp;#41; &amp;#40;mapcat generate phrase&amp;#41;
        &amp;#40;non-terminal? phrase&amp;#41; &amp;#40;generate &amp;#40;rand-nth &amp;#40;rewrites phrase&amp;#41;&amp;#41;&amp;#41;
        :else &amp;#40;list phrase&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;2.3&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 2.3 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a trivial grammer for some other language. This can be a natural language other than English, or perhaps a subset of a computer language.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;A subset of &quot;Clojure&quot;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def simple-clj-grammar
  &amp;quot;A grammar for a trivial subset of Clojure&amp;quot;
  {:code                &amp;#91;&amp;#91;:definition-phrase :function-definition&amp;#93;&amp;#93;
   :definition-phrase   &amp;#91;&amp;#91;:definition :names :docstring&amp;#93;&amp;#93;
   :function-definition &amp;#91;&amp;#91;:library-definitions :parameter-types&amp;#93;&amp;#93;
   :definition          #{&amp;quot;defn&amp;quot;}
   :docstring           #{&amp;quot;wtf?&amp;quot; &amp;quot;TODO&amp;quot;}
   :names               #{&amp;quot;my-method&amp;quot; &amp;quot;awesome?&amp;quot; &amp;quot;change-it!&amp;quot;}
   :library-definitions #{&amp;quot;map&amp;quot; &amp;quot;mapcat&amp;quot; &amp;quot;inc&amp;quot; &amp;quot;dec&amp;quot;}
   :parameter-types     #{&amp;quot;string&amp;quot; &amp;quot;int&amp;quot; &amp;quot;long&amp;quot; &amp;quot;bool&amp;quot;}}&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;2.4&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 2.4 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;One way of describing &lt;code&gt;combine-all&lt;/code&gt; is that it calculates the cross-product of the function &lt;code&gt;append&lt;/code&gt; on the argument lists. Write the higher-order function &lt;code&gt;cross-product&lt;/code&gt;, and define &lt;code&gt;combine-all&lt;/code&gt; in terms of it. The moral is to make your code as general as possible, because you never know what you may want to do with it next.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;It is possible to write cross-product using a &lt;a href='https://clojuredocs.org/clojure.core/for'&gt;for-comprehension&lt;/a&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn cross-product
  &amp;quot;Calculates the cross product.&amp;quot;
  &amp;#91;f coll1 coll2&amp;#93;
  &amp;#40;if &amp;#40;empty? coll1&amp;#41;
    '&amp;#40;&amp;#40;&amp;#41;&amp;#41;
    &amp;#40;for &amp;#91;x coll1
          y coll2&amp;#93;
      &amp;#40;f x y&amp;#41;&amp;#41;&amp;#41;&amp;#41;

&amp;#40;defn combine-all
  &amp;#91;xlist ylist&amp;#93;
  &amp;#40;cross-product concat xlist ylist&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The cross-product function in use:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;cross-product + '&amp;#40;1 2 3&amp;#41; '&amp;#40;10 20 30&amp;#41;&amp;#41;
; =&amp;gt; '&amp;#40;11 21 31
;      12 22 32
;      13 23 33&amp;#41;&amp;#41;&amp;#41;

&amp;#40;cross-product list '&amp;#40;a b&amp;#41; '&amp;#40;1 2&amp;#41;&amp;#41;
; =&amp;gt; '&amp;#40;&amp;#40;a 1&amp;#41; &amp;#40;a 2&amp;#41; &amp;#40;b 1&amp;#41; &amp;#40;b 2&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That was a full day of work. I will start with Chapter 3 tomorrow.&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Thu, 11 Aug 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-07-13-paip-intro/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-07-13-paip-intro/
</link>
<title>
PAIP in Clojure Chapter 1
</title>
<description>
&lt;p&gt;From my parents I received the book &lt;a href='https://amzn.to/29CsgBt'&gt;&lt;em&gt;Paradigms of Artificial Intelligence Programming&lt;/em&gt;&lt;/a&gt; by Peter Norvig for my 28th birthday.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://amzn.to/29CsgBt&quot;&gt;&lt;img src=&quot;https://images-na.ssl-images-amazon.com/images/I/516h5FydqNL.&lt;i&gt;SX359&lt;/i&gt;BO1,204,203,200_.jpg&quot;&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;PAIP is a classic with high standard Common Lisp code to solve problems in artificial intelligence. The coming year I will study this book.&lt;/p&gt;&lt;p&gt;There are 25 chapters and there are 52 weeks till 13 July 2017. This means I have to finish a chapter roughly every two weeks.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;summary&amp;#95;for&amp;#95;chapter&amp;#95;1:&amp;#95;introduction&amp;#95;to&amp;#95;lisp&quot;&gt;&lt;/a&gt;Summary for Chapter 1: Introduction to Lisp&lt;/h2&gt;&lt;p&gt;The chapter starts with a quote by Alan Perlis:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;You think you know when you learn, are more sure&lt;br&gt; when you can write, even more when you can teach,&lt;br&gt; but certain when you can program. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;The rest of the chapter explain the fundamentals of programming in Lisp and why it is awesome.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;exercises&quot;&gt;&lt;/a&gt;Exercises&lt;/h2&gt;&lt;p&gt;I will do a selection of the exercises in this book. I assume that you as a reader have not read the book, so I'll explain the exercises if necessary. The source code with unit tests is available at &lt;a href='https://www.github.com/transducer/paip'&gt;https://www.github.com/transducer/paip&lt;/a&gt;.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;1.1&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 1.1 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Define a version of &lt;code&gt;last-name&lt;/code&gt; that handles &quot;Rex Morgan Md,&quot; &quot;Morton Downey, Jr.,&quot; and whatever other cases you can think of.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;In the book we had a function &lt;code&gt;first-name&lt;/code&gt; to retrieve the first names from a list of names, where a name is a list of strings like &lt;code&gt;&amp;#40;&amp;quot;Robert&amp;quot; &amp;quot;Downey&amp;quot; &amp;quot;Jr.&amp;quot;&amp;#41;&lt;/code&gt;. The &lt;code&gt;first-name&lt;/code&gt; method first checked if the first element of the name existed in the parameter list &lt;code&gt;&amp;#42;titles&amp;#42;&lt;/code&gt;. If it did &lt;code&gt;first-name&lt;/code&gt; invoked itself recursively with the rest of the name.&lt;/p&gt;&lt;p&gt;We have to do the same, but instead of looking for the first element, we have to look for the last. And instead of validating the element does not exist in &lt;code&gt;&amp;#42;titles&amp;#42;&lt;/code&gt;, we look in a parameter called &lt;em&gt;suffixes&lt;/em&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def suffixes '&amp;#40;&amp;quot;Jr.&amp;quot; &amp;quot;Md&amp;quot;&amp;#41;&amp;#41;

&amp;#40;defn last-name
  &amp;quot;Select the last name from a name represented as a list.&amp;quot;
  &amp;#91;name&amp;#93;
  &amp;#40;if &amp;#40;some #&amp;#40;= &amp;#40;last name&amp;#41; %&amp;#41; suffixes&amp;#41;
    &amp;#40;last-name &amp;#40;drop-last name&amp;#41;&amp;#41;
    &amp;#40;last name&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The library functions &lt;code&gt;drop-last&lt;/code&gt; and &lt;code&gt;last&lt;/code&gt; are convenient.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;1.2&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 1.2 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a function to exponentiate, or raise a number to an integer power. For example: (power 3 2) = 3&lt;sup&gt;2&lt;/sup&gt; = 9.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;With the use of an iterative loop:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn power
  &amp;quot;Exponentiate a base to a power&amp;quot;
  &amp;#91;base power&amp;#93;
  &amp;#40;loop &amp;#91;b base
         n power
         result 1&amp;#93;
    &amp;#40;if &amp;#40;= 0 n&amp;#41;
      result
      &amp;#40;recur b &amp;#40;dec n&amp;#41; &amp;#40;&amp;#42; b result&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;1.3&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 1.3 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a function that counts the number of atoms in an expression. For example: &lt;code&gt;&amp;#40;count-atoms '&amp;#40;a &amp;#40;b&amp;#41; c&amp;#41;&amp;#41; = 3&lt;/code&gt;. Notice that there is something of an ambiguity in this: should &lt;code&gt;&amp;#40;a nil c&amp;#41;&lt;/code&gt; count as three atoms, or as two, because it is equivalent to &lt;code&gt;&amp;#40;a &amp;#40;&amp;#41; c&amp;#41;&lt;/code&gt;?&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn count-atoms
  &amp;quot;Counts the number of elements in an expression. nil is considered an atom.
   Clojure does not have true atoms, so better to call this method count-elements&amp;quot;
  &amp;#91;expression&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; expression
       flatten
       count&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;1.4&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 1.4 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a function that counts the number of times an expression occurs anywhere within another expression. Example: &lt;code&gt;&amp;#40;count-anywhere 'a '&amp;#40;a &amp;#40;&amp;#40;a&amp;#41; b&amp;#41; a&amp;#41;&amp;#41; ; =&amp;gt; 3&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn count-anywhere
  &amp;quot;Counts the number of times an expression occurs anywhere within another
   expression&amp;quot;
  &amp;#91;expression-to-search expression&amp;#93;
  &amp;#40;-&amp;gt;&amp;gt; expression
       flatten
       &amp;#40;filter #{expression-to-search}&amp;#41;
       count&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;h3&gt;&lt;a name=&quot;exercise&amp;#95;1.5&amp;#95;[m]&quot;&gt;&lt;/a&gt;Exercise 1.5 [m]&lt;/h3&gt;&lt;p&gt;&lt;em&gt;Write a function to compute the dot product of two sequences of numbers, represented as lists. The dot product is computed by multiplying corresponding elements and then adding up the resulting products. Example:&lt;/em&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;&amp;#40;dot-product '&amp;#40;10 20&amp;#41; '&amp;#40;3 4&amp;#41;&amp;#41; = 10 x 3 + 20 x 4 = 110&lt;/code&gt;&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn dot-product
  &amp;quot;Calculates the dot product. Assuming vectors are of even length and consist of numbers.&amp;quot;
  &amp;#91;coll1 coll2&amp;#93;
  &amp;#40;if &amp;#40;empty? coll1&amp;#41; 0
    &amp;#40;+ &amp;#40;&amp;#42; &amp;#40;first coll1&amp;#41; &amp;#40;first coll2&amp;#41;&amp;#41;
       &amp;#40;dot-product &amp;#40;rest coll1&amp;#41; &amp;#40;rest coll2&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Wed, 13 Jul 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-06-02-petri-net/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-06-02-petri-net/
</link>
<title>
How a Petri net can help you simplify your business logic
</title>
<description>
&lt;p&gt;In enterprise organizations it is bound to occur that different teams are building similar software independently of each other. For example, multiple teams write code which interacts with various services and performs some business logic in a similar manner. The complexity of creating software is usually not in creating components which interacts with external software itself (e.g., connecting with a RESTful API via a service client class). The complexity resides in the means of combination of these various components. I.e. the modeling of the business process (the flow of work through an organization).&lt;/p&gt;&lt;p&gt;A Petri net is a mathematical modeling language which is particularly suited to model business processes. In the foreword of &lt;a href='https://amzn.to/1VzuMhh'&gt;&lt;em&gt;Modeling Business Processes: A Petri Net-Oriented Approach&lt;/em&gt;&lt;/a&gt; by Aalst &amp; Stahl (2011) it is stated that:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Petri nets provide the foundation of the graphical notation and the basic primitives for modeling concurrency, communication, and synchronization. The extension of these basic primitives with data (color) ... makes it possible to model and analyze complex artifacts. (p. iv). &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;To facilitate &lt;strong&gt;flexibility&lt;/strong&gt; in the face of changing requirements, to &lt;strong&gt;encapsulate&lt;/strong&gt; the business rules in one central place, and to possibly tackle the problem of &lt;strong&gt;re-usability&lt;/strong&gt; described above, a Petri net can be used to model a business process. Below I will show an example of using a Petri net using a domain specific language (DSL) which we have started creating at work. From this DSL which describes a business process an event-driven Petri net representation can be generated. All that is left of complex business logic in an application is the need to send the right events (with data) to the Petri net representation.&lt;/p&gt;&lt;p&gt;In this article I will elaborate on Petri nets, the DSL created and an event-driven Petri net representation.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;petri&amp;#95;nets&quot;&gt;&lt;/a&gt;Petri nets&lt;/h2&gt;&lt;p&gt;In 1939 Carl Adam Petri was only 13 years old when he invented the Petri net with the goal of describing a chemical process. A Petri net is a directed bipartite graph consisting of places and transitions, where every place only connects with transitions and every transition only connects with places.&lt;/p&gt;&lt;p&gt;Below a visualization of a Petri net is provided. Transitions are visualized as rectangles and places as circles.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/jOa0nDH.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/jOa0nDH.gif&quot; alt=&quot;Petri net trajectory from Wikipedia&quot; /&gt; &lt;/a&gt; &lt;br/&gt; (Source: &lt;a href='https://en.wikipedia.org/wiki/Petri_net'&gt;Wikipedia&lt;/a&gt;)&lt;/p&gt;&lt;p&gt;In the places tokens can exist (the dots that appear in the image above). Once all in-adjacent places towards a transition are filled, the transition can fire and &lt;em&gt;consume&lt;/em&gt; the tokens, and thereby &lt;em&gt;produce&lt;/em&gt; new tokens in the out-adjacent places out of the transition. Parallelism is supported (e.g., multiple places next to each other coming out of a transition or multiple places leading to one transition). &lt;/p&gt;&lt;p&gt;There are various extensions to the Petri net. A colored Petri net is a special type of Petri net where the tokens can also have data. A colored Petri net is particularly suited for modeling business processes.&lt;/p&gt;&lt;p&gt;Especially in Europe much research has been done on Petri nets and certain properties can be proven about them. It is possible to mathematically reason about reachability (&quot;can we reach a certain state?&quot;), liveness (&quot;can a transition fire?&quot;) and boundedness (&quot;how many tokens can there be?&quot;). Reasoning about such properties is useful for example for:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Showing how much memory or disk space a process will consume.&lt;/li&gt;&lt;li&gt;Checking the validity of a business process.&lt;/li&gt;&lt;li&gt;Analyze bottle necks in the flow.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;By using &lt;a href='https://xml.coverpages.org/PNML200303.pdf'&gt;Petri Net Markup Language&lt;/a&gt; (PNML) to describe the Petri net analysis can be done via existing tools.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;dsl&quot;&gt;&lt;/a&gt;DSL&lt;/h2&gt;&lt;p&gt;When a chef cooks a recipe she combines various ingredients. When certain events happen, or when ingredients are ready, a chef knows what action(s) to execute next. E.g., when a chef receives an event WaterBoiling she knows that she can start cooking the pasta. And once the chef has a knife and tomatoes she will start cutting them. If the chef is skilled, this results in pasta sauce when finished.&lt;/p&gt;&lt;p&gt;In the DSL below a similar recipe can be provided to a chef – only the chef is an execution engine written in Scala. Ingredients do not consist of edible substances but of software components. Actions to be executed are not certain kitchen skills, but instead methods on these software components. The preconditions for these actions are data or events that are provided.&lt;/p&gt;&lt;p&gt;The chef is all that is needed to handle flows through our business process.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;event-driven&amp;#95;petri&amp;#95;net&amp;#95;representation&quot;&gt;&lt;/a&gt;Event-driven Petri net representation&lt;/h2&gt;&lt;p&gt;In the current setup the recipe is represented as a Java map where the keys are the interfaces of the components and the values a representation of the actions. The representation of the action has properties to specify which methods are needed and which preconditions they have. These preconditions are specified as events or data.&lt;/p&gt;&lt;p&gt;Once the chef received the recipe it can start cooking a Petri net topology. The chef &quot;cooks&quot; by using reflection to get all the information out of the recipe and the ingredients. This topology is shared with various states of the Petri net (a state describes in what place which data/tokens are).&lt;/p&gt;&lt;p&gt;The chef can listen for events that are happening. Once it processes an event it knows to which Petri net state it belongs by looking at the process identifier, and it will perform the action specified in the recipe and update the state accordingly with the results.&lt;/p&gt;&lt;p&gt;The Petri net is modeled in-memory via the &lt;a href='https://github.com/merlijn/kagera'&gt;Kagera&lt;/a&gt; library which is maintained by one of my team members at work (who happens to be &lt;em&gt;really&lt;/em&gt; enthusiastic about Petri nets). In the future it will be possible to store the state on disk using &lt;a href='https://cqrs.wikidot.com/doc:event-sourcing'&gt;event sourcing&lt;/a&gt; – with the added benefit that all historical flows can be replayed and analyzed.&lt;/p&gt;&lt;p&gt;The chef has the following abilities:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;It can be provided with real or stub implementations of the ingredients in its constructor.&lt;/li&gt;&lt;li&gt;It must be told what events are used.&lt;/li&gt;&lt;li&gt;It is possible to retrieve all state which belongs to a certain process.&lt;/li&gt;&lt;li&gt;It provides some more methods to get a GraphViz or PNML representation of the recipe for visualization and analysis purposes.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Below we see the interface of the chef:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;class Chef&amp;#40;recipe: Map&amp;#91;Class&amp;#91;&amp;#95;&amp;#93;, Seq&amp;#91;Action&amp;#93;&amp;#93;,
           ingredientImpls: Map&amp;#91;Class&amp;#91;&amp;#95;&amp;#93;, AnyRef&amp;#93;,
           events: Set&amp;#91;Class&amp;#91;&amp;#95;&amp;#93;&amp;#93;&amp;#41; {

  /&amp;#42; Cook the recipe for a specific process id &amp;#42;/
  def cook&amp;#40;processId: UUID&amp;#41;: Unit = /&amp;#42; &amp;#40;...&amp;#41; &amp;#42;/ 

  /&amp;#42; Get all accumulated state from the Petri net marking &amp;#42;/
  def getAccumulatedState&amp;#40;processId: UUID&amp;#41;: Map&amp;#91;String, Optional&amp;#91;Any&amp;#93;&amp;#93; = /&amp;#42; &amp;#40;...&amp;#41; &amp;#42;/ 

  /&amp;#42; Tell the chef an event has happened for a specific process id &amp;#42;/
  def tellEventHappened&amp;#40;processId: UUID, event: AnyRef&amp;#41;: Unit = /&amp;#42; &amp;#40;...&amp;#41; &amp;#42;/ 

  /&amp;#42; Get the GraphViz &amp;#40;graph visualization software&amp;#41; implementation of the recipe &amp;#42;/
  def getVisualRecipe: String = /&amp;#42; &amp;#40;...&amp;#41; &amp;#42;/ 

  /&amp;#42; Get the PNML &amp;#40;Petri Net Modelling Language&amp;#41; representation of the recipe &amp;#42;/
  def getPnmlRecipe: String = /&amp;#42; &amp;#40;...&amp;#41; &amp;#42;/ 
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When &lt;code&gt;getVisualRecipe&lt;/code&gt; is called the following GraphViz visualization of the recipe describing a simple cooking process is returned:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/ZTpcOE5.png&quot;&gt; &lt;img src=&quot;https://i.imgur.com/ZTpcOE5.png&quot; alt=&quot;GraphViz visualization of recipe&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;Here events are modeled as blue diamonds, red circles represent data (places in Petri net terminology), and grey rectangles are the actions on the ingredients (transitions in Petri net terminology).&lt;/p&gt;&lt;p&gt;In the code of your application only the user-facing parts need to be created. Here the chef can be notified by events via the &lt;code&gt;tellEventHappened&lt;/code&gt; method. &lt;/p&gt;&lt;p&gt;For example in a Java API, an instance of the &lt;code&gt;Chef&lt;/code&gt; is provided in the classes providing API endpoints. This can look roughly as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;@Autowired
private JChef chef;

@POST
@Path&amp;#40;&amp;quot;pastaSauce&amp;quot;&amp;#41;
public Response waterBoiling&amp;#40;UUID processId, Sauce sauce&amp;#41; {
    chef.tellEventHappened&amp;#40;processId, new PastaSauceReady&amp;#40;sauce&amp;#41;&amp;#41;;

    return Response.ok&amp;#40;&amp;#41;.build&amp;#40;&amp;#41;;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Once the API is called on the &lt;em&gt;pastaSauce&lt;/em&gt; resource there is no complex if-then-else business logic. The chef is just told whom it is that is calling our API, that it is the &lt;code&gt;PastaSauceReady&lt;/code&gt; event that has happened and what &lt;code&gt;sauce&lt;/code&gt; data was provided. All logic on what to do with this information is provided by the recipe and encapsulated in the chef.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;closing&amp;#95;remarks&quot;&gt;&lt;/a&gt;Closing remarks&lt;/h2&gt;&lt;p&gt;By using the modeling language of Petri nets and by creating a DSL it is possible to facilitate reuse, flexibility and encapsulation of complexity in the modeling of a business process. Changing the business logic has become as easy as changing the recipe. Business analysts can read or view the recipe and see if it adheres to their ideas. The chef should even be able to tell if it can cook a specific recipe. In theory, it is possible to share the ingredients and the chef with other teams and let them create new recipes reusing the components. And where in classically build APIs it can be difficult to trace where things went wrong, because of the properties of Petri nets it is possible to thoroughly analyze flows taken through the application.&lt;/p&gt;&lt;p&gt;If you want to read more:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Fowler, M. (2010). &lt;a href='https://amzn.to/1TYg3dd'&gt;&lt;em&gt;Domain-Specific Languages&lt;/em&gt;&lt;/a&gt;. Addison-Wesley Professional.&lt;/li&gt;&lt;li&gt;Van der Aalst, W.M.P. &amp; Stahl, C (2011). &lt;a href='https://amzn.to/1VzuMhh'&gt;&lt;em&gt;Modeling Business Processes: A Petri Net-Oriented Approach&lt;/em&gt;&lt;/a&gt;. The MIT Press.&lt;/li&gt;&lt;/ul&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Thu, 02 Jun 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-05-17-programming-and-meditation/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-05-17-programming-and-meditation/
</link>
<title>
Programming and meditation
</title>
<description>
&lt;p&gt;Our minds jump from past memory to future fantasy and are extraordinarily out of control. Buddhism provides a technique which helps us to tame our wild minds: meditation.&lt;/p&gt;&lt;p&gt;Meditation is &lt;a href='https://www.youtube.com/watch?v=-h1miVEqer0&amp;t=11m11s'&gt;sitting down quietly and being aware of all that goes on, without comment&lt;/a&gt;. In meditation (Vipassana) the idea is to stay with reality as it is experienced in this very moment. It brings about &lt;a href='https://www.shinzen.org/wp-content/uploads/2016/12/art_purpose.pdf'&gt;purification and insight&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I learned the technique of meditation at a 10-day retreat of &lt;a href='https://www.dhamma.org'&gt;dhamma.org&lt;/a&gt;. Last year I went to Thailand and I have lived 10 days in a similar manner as Buddhist monks and nuns at Wat Ram Poeng.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://i.imgur.com/7zM16Pa.jpg&quot; alt=&quot;Blending in at the Vipassana meditation retreat at Wat Ram Poeng&quot;&gt;&lt;/img&gt; &lt;br/&gt; &lt;i&gt;Blending in at a meditation retreat at Wat Ram Poeng&lt;/i&gt;&lt;/p&gt;&lt;p&gt;This has led to me appreciate this wonderful technique for feeling at ease and dealing with the vicissitudes of life.&lt;/p&gt;&lt;p&gt;Where meditation helps me to stay grounded, programming, on the other hand, can be an activity which moves me away from everyday reality. As a programmer I work with abstractions.&lt;/p&gt;&lt;p&gt;As Fred Brooks writes in &lt;a  href=&quot;https://www.amazon.com/gp/product/0201835959/ref=as&lt;i&gt;li&lt;/i&gt;tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201835959&amp;linkCode=as2&amp;tag=evalapply-20&amp;linkId=5322NWVJYDUY7P3X&quot;&gt;The Mythical Man-Month&lt;/a&gt;&lt;img src=&quot;https://ir-na.amazon-adsystem.com/e/ir?t=evalapply-20&amp;l=as2&amp;o=1&amp;a=0201835959&quot; width=&quot;1&quot; height=&quot;1&quot; border=&quot;0&quot; alt=&quot;&quot; style=&quot;border:none !important; margin:0px !important;&quot; /&gt;:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds castles in the air, from air, creating by exertion of the imagination. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Meditation can not only provide a welcome counterweight to this work with abstractions, it also cultives 10 qualities of character (Pali: &lt;em&gt;paramis&lt;/em&gt;) that are useful during the practice of programming.&lt;/p&gt;&lt;p&gt;Below I will list these 10 qualities and explain how they might benefit the programmer.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;dana&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;generosity&quot;&gt;&lt;/a&gt;&lt;em&gt;Dana&lt;/em&gt; &amp;ndash; Generosity&lt;/h3&gt;&lt;p&gt;Meditation teaches you to give freely without expecting anything in return. Won't be surprised when you start coding for others for the sheer joy of giving.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;sila&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;morality&quot;&gt;&lt;/a&gt;&lt;em&gt;Sila&lt;/em&gt; &amp;ndash; Morality&lt;/h3&gt;&lt;p&gt;Meditation helps you to speak properly, perform good actions and have a right means of livelihood. Software engineering involves communication with others and is a way to sustain yourself. Cultivating the urgency to do or say the right thing will help you with this.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;nekkhamma&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;renunciation&quot;&gt;&lt;/a&gt;&lt;em&gt;Nekkhamma&lt;/em&gt; &amp;ndash; Renunciation&lt;/h3&gt;&lt;p&gt;By renouncing the thoughts of for example sensual pleasures you become more adequate at dealing with that what is actually going on. When you code you code. Nothing else.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;panna&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;wisdom/understanding&quot;&gt;&lt;/a&gt;&lt;em&gt;Panna&lt;/em&gt; &amp;ndash; Wisdom/understanding&lt;/h3&gt;&lt;p&gt;Meditation makes you realize on a fundamental level that everything is impermanent (&lt;em&gt;Anicca&lt;/em&gt;) and that because we as human beings cling to and identify with (&lt;em&gt;Anatta&lt;/em&gt;) this changing reality we suffer (&lt;em&gt;Dukkha&lt;/em&gt;). One thing to learn from this is that you are not your code. This helps when receiving feedback.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;viriya&lt;/em&gt;&amp;#95;-&amp;#95;effort&quot;&gt;&lt;/a&gt;&lt;em&gt;Viriya&lt;/em&gt; - Effort&lt;/h3&gt;&lt;p&gt;Mindfulness trains the mind to not procrastinate. It leads to prolonged periods of focus. Focus comes in handy during programming.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;khanti&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;patience&amp;#95;/&amp;#95;tolerance&quot;&gt;&lt;/a&gt;&lt;em&gt;Khanti&lt;/em&gt; &amp;ndash; Patience / tolerance&lt;/h3&gt;&lt;p&gt;Meditation gives you the patience and tolerance to just fill in that Excel sheet for the next hour.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;sacca&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;truthfulness&quot;&gt;&lt;/a&gt;&lt;em&gt;Sacca&lt;/em&gt; &amp;ndash; Truthfulness&lt;/h3&gt;&lt;p&gt;You will tell your boss the true state of affairs: the software will not be finished before the deadline.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;adhitthana&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;strong&amp;#95;determination&quot;&gt;&lt;/a&gt;&lt;em&gt;Adhitthana&lt;/em&gt; &amp;ndash; Strong determination&lt;/h3&gt;&lt;p&gt;Just like the Buddha did not leave the tree till he was enlightened, you will not stand up from your chair till you have finished that piece of code.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;metta&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;loving-kindness&quot;&gt;&lt;/a&gt;&lt;em&gt;Metta&lt;/em&gt; &amp;ndash; Loving-kindness&lt;/h3&gt;&lt;p&gt;Meditation teaches you to love what you do and the people you do it with. Enjoying what you do and cultivating good relationships with colleagues or friends helps with programming just as much as everything else.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;em&gt;upekkha&lt;/em&gt;&amp;#95;&amp;ndash;&amp;#95;equanimity&quot;&gt;&lt;/a&gt;&lt;em&gt;Upekkha&lt;/em&gt; &amp;ndash; Equanimity&lt;/h3&gt;&lt;p&gt;Sitting through (enjoying even) hours of pain in your legs without responding to it has taught you to stay calm in the face of adversity. These 20 more use cases that you had initially overseen that will need to be implemented? No problem.&lt;/p&gt;&lt;p&gt;As a bonus, what I love of meditation is how aware you become of bodily sensations. For example: you notice earlier that your body is aching and that it is time to walk and stretch. It also helps with creativity. It's impressive how ideas start to flow when you watch your belly go up and down 30 minutes in the morning.&lt;/p&gt;&lt;p&gt;Interested? A good way to learn the technique of Vipassana meditation and experience its beneficial results is at a 10-day retreat at &lt;a href='https://www.dhamma.org'&gt;dhamma.org&lt;/a&gt;. Alternatively you can go to a country like Thailand and learn the technique at one of the meditation centers there.&lt;/p&gt;&lt;p&gt;Shameless plug:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://www.microsoft.com/en-us/store/apps/no-nonsense-meditation-timer/9nblggh6cgj0&quot;&gt; &lt;img src=&quot;https://i.imgur.com/eRpw8Bd.png&quot; alt=&quot;No Nonsense Meditation Timer in Windows Phone Store&quot;&gt;&lt;/img&gt; &lt;/a&gt;&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Tue, 17 May 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-05-02-vim-and-emacs/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-05-02-vim-and-emacs/
</link>
<title>
Vim and Emacs
</title>
<description>
&lt;p&gt;I'll show you why I love Vim and why I switched to Emacs and why you might too.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;vim&quot;&gt;&lt;/a&gt;Vim&lt;/h2&gt;&lt;p&gt;Vim is really really awesome. Inspired by a lot of great hackers who swear by Vim (&lt;a href='https://www.reddit.com/r/vim/comments/34vffh/famous_vim_users/'&gt;like Bram Moolenaar and Vim Diesel&lt;/a&gt;) and by the greatest ode to a text editor ever (&lt;a href='https://www.norfolkwinters.com/vim-creep/'&gt;&quot;Vim Creep&quot;&lt;/a&gt;), eight months ago I decided to take the plunge.&lt;/p&gt;&lt;p&gt;First I did &lt;code&gt;vimtutor&lt;/code&gt; at home, then I installed VimEmu in Visual Studio (I programmed C&amp;#35; at the time), I printed the &lt;a href='https://www.viemu.com/vi-vim-cheat-sheet.gif'&gt;Vim cheat sheet&lt;/a&gt;, and broke up with my mouse.&lt;/p&gt;&lt;p&gt;Against the advice in the excellent video Learning Vim in a week (see below) I did start at work.&lt;/p&gt;&lt;p&gt;&lt;iframe src=&quot;https://www.youtube.com/embed/_NUO4JEtkDw&quot; allowfullscreen=&quot;&quot; frameborder=&quot;0&quot; height=&quot;315&quot; width=&quot;420&quot;&gt;&lt;/iframe&gt;&lt;/p&gt;&lt;p&gt;Work is the place where I edit the most text and I needed to do some boring work at the time. I have no regrets learning Vim there. Within a week my speed was back to my average before that. I became slower in certain parts but faster in others.&lt;/p&gt;&lt;p&gt;More importantly, boring, repetitive tasks were no longer boring and repetitive. In Vim, writing boring code is seriously fun because you stretch your mind on creating efficient text manipulations. I stayed interested doing the work, and I learned Vim. In that period both my employer and myself have benefited from me learning Vim at work.&lt;/p&gt;&lt;p&gt;Eight months later I use Vim everywhere. Nowadays even a mundane task as updating my TODO list is exhilarating.&lt;/p&gt;&lt;p&gt;The following example of the awesomeness of Vim is based on a real life situation where I wanted to unroll a T-SQL loop. Suppose you want to create four separate update statements from the four table names (First, Second, Third, Fourth) and columns above the EXECUTE block below:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;INSERT INTO @TABLES&amp;#95;COLUMNS &amp;#40;TABLE&amp;#95;NAME, COLUMN&amp;#95;NAME&amp;#41;
    VALUES
    &amp;#40;'&amp;#91;dbo&amp;#93;.&amp;#91;First&amp;#93;', '&amp;#91;Yadadada&amp;#93;'&amp;#41;,
    &amp;#40;'&amp;#91;dbo&amp;#93;.&amp;#91;Second&amp;#93;', '&amp;#91;Blabla&amp;#93;'&amp;#41;,
    &amp;#40;'&amp;#91;dbo&amp;#93;.&amp;#91;Third&amp;#93;', '&amp;#91;Abacadabra&amp;#93;'&amp;#41;,
    &amp;#40;'&amp;#91;dbo&amp;#93;.&amp;#91;Fourth&amp;#93;', '&amp;#91;Yeehah&amp;#93;'&amp;#41;,
    &amp;#40;...&amp;#41;

    WHILE 1=1
    /&amp;#42; Set the variables of table name and column name &amp;#40;substitute with VALUES above&amp;#41; &amp;#42;/
    EXECUTE
    &amp;#40;
        'UPDATE ' + @TABLE&amp;#95;NAME + ' ' +
        'SET ' + @COLUMN&amp;#95;NAME + ' = temp.OLD
        'FROM ' + @TABLE&amp;#95;NAME + 'AS t ' +
        'INNER JOIN #temp AS temp ' +
        'ON t.' + @COLUMN&amp;#95;NAME + ' = temp.NEW'
    &amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;(Note that this code is a bit simplified: the setting of the loop variables and extra values are skipped.)&lt;/p&gt;&lt;p&gt;In the real life example this was based on there were about 15 of those substitutions instead of four. This is what I would consider a boring task. Since the task is short enough that writing a script to automate it is slower than actually doing it, in normal (non-Vim) life I would to do this by hand.&lt;/p&gt;&lt;p&gt;What needs to be done above is:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Cleanup the &quot;+&quot; and quotes from the EXECUTE statement.&lt;/li&gt;&lt;li&gt;Copy the cleaned up EXECUTE statement.&lt;/li&gt;&lt;li&gt;Copy the first variable value and substitute it for @TABLE_NAME.&lt;/li&gt;&lt;li&gt;Copy the second variable value and substitute it for @COLUMN_NAME.&lt;/li&gt;&lt;li&gt;Repeat step 2 till 4 for the next entries in @TABLES_COLUMNS.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;I would have to do this about 15 times. I think this would take me about 10 minutes.&lt;/p&gt;&lt;p&gt;With Vim it is different.&lt;/p&gt;&lt;p&gt;I recorded the operations on the text once, and then I executed the operation I just did on the next two variable values. Then on the next, then on the next. This is programming your text. And it is so easy. You should probably see the recording and execution of the macro to understand:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/KotHf82.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/KotHf82.gif&quot; alt=&quot;Vim macro recorded and repeated&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;sub&gt;Note: after recording I see that showing these keypresses doesn't really help since a lot of them are missed and you cannot easily see the difference between lower and upper case. :) Apologies.&lt;/sub&gt;&lt;/p&gt;&lt;p&gt;We see lots of missed efficiencies and some wrong keypresses. It is a dirty recording. But life in Vim is messy. Editing code with a mouse doesn't go right the first time either.&lt;/p&gt;&lt;p&gt;What we see in the gif above is that first I remove the no longer necessary EXECUTE statement after easily having jumped to the end of the file (G). (Note that navigating in Vim goes with h, j, k and l &amp;ndash; you never have to leave your home row.) I &lt;strong&gt;v&lt;/strong&gt;isually select the statement with something like V5k (visually select five lines [V] upwards [k]).&lt;/p&gt;&lt;p&gt;In Vim it is as if you speak to your computer: you say a verb, you say how many times and you say what.&lt;/p&gt;&lt;p&gt;Then I &lt;strong&gt;s&lt;/strong&gt;ubstitute the &quot;'&quot; and &quot;+&quot; from the selected region with a command (:) with nothing &lt;strong&gt;g&lt;/strong&gt;lobally:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;:s/&amp;#91;+'&amp;#93;//g&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Next I &lt;strong&gt;d&lt;/strong&gt;elete the selection and I yank the UPDATE statement plus one blank line in register u (&quot;ud [delete into register u]). Now I navigate to the top of the page (gg) and start a recording in register a (qa) (I pick register a for no other reason than that it is close to q). I navigate down two lines (2j), &lt;strong&gt;f&lt;/strong&gt;ind the first quote (f') of the first variable and &lt;strong&gt;y&lt;/strong&gt;ank (copy) everything &lt;strong&gt;i&lt;/strong&gt;nside the quotes (') into register &lt;strong&gt;f&lt;/strong&gt; (&quot;fyi'). Next I go to the end of the line ($) and copy the second variable into register s. (I use register f for first and s for second.) So now we have the table name we want to substitute stored in register f and the column name in register s.&lt;/p&gt;&lt;p&gt;Then I go to the end of the file (G), &lt;strong&gt;p&lt;/strong&gt;aste everything inside register &lt;strong&gt;u&lt;/strong&gt; (&quot;up). This way the UPDATE-statement comes at the bottom of the page. i Next I &lt;strong&gt;v&lt;/strong&gt;isually select the &lt;strong&gt;w&lt;/strong&gt;ord of the table name variable and paste the &lt;strong&gt;f&lt;/strong&gt; register over it (&quot;fp) (so: vw&quot;fp). I also substitute the column name for the new value inside register s.&lt;/p&gt;&lt;p&gt;After having substituted all the column names and table names variables for the new values, I jump to the top of the file and go two lines down (gg2k). I remove the line (dd), jump back to the top (gg) and stop recording (q).&lt;/p&gt;&lt;p&gt;Next I execute that what I have just recorded three times (3@a)! Since the recording was on a meta-level of navigation, selection and substitution this works perfectly fine for the other variable names. Each time copying the statement, removing and substituting the values of the table and column name and ending on the top of the file. The whole file is done. This would have worked just as fast for 100 rows by the way.&lt;/p&gt;&lt;p&gt;I find these possibilities so cool.&lt;/p&gt;&lt;p&gt;&lt;em&gt;/edit As Veedrac showed in a &lt;a href='https://www.reddit.com/r/programming/comments/4hcvya/ill_show_you_why_i_love_vim_and_why_i_switched_to/d2pfiun'&gt;comment on reddit&lt;/a&gt; in &lt;/em&gt; &lt;em&gt;Sublime Text this refactoring is also possible and arguably more intuitive using multiple cursors. &lt;/em&gt; &lt;em&gt;Vedrac made a video where multiple cursors are used to do the same refactoring. This video can be watched &lt;a href='https://sendvid.com/7o5z2ky6'&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Note that the jumping around in Vim and selecting text is usually the biggest time saver. As JangoSteve writes in the comments on Hacker News in response to the article Vim Creep:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;vim doesn't save you five minutes, twenty times a week; it saves you 0.75 seconds, eight thousand times a week. Same time savings, but much harder notice the pain before you've solved it. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;And indeed the most time savings are just all the basic movements where you would have normally grabbed your mouse repeatedly. But Vim is also absolutely wonderful for these large refactorings as above.&lt;/p&gt;&lt;p&gt;To be honest, when I recorded the macro for the first time (in the real life thing where the example was based on) it only really worked the tenth time I tried. (In my defense: it was during a late night cowboy deploy that went horribly wrong because of  a query that performed a tad bit worse on production than acceptance and there were people watching my actions via the remote which gave me  performance anxiety.) But finally it did succeed and I learned from it and this time while recreating it I got it in one go. In the excellent book &lt;a  href=&quot;https://www.amazon.com/gp/product/059652983X/ref=as&lt;i&gt;li&lt;/i&gt;tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=059652983X&amp;linkCode=as2&amp;tag=evalapply-20&amp;linkId=UG223IAEZ2T3MQXI&quot;&gt;Learning the vi and Vim Editors&lt;/a&gt;&lt;img src=&quot;https://ir-na.amazon-adsystem.com/e/ir?t=evalapply-20&amp;l=as2&amp;o=1&amp;a=059652983X&quot; width=&quot;1&quot; height=&quot;1&quot; border=&quot;0&quot; alt=&quot;&quot; style=&quot;border:none !important; margin:0px !important;&quot; /&gt; something like this is said about forcing yourself to learn efficiency gains: first some action or learning a regex will take you some time, but this pays back many times over the next time when hyper-efficient text-editing has become embedded in your muscle memory.&lt;/p&gt;&lt;p&gt;Note that one of the lessons of the Learning Vim in a Week video above is that &quot;There is always a better way.&quot; Typing this I see I could have better substituted the variable names in a similar manner as how I substituted the quotes and plus from the full statement. Also I used B or W instead of b and w to jump &lt;strong&gt;B&lt;/strong&gt;ackwards or forwards a big &lt;strong&gt;W&lt;/strong&gt;ord (including the @). So there was indeed a better way with less keypresses. There surely is even a (much) better way.&lt;/p&gt;&lt;p&gt;Furthermore, the fact that I am now recreating this situation shows how much fun it is. I really don't mind.&lt;/p&gt;&lt;p&gt;I got a bit carried away already, but Vim is awesome. Some of the things we have seen is easily navigating with the keyboard, executing commands over lines of text, storing stuff in multiple registers, editing selecting or deleting specific blocks of text, and recording a macro to re-execute a sequence of keypresses.&lt;/p&gt;&lt;p&gt;This is made possible by different modes that are available in Vim: normal mode for navigation, insert mode for inserting text, command mode for executing a command and visual mode for selection.&lt;/p&gt;&lt;p&gt;Some more awesomeness that is not shown in the example above are for example:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The .-command to repeat your last action.&lt;/li&gt;&lt;li&gt;Editing the .vimrc file to easily bind new keys and add plugins. (Well this is shown, you see for example syntax highlighting and &lt;a href='https://github.com/myusuf3/numbers.vim'&gt;relative line numbers&lt;/a&gt;).&lt;/li&gt;&lt;li&gt;The awesome Vim plugin &lt;a href='https://github.com/tpope/vim-surround'&gt;surround.vim&lt;/a&gt; to easily change surrounding quotes or braces into something else or add or delete them.&lt;/li&gt;&lt;li&gt;Marking places in the text and jumping back (ma &amp;ndash; mark this position with a and 'a to jump to position a).&lt;/li&gt;&lt;li&gt;Reselecting the region you just had selected with gv.&lt;/li&gt;&lt;li&gt;Doing a block selection with CTRL-V and changing the selection size on the &lt;strong&gt;o&lt;/strong&gt;ther side with o.&lt;/li&gt;&lt;li&gt;Navigating undo trees (e.g., go to the state of your file five minutes back in time with :earlier 5m).&lt;/li&gt;&lt;li&gt;Pair programming by working in the same file after sharing your buffer over SSH using tmux.&lt;/li&gt;&lt;li&gt;Everything else other text-editors can do.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;If you want to jump into Vim I can advice you to watch the video on Learning Vim in a Week above and do the &lt;code&gt;vimtutor&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Stick with it. You will not regret it.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;emacs&quot;&gt;&lt;/a&gt;Emacs&lt;/h2&gt;&lt;p&gt;I love Lisp and it turns out that for Lisp editing it is somewhat more logical to use Emacs (although for example the expert Lisper Doug Hoyte swears by vi &amp;ndash; the non-improved version of Vim). The reason for that is it has tight integration with the language and you can use a version of Lisp called ELisp to configure and modify the editor. (Note that some people get really carried away with editing their editor instead of editing arguably more useful code).&lt;/p&gt;&lt;p&gt;But even before I used Emacs to learn the Lisp-dialect Clojure I had already switched to it. The reason for that was the video &quot;Evil Mode: Or, How I Learned to Stop Worrying and Love Emacs&quot;:&lt;/p&gt;&lt;p&gt;(Warning: it is a bit long.)&lt;/p&gt;&lt;p&gt;&lt;iframe src=&quot;https://www.youtube.com/embed/JWD1Fpdd4Pc&quot; allowfullscreen=&quot;&quot; frameborder=&quot;0&quot; height=&quot;315&quot; width=&quot;420&quot;&gt;&lt;/iframe&gt;&lt;/p&gt;&lt;p&gt;Evil Mode is an &lt;strong&gt;E&lt;/strong&gt;xtensible &lt;strong&gt;v&lt;/strong&gt;i &lt;strong&gt;l&lt;/strong&gt;ayer for Emacs. This means you can have Vim keybindings while having the Emacs environment.&lt;/p&gt;&lt;p&gt;Why would you want that? Well, Emacs is a much better environment than Vim. Some people call it an operating system instead of a text-editor. And it is true. Where Vim will sometimes hang when performing large operations, Emacs just runs on easily.&lt;/p&gt;&lt;p&gt;In the video above examples are shown how things that would block normal Vim can sometimes go on in Emacs on a background thread. And for me Emacs with Evil mode just feels lighter than Vim. There are some other attempts to improve the performance of Vim (notably &lt;a href='https://neovim.io/'&gt;NeoVim&lt;/a&gt;), but this would still not have the Lisp integration Emacs has.&lt;/p&gt;&lt;p&gt;Furthermore, things like searching and replacing are better. You visually see in the text what will change while a substitution command is typed. And search matches light up before you finished typing your search. Examples of search and replace are shown in the video at the end. And when you start typing in the command area it automatically starts showing suggestions. There are a lot of these minor things that make Emacs with Evil mode very pleasurable.&lt;/p&gt;&lt;p&gt;Because of the Lisp integration (firing up a REPL and never having to leave Emacs), nice quirks as command completion, and the better performance I use Emacs.&lt;/p&gt;&lt;p&gt;To configure Emacs you can edit a .emacs file or the ~/.emacs.d/init.el file. Evil mode provides a &lt;a href='https://www.emacswiki.org/emacs/Evil'&gt;lot of ways to hook into the execution flow and plugins&lt;/a&gt;. For editing Clojure I just use the Emacs setup as described in &lt;a href='https://www.braveclojure.com/basic-emacs/'&gt;Clojure for the Brave and True&lt;/a&gt; extended with Evil mode.&lt;/p&gt;&lt;p&gt;Some of the non-Evil features I use for editing Clojure are mentioned there. Things like CTRL-c CTRL-k to compile code and CTRL-c CTRL-d CTRL-d to view the library definition (if I am not mistaken, fact of the matter is the keybindings for Emacs to me are much more unlogical than those of Vim).&lt;/p&gt;&lt;p&gt;Now I will visually show some of the other awesomeness, but related to Evil mode. Just to give an impression.&lt;/p&gt;&lt;p&gt;Redoing things with the .-command work just as in Vim:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/0UW5Jke.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/0UW5Jke.gif&quot; alt=&quot;Redo command in Evil mode&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;Above we see the . command used to &lt;strong&gt;c&lt;/strong&gt;hange text &lt;strong&gt;i&lt;/strong&gt;nside the parentheses &lt;strong&gt;&quot;&lt;/strong&gt; (ci&quot;).&lt;/p&gt;&lt;p&gt;Next I have bound CTRL-b to display all available buffers and easily switch between them. This is done in such a way you can use the familiar hjkl to navigate.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/nQJip0a.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/nQJip0a.gif&quot; alt=&quot;Easily switch between buffers in Evil-mode&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;And we can display multiple windows &lt;strong&gt;v&lt;/strong&gt;ertically (CTRL-W v) or &lt;strong&gt;s&lt;/strong&gt;plit them horizontally (CTRl-W s):&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/DXe5QtD.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/DXe5QtD.gif&quot; alt=&quot;Multiple buffers editing&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;(Since I did not want to not use these buffers at all, note that we made a selection &lt;strong&gt;u&lt;/strong&gt;pper case with U and it changed in all views of the buffer  simultaneously.)&lt;/p&gt;&lt;p&gt;Another really awesome thing which I believe comes out of the box is undolist, with it you can visually navigate the undo history. Yes, you can view the branches you decided to delete. Undo history can easily be viewed and navigated by typing the command:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;:undolist&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/uCTvsRK.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/uCTvsRK.gif&quot; alt=&quot;Evil mode has very nice undo history visualiation.&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;How cool is that?&lt;/p&gt;&lt;p&gt;And we can add a very rich set of plugins to Emacs. Of course we have all the plugins added for Clojure by the author of Clojure for the Brave and True. Which provide syntax highlighting and tight integration with documentation, the REPL and executing code.&lt;/p&gt;&lt;p&gt;I'll now show two other plugins I find very interesting.&lt;/p&gt;&lt;p&gt;We can display the file system on the left if we want with F8 by using &lt;a href='https://github.com/jaypei/emacs-neotree'&gt;NeoTree&lt;/a&gt;: &lt;a href=&quot;https://i.imgur.com/B1RszIj.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/B1RszIj.gif&quot; alt=&quot;Navigate with F8.&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;Above we see me pressing F8 and navigating to an uninteresting folder on my file system.&lt;/p&gt;&lt;p&gt;Furthermore, look at this &quot;slurping&quot; of some elements from a string with &gt; (SHIFT-.): &lt;a href=&quot;https://i.imgur.com/JaSZHP1.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/JaSZHP1.gif&quot; alt=&quot;ParEdit for slurping&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;(Note that the five lines are combine with 5J [J is for &lt;strong&gt;j&lt;/strong&gt;oining two lines] &amp;ndash; another feature I wanted to force into this).&lt;/p&gt;&lt;p&gt;Slurping on one end or the other or barfing things out on one side of the other is a feature of &lt;a href='https://www.emacswiki.org/emacs/ParEdit'&gt;ParEdit&lt;/a&gt;. ParEdit is helpful for manipulating S-expressions (the parentheses in Lisp) but can also be used for other structures like the quotes above.&lt;/p&gt;&lt;p&gt;Is everything rose shine and moon light? No. I have identified the following shortcomings so far:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Sometimes I want to quit an Emacs buffer (q), but then I cannot do so because I first have to enter insert mode. See my question about it on the Emacs Stack Exchange &lt;a href='https://emacs.stackexchange.com/questions/21628/use-default-keybindings-in-evil-in-non-text-editing-buffers'&gt;here&lt;/a&gt;.&lt;/li&gt;&lt;li&gt;The window jumps halfways unwantedly when scrolling up and down (CTRL-E CTRL-Y btw). This can probably be fixed.&lt;/li&gt;&lt;li&gt;Paredit can be annoying. You have to press CTRL-Q before inserting a parenthesis. But you can of course disable it.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;That's all I can come up with and I have thought really hard.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;closing&amp;#95;remarks&quot;&gt;&lt;/a&gt;Closing remarks&lt;/h2&gt;&lt;p&gt;I think Emacs Evil mode is a very nice environment to edit text. I hope I was able to show some of that by the examples. If you want some more of Evil mode I can recommend this great demonstration:&lt;/p&gt;&lt;p&gt;&lt;iframe src=&quot;https://www.youtube.com/embed/Uz_0i27wYbg&quot; allowfullscreen=&quot;&quot; frameborder=&quot;0&quot; height=&quot;315&quot; width=&quot;420&quot;&gt;&lt;/iframe&gt;&lt;/p&gt;&lt;p&gt;You can download the &lt;a href='https://www.braveclojure.com/basic-emacs/'&gt;Clojure for the Brave and True emac setup&lt;/a&gt; which I extended with Evil mode as descibed above &lt;a href='https://github.com/transducer/emacs'&gt;by clicking here&lt;/a&gt;. If you install Emacs and place the repository in the ~/.emacs.d directory everything will install automatically. Note that there are probably better dotfiles out there. The way to install plain Vim can be found &lt;a href='https://www.vim.org/download.php'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;One final note: if you start using Vim do not forget to remap your Capslock to Escape. You will be pressing Escape a lot and on todays keyboards it is too faraway from the homerow.&lt;/p&gt;&lt;p&gt;Thank you for reading. Comments are welcome.&lt;/p&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Mon, 02 May 2016 00:00:00 +0200
</pubDate>
</item>
<item>
<guid>
https://www.rooijakkers.software/posts/2016-04-25-metacircular-evaluator/
</guid>
<link>
https://www.rooijakkers.software/posts/2016-04-25-metacircular-evaluator/
</link>
<title>
The meta-circular evaluator
</title>
<description>
&lt;p&gt;Meta-circular evaluators are awe-inspiring.&lt;/p&gt;&lt;p&gt;This will be a walkthrough of the meta-circular evaluator demonstrated in &lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-25.html'&gt;Chapter 4&lt;/a&gt; and &lt;a href='https://www.youtube.com/watch?v=0m6hoOelZH8'&gt;Lecture 7A&lt;/a&gt; of &lt;a href='https://mitpress.mit.edu/sicp/'&gt;The Structure and Interpretation of Computer Programs&lt;/a&gt; (SICP). The chapter and video are on the subject of &quot;meta-linguistic abstraction&quot; &amp;ndash; the establishing of new languages.&lt;/p&gt;&lt;p&gt;To evaluate a computer language you need an evaluator (also called interpreter) for that language. Evaluating an expression in a programming language means that the evaluator performs or executes the instructions described in the expression. An evaluator is called meta-circular if it evaluates the same language as it is written in using the same language constructs as the language itself (circular definitions).&lt;/p&gt;&lt;p&gt;Why would you want such a thing? One of the reasons is that having a meta-circular evaluator makes it very practical to implement new languages on top of the implementation language. Using a meta-circular evaluator you can, for example, create a language that is particularly suited for a problem at hand (a &lt;a href='https://en.wikipedia.org/wiki/Domain-specific_language'&gt;Domain Specific Language&lt;/a&gt;). Another reason is that it is insightful for educational and experimental purposes. The basic eval-apply structure below can be used to write interpreters for all kinds of languages. It is the kernel for every computer language.&lt;/p&gt;&lt;p&gt;What does a meta-circular evaluator look like? In &lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-25.html'&gt;SICP it is stated that&lt;/a&gt;:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;It is no exaggeration to regard this as the most fundamental idea in programming:&lt;br&gt;&lt;br&gt; The evaluator, which determines the meaning of expressions in a programming language, is just another program. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;So it is just another program. In this post I have translated the code from meta-circular evaluator program from SICP (you can find the original code &lt;a href='https://mitpress.mit.edu/sicp/code/ch4-mceval.scm'&gt;here&lt;/a&gt;) to Clojure.&lt;/p&gt;&lt;p&gt;Clojure is interesting because:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;It runs on the Java Virtual Machine (therefore having access to all Java libraries and being able to interoperate with existing Java code bases).&lt;/li&gt;&lt;li&gt;It has a functional core (therefore being particularly suited for concurrent programming, necessary to utilize multiple CPUs).&lt;/li&gt;&lt;li&gt;And it is a dialect of Lisp (therefore having all the interesting properties described below).&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Now, before I continue, let me be clear. I am not an expert on the subject matter. It is impossible for me to improve on the &lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html'&gt;explanation in SICP&lt;/a&gt;. What I have attempted to do here is translate the Scheme code of SICP to Clojure and thereby deeper understand what is going on in the meta-circular evaluator and also learn something about Clojure. I have tried to put into my own words what is described in SICP. If you have a background in computer science this post is probably not much new. After all, SICP is an introductory level computer science book. I don't have such a background so for me this was all pretty mind blowing. I learned quite a lot from this post myself. Before I started to write I thought I understood, but when converting the SICP code to Clojure I realized I did not understand it as thoroughly as I thought. I needed quite a lot of help from the web and the end result is basically different sources copy-pasted together till I had a reasonably working evaluator.&lt;/p&gt;&lt;p&gt;It is very likely that the text in this post contains mistakes and I would be happy if they will be pointed out to me as well.&lt;/p&gt;&lt;p&gt;Now, let's get started.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;background&quot;&gt;&lt;/a&gt;Background&lt;/h2&gt;&lt;p&gt;The idea of a meta-circular evaluator was first described by John McCarthy in his paper &lt;a href='https://www-formal.stanford.edu/jmc/recursive.html'&gt;Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;(There has by the way never been a Part 2, although &lt;a href='https://www.youtube.com/watch?v=CD-Dtr9j0f4'&gt;some people have some ideas what it would look like&lt;/a&gt;).&lt;/p&gt;&lt;p&gt;This is the paper where McCarthy invented Lisp (acronym for LIst Processing). It contained the definition for &lt;code&gt;eval&lt;/code&gt; &amp;ndash; the universal function. &lt;code&gt;eval&lt;/code&gt; is a universal machine: if you feed it a Lisp program, &lt;code&gt;eval&lt;/code&gt; starts behaving as that program. It required inventing a notation where you could represent programs as data.&lt;/p&gt;&lt;p&gt;For McCarthy, writing this function was just a theoretical exercise. It was never his idea that the language or the function was actually implemented. What then happened was that Steve Russell, one of McCarthy's graduate students (who also &lt;a href='https://en.wikipedia.org/wiki/Spacewar_%28video_game%29'&gt;invented one of the first computer games&lt;/a&gt;) transformed his theory into an actual programming language. As McCarthy stated in an interview:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Steve Russell said, look, why don't I program this eval..., and I said to him, ho, ho, you're confusing theory with practice, this eval is intended for reading, not for computing.  But he went ahead and did it. That is, he compiled the &lt;code&gt;eval&lt;/code&gt; in my paper into IBM 704 machine code, fixing a bug, and then advertised this as a Lisp interpreter, which it certainly was. So at that point Lisp had essentially the form that it has today...&quot; (&lt;a href='https://books.google.nl/books?id=eH6jBQAAQBAJ&amp;pg=PA777&amp;lpg=PA777#v=onepage&amp;q&amp;f=false'&gt;Source&lt;/a&gt;) &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Alan Kay (famous computer scientist and creator of the language Smalltalk) &lt;a href='(https://queue.acm.org/detail.cfm?id=1039523'&gt;describes his excitement&lt;/a&gt; when he first saw this &lt;code&gt;eval&lt;/code&gt; and understood that it was Lisp written in itself.&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;These were &quot;Maxwells Equations of Software!&quot; This is the whole world of programming in a few lines that I can put my hand over. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;&lt;sup&gt;Note: the &lt;a href='https://www.youtube.com/watch?v=DSRLvkP0vmg'&gt;Maxwell equations&lt;/a&gt; are four extremely elegant equations from which everything there is to know about the electromagnetic field can be derived.&lt;/sup&gt;&lt;/p&gt;&lt;p&gt;Lisp is special because it does not enforce syntactic and semantic rules: it can be programmed at a higher level of abstraction than other languages. Lisp can be transformed in other languages. Some of that we will see below.&lt;/p&gt;&lt;p&gt;So what does Lisp look like?&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;lisp,&amp;#95;lisp,&amp;#95;lisp&quot;&gt;&lt;/a&gt;Lisp, Lisp, Lisp&lt;/h2&gt;&lt;p&gt;The nice thing about Lisp is that is has almost no syntax. The rules are simple (like Go), but the possibilities within these rules are virtually endless (like Go). Lisp is infamous for its parentheses.&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://imgs.xkcd.com/comics/lisp_cycles.png&quot; alt=&quot;xkcd I've just received word that the Emperor has dissolved the MIT computer science program permanently.&quot; /&gt;&lt;/p&gt;&lt;p&gt;(Source: &lt;a href='https://xkcd.com/297/'&gt;https://xkcd.com/297/&lt;/a&gt;)&lt;/p&gt;&lt;p&gt;Combined with prefix notation these parentheses makes it so that Lisp data structures have the same makeup as Lisp code. The fundamental data structure in Lisp is a list (in Clojure we have some more data structures, we will not worry about that now). The first part of a list is interpreted as the operator, and the rest as the operands.&lt;/p&gt;&lt;p&gt;So for example in:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;+ 1 2 &amp;#40;&amp;#42; 3 4&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The operator is &lt;code&gt;+&lt;/code&gt; and the operands are 1, 2, and &lt;code&gt;&amp;#40;&amp;#42; 3 4&amp;#41;&lt;/code&gt;. Lisp applies the operator to the operands and this leads to the result of 12 in the case of &lt;code&gt;&amp;#40;&amp;#42; 3 4&amp;#41;&lt;/code&gt; and 15 in the case of &lt;code&gt;&amp;#40;+ 1 2 12&amp;#41;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;The &lt;a href='https://en.wikipedia.org/wiki/Abstract_syntax_tree'&gt;abstract syntax tree&lt;/a&gt; (AST) looks like this: &lt;img src=&quot;https://i.imgur.com/qxpVOq1.png&quot; alt=&quot;AST for (+ 1 2 (* 3 4))&quot;/&gt;&lt;/p&gt;&lt;p&gt;(Source: &lt;a href='https://github.com/jiacai2050/JCScheme'&gt;https://github.com/jiacai2050/JCScheme&lt;/a&gt;)&lt;/p&gt;&lt;p&gt;As can be seen the AST of Lisp is the same as Lisp itself. A Lisp is a language that is written in an AST, when the language is interpreted or compiled these code trees can be manipulated.&lt;/p&gt;&lt;p&gt;Now, let's look at the seven or so special forms of the language. The rest of Lisp can be implemented in these special forms. (Note: in reality Lisp is not implemented this way, there are some more special forms used in most Lisps for for example performance and usability reasons).&lt;/p&gt;&lt;p&gt;My description of these special forms (from which &lt;code&gt;eval&lt;/code&gt; can be created) is roughly based on the article &lt;a href='https://www.paulgraham.com/rootsoflisp.html'&gt;Roots of Lisp&lt;/a&gt; of Paul Graham where he explains what McCarthy has discovered. The original definitions of McCarthy can be found &lt;a href='https://www-formal.stanford.edu/jmc/recursive/node3.html'&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;In Lisp there are about seven fundamental forms:&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;code&gt;atom&lt;/code&gt;&quot;&gt;&lt;/a&gt;&lt;code&gt;atom&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;Everything in Lisp is either a list or an atom. (In Clojure we also have some other types like vectors, but we do not worry about that.) Atoms are for example numbers (1), strings (&quot;hello&quot;) or symbols (add1). Lists consist of parentheses surrounding atoms separated by whitespace or other lists or both.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;code&gt;quote&lt;/code&gt;&quot;&gt;&lt;/a&gt;&lt;code&gt;quote&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;Quoting an expression means that the expression does not need to be evaluated. This is similar to our use of quotes in natural language, where we use quotes to refer to the symbol itself instead to the meaning. To &quot;say your name&quot; I reply with &quot;Erwin&quot;, to &quot;say 'your name'&quot; I reply with &quot;your name&quot;. The quote operator can be used to blur the distinction between code and data. By quoting code you can pass it as data to another method which can then inspect and evaluate the expression. To quote you can use the operator &lt;code&gt;quote&lt;/code&gt; or put a &lt;code&gt;'&lt;/code&gt; in front of the expression.&lt;/p&gt;&lt;p&gt;Example: &lt;code&gt;'&amp;#40;+ 1 2 3&amp;#41;&lt;/code&gt;. Which is equal to &lt;code&gt;&amp;#40;quote &amp;#40;+ 1 2 3&amp;#41;&amp;#41;&lt;/code&gt;. When this expression is evaluated the result is &lt;code&gt;&amp;#40;+ 1 2 3&amp;#41;&lt;/code&gt; (instead of 6, the result of evaluating the unquoted &lt;code&gt;&amp;#40;+ 1 2 3&amp;#41;&lt;/code&gt;).&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;code&gt;eq?&amp;#95;a&amp;#95;b&lt;/code&gt;&quot;&gt;&lt;/a&gt;&lt;code&gt;eq? a b&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;&lt;code&gt;&amp;#40;eq? a b&amp;#41;&lt;/code&gt; returns true if the values of &lt;em&gt;a&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt; are the same atom or both the empty list (defined as &lt;code&gt;'&amp;#40;&amp;#41;&lt;/code&gt;), and false otherwise.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;code&gt;cons&amp;#95;a&amp;#95;l&lt;/code&gt;&quot;&gt;&lt;/a&gt;&lt;code&gt;cons a l&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;&lt;code&gt;cons&lt;/code&gt; stands for construct and is used to add one element &lt;em&gt;a&lt;/em&gt; to a list &lt;em&gt;l&lt;/em&gt;. Lisp lists are chains of cons cells, where the second element points to the first element of the next cons cell (a &lt;a href='https://macromancy.com/2014/01/16/data-structures-clojure-singly-linked-list.html'&gt;linked list&lt;/a&gt;). The last element of a list is the empty list &lt;code&gt;'&amp;#40;&amp;#41;&lt;/code&gt; (or nil).&lt;/p&gt;&lt;p&gt;Note that Clojure does not use the &lt;code&gt;cons&lt;/code&gt; cell as described above to create a list. Clojure has &lt;a href='https://clojure.org/reference/sequences'&gt;&lt;code&gt;sequences&lt;/code&gt;&lt;/a&gt;. Again, we will not worry about that now since the operations supported are similar, only the underlying implementation is different.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;code&gt;car&amp;#95;l&lt;/code&gt;&quot;&gt;&lt;/a&gt;&lt;code&gt;car l&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;&lt;code&gt;&amp;#40;car l&amp;#41;&lt;/code&gt; returns the first item in a list. In Clojure this form is called &lt;a href='https://clojuredocs.org/clojure.core/first'&gt;&lt;code&gt;first&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;code&gt;cdr&amp;#95;l&lt;/code&gt;&quot;&gt;&lt;/a&gt;&lt;code&gt;cdr l&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;&lt;code&gt;&amp;#40;cdr l&amp;#41;&lt;/code&gt; returns everything but the first item in a list. In Clojure this form is called &lt;a href='https://clojuredocs.org/clojure.core/rest'&gt;&lt;code&gt;rest&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;code&gt;car&lt;/code&gt; comes from &quot;Contents of the Address part of Register number&quot; and &lt;code&gt;cdr&lt;/code&gt; from &quot;Contents of the Decrement part of Register number&quot;. They refer to the way cons cells were stored in early computers. This is no longer the way it is, but Lispers have decided to stay with it because you can easily combine them. E.g., the car of the &lt;code&gt;cdr&lt;/code&gt; (the second element of a list) is the &lt;code&gt;cadr&lt;/code&gt;. Clojure breaks this connection with these roots, but has introduced other forms to make it easier to chain methods together (e.g., &lt;a href='https://clojuredocs.org/clojure.core/-%3E'&gt;-&gt;&lt;/a&gt;) and has special utility methods like &lt;code&gt;nth&lt;/code&gt; to obtain the nth element from a list.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;&lt;code&gt;cond&amp;#95;&amp;lt;p1&amp;gt;&amp;#95;&amp;lt;e1&amp;gt;&amp;#95;...&amp;#95;&amp;lt;pn&amp;gt;&amp;#95;&amp;lt;en&amp;gt;&lt;/code&gt;&quot;&gt;&lt;/a&gt;&lt;code&gt;cond &amp;lt;p1&amp;gt; &amp;lt;e1&amp;gt; ... &amp;lt;pn&amp;gt; &amp;lt;en&amp;gt;&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;A conditional (conditionals were among other things first introduced in the paper of McCarthy). If &lt;em&gt;p&lt;sub&gt;n&lt;/sub&gt;&lt;/em&gt; is true &lt;em&gt;e&lt;sub&gt;n&lt;/sub&gt;&lt;/em&gt; is evaluated. Also an :else clause can be introduced if no predicates are true.&lt;/p&gt;&lt;p&gt;So in &lt;code&gt;&amp;#40;cond &amp;#40;p&amp;lt;sub&amp;gt;1&amp;lt;/sub&amp;gt; n&amp;lt;sub&amp;gt;1&amp;lt;/sub&amp;gt;&amp;#41; &amp;#40;p&amp;lt;sub&amp;gt;2&amp;lt;/sub&amp;gt; n&amp;lt;sub&amp;gt;2&amp;lt;/sub&amp;gt;&amp;#41; :else &amp;quot;Hi&amp;quot;&amp;#41;&lt;/code&gt; the result is &lt;em&gt;n&lt;sub&gt;1&lt;/sub&gt;&lt;/em&gt; if &lt;em&gt;p&lt;sub&gt;1&lt;/sub&gt;&lt;/em&gt; is true, &lt;em&gt;n&lt;sub&gt;2&lt;/sub&gt;&lt;/em&gt; if &lt;em&gt;p&lt;sub&gt;1&lt;/sub&gt;&lt;/em&gt; is false, and &lt;em&gt;p&lt;sub&gt;2&lt;/sub&gt;&lt;/em&gt; is true, and &lt;code&gt;&amp;quot;Hi&amp;quot;&lt;/code&gt; if both &lt;em&gt;p&lt;sub&gt;1&lt;/sub&gt;&lt;/em&gt; and &lt;em&gt;p&lt;sub&gt;2&lt;/sub&gt;&lt;/em&gt; are false.&lt;/p&gt;&lt;p&gt;Besides these fundamental forms you can create functions with &lt;code&gt;fn&lt;/code&gt;. In a function you have a list of arguments and a list of expressions. The value of the arguments are assigned to the values that are passed during the function call (this becomes relevant later). A lambda expression (anonymous function) is created like this:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;fn &amp;#40;arg&amp;#41; &amp;#40;+ arg 1&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;And you call the lambda expression as follows:&lt;pre&gt;&lt;code&gt;&amp;#40;&amp;#40;fn &amp;#40;arg&amp;#41; &amp;#40;+ arg 1&amp;#41;&amp;#41; 1&amp;#41; ;; =&amp;gt; 2
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This can be read as &quot;call the lambda expression with argument &lt;code&gt;arg&lt;/code&gt; and body &lt;code&gt;arg plus 1&lt;/code&gt; with the argument 1 substituted for &lt;code&gt;arg&lt;/code&gt;, resulting in &lt;code&gt;&amp;#40;+ 1 1&amp;#41;&lt;/code&gt; which evaluates to 2&quot;.&lt;/p&gt;&lt;p&gt;Expressions can be bound to a symbol in Clojure with &lt;code&gt;defn&lt;/code&gt; as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn add1 &amp;#91;arg&amp;#93;
 &amp;#40;+ arg 1&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Here &lt;code&gt;add1&lt;/code&gt; with argument &lt;code&gt;arg&lt;/code&gt; is bound to &lt;code&gt;&amp;#40;+ arg 1&amp;#41;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;As said Clojure has more collection types than the list. Clojure also contains &lt;a href='https://clojure.org/reference/data_structures'&gt;maps, vectors and sets&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;It is interesting to note that these other data structures are implemented in Clojure in such a way that they are immutable (unchangeable). And because they share underlying structures when being copied they have very good performance characteristics. To learn some more about this you can view &lt;a href='https://www.youtube.com/watch?v=dGVqrGmwOAw'&gt;a video where the creator of Clojure explains this how these data structures are implemented&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;One more thing you will see in the implementation below: some data structures are demarcated by different types of symbols. The vector uses the &lt;code&gt;&amp;#91;&lt;/code&gt; and &lt;code&gt;&amp;#93;&lt;/code&gt;. In Clojure the argument list to a function or definition is a vector (not a list) and looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;fn &amp;#91;arg&amp;#93; &amp;#40;+ arg 1&amp;#41; 1&amp;#41; ;; =&amp;gt; 2
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Since it supports the same basic operations as a list (like &lt;code&gt;first&lt;/code&gt;, &lt;code&gt;empty, or &lt;/code&gt;rest`) it is fine to think about it as a list.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;example&amp;#95;of&amp;#95;use:&amp;#95;implementing&amp;#95;&lt;code&gt;map&lt;/code&gt;&quot;&gt;&lt;/a&gt;Example of use: implementing &lt;code&gt;map&lt;/code&gt;&lt;/h3&gt;&lt;p&gt;To define functions and to evaluate them often recursion is used. Below we will define a procedure that is called &lt;code&gt;map&lt;/code&gt;. &lt;code&gt;map&lt;/code&gt; applies a given function &lt;em&gt;f&lt;/em&gt; to every argument in a list (coll) and returns a list with the results. So when we do &lt;code&gt;&amp;#40;map add1 '&amp;#40;1 2 3&amp;#41;&amp;#41;&lt;/code&gt; (using &lt;code&gt;add1&lt;/code&gt; defined above) the result will be &lt;code&gt;&amp;#40;2 3 4&amp;#41;&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn map &amp;#91;f coll&amp;#93;
 &amp;#40;if &amp;#40;empty? coll&amp;#41; '&amp;#40;&amp;#41;
  &amp;#40;cons &amp;#40;f &amp;#40;first coll&amp;#41;&amp;#41; &amp;#40;map f &amp;#40;rest coll&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is done by &lt;code&gt;cdr&lt;/code&gt;ing (&quot;&lt;code&gt;rest&lt;/code&gt;ing&quot; in the case of Clojure) down a list and &lt;code&gt;cons&lt;/code&gt;ing up the result. It applies f to the first element of the list, and combines (&lt;code&gt;cons&lt;/code&gt;) the result with f mapped to the rest of the list. The recursion breaks if the collection is empty. The evaluator has a lot of these type of recursive definitions as well so it is crucial to understand.&lt;/p&gt;&lt;p&gt;The seven forms above (&lt;code&gt;map&lt;/code&gt; is not a primitive) are all the primitives you need to create a meta-circular evaluator.&lt;/p&gt;&lt;p&gt;Now, in an actual Lisp implementation there are a lot more primitives. The code belows also uses more forms. Most of them can be implemented in the code below, but others can't. The reason for that is that sometimes the evaluation order matters.&lt;/p&gt;&lt;p&gt;Another form we will see is &lt;a href='https://clojuredocs.org/clojure.core/let'&gt;&lt;code&gt;let&lt;/code&gt;&lt;/a&gt;, which is of the form&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;let &amp;#91;&amp;lt;var1&amp;gt; &amp;lt;val1&amp;gt; &amp;lt;varn&amp;gt; &amp;lt;valn&amp;gt;&amp;#93; &amp;lt;body&amp;gt;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;a href='https://clojuredocs.org/clojure.core/let'&gt;&lt;code&gt;let&lt;/code&gt;&lt;/a&gt; can be used to bind variables (var) to value (val) (to declare variables basically). These are in scope in the body. This let can roughly be written as:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;&amp;#40;fn &amp;#91;&amp;lt;var1&amp;gt; &amp;lt;varn&amp;gt;&amp;#93; &amp;lt;body&amp;gt;&amp;#41; &amp;lt;val1&amp;gt; &amp;lt;valn&amp;gt;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Where you create a lambda where the variables are substituted for the values.&lt;/p&gt;&lt;p&gt;This is impossible to implement in a normal function, since the variables are &lt;em&gt;always&lt;/em&gt; evaluated. When evaluation order needs to be controlled, a so-called macro can be created.&lt;/p&gt;&lt;p&gt;A macro hooks provides a convenient way to hook directly into the abstract syntax tree and change it at compile time (before the code runs). We will not be using or supporting macro's in this meta-circular evaluator, but it is definitely possible. If you want to learn more about macros you can read Paul Graham's &lt;a href='https://www.paulgraham.com/onlisp.html'&gt;On Lisp&lt;/a&gt; or Doug Hoyte's &lt;a  href=&quot;https://www.amazon.com/gp/product/1435712757/ref=as&lt;i&gt;li&lt;/i&gt;tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1435712757&amp;linkCode=as2&amp;tag=evalapply-20&amp;linkId=F3253FX5SJN7YEHG&quot;&gt;Let Over Lambda&lt;/a&gt;&lt;img src=&quot;https://ir-na.amazon-adsystem.com/e/ir?t=evalapply-20&amp;l=as2&amp;o=1&amp;a=1435712757&quot; width=&quot;1&quot; height=&quot;1&quot; border=&quot;0&quot; alt=&quot;&quot; style=&quot;border:none !important; margin:0px !important;&quot; /&gt;.&lt;/p&gt;&lt;p&gt;Now we have defined all the basic operators. Let's look at the meta-circular evaluator.&lt;/p&gt;&lt;h1&gt;&lt;a name=&quot;the&amp;#95;implementation&amp;#95;of&amp;#95;the&amp;#95;meta-circular&amp;#95;evaluator&quot;&gt;&lt;/a&gt;The implementation of the meta-circular evaluator&lt;/h1&gt;&lt;p&gt;The meta-circular evaluator consists of two methods: &lt;code&gt;eval&lt;/code&gt; and &lt;code&gt;apply&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;These methods call each other recursively as follows. This can be displayed as follows:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/iyviGMz.png&quot;&gt; &lt;img src=&quot;https://i.imgur.com/iyviGMz.png&quot; alt=&quot;Eval apply cycle visualized&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;(Source: &lt;a href='https://github.com/jiacai2050/JCScheme'&gt;https://github.com/jiacai2050/JCScheme&lt;/a&gt;)&lt;/p&gt;&lt;p&gt;If no descriptive names are used for definitions inside &lt;code&gt;eval&lt;/code&gt; and &lt;code&gt;apply&lt;/code&gt;, the whole evaluator fits on one page. As shown in the &lt;a href='https://www.softwarepreservation.org/projects/LISP/book/LISP%201.5%20Programmers%20Manual.pdf#21'&gt;Lisp manual (p. 13)&lt;/a&gt; it fits on one page, and as demonstrated in SICP lecture 7A: &lt;a href='https://www.youtube.com/watch?v=0m6hoOelZH8&amp;t=34m36s'&gt;on a blackboard&lt;/a&gt;. In the current implementation a bit more descriptive names are used since it helps for clarity. And also a somewhat sophisticated environment structure is used to store procedures. Therefore this code does not fit on one page, but it is definitely still a short program.&lt;/p&gt;&lt;p&gt;Unfortunately the implementation described below is possibly not truly a meta-circular evaluator. A defining characteristic of a meta-circular evaluator is that it is written in the language it evaluates. This evaluator is written in Clojure, but it cannot evaluate everything of Clojure. What it can evaluate looks a lot like Scheme translated to Clojure, because in fact it is. But... Since Clojure is a Lisp and Scheme is a Lisp, I think the name meta-circular evaluator is still warranted.&lt;/p&gt;&lt;p&gt;Now we will implement &lt;code&gt;eval&lt;/code&gt; and &lt;code&gt;apply&lt;/code&gt;.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;eval&quot;&gt;&lt;/a&gt;Eval&lt;/h2&gt;&lt;p&gt;&lt;code&gt;eval&lt;/code&gt; is a procedure that takes two arguments: an expression and an environment. And &lt;a href='https://www.youtube.com/watch?v=0m6hoOelZH8&amp;t=5m31s'&gt;like every interesting procedure, it is a case analysis&lt;/a&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn eval &amp;#91;exp env&amp;#93;
      &amp;#40;cond &amp;#40;self-evaluating? exp&amp;#41; exp
            &amp;#40;variable? exp&amp;#41; &amp;#40;lookup-variable-value exp env&amp;#41;
            &amp;#40;quoted? exp&amp;#41; &amp;#40;text-of-quotation exp&amp;#41;
            &amp;#40;assignment? exp&amp;#41; &amp;#40;eval-assignment exp env&amp;#41;
            &amp;#40;definition? exp&amp;#41; &amp;#40;eval-definition exp env&amp;#41;
            &amp;#40;if? exp&amp;#41; &amp;#40;eval-if exp env&amp;#41;
            &amp;#40;lambda? exp&amp;#41; &amp;#40;make-procedure &amp;#40;lambda-parameters exp&amp;#41;
                                          &amp;#40;lambda-body exp&amp;#41;
                                          env&amp;#41;
            &amp;#40;begin? exp&amp;#41; &amp;#40;eval-sequence &amp;#40;begin-actions exp&amp;#41; env&amp;#41;
            &amp;#40;cond? exp&amp;#41; &amp;#40;eval &amp;#40;cond-&amp;gt;if exp&amp;#41; env&amp;#41;
            &amp;#40;application? exp&amp;#41; &amp;#40;apply &amp;#40;eval &amp;#40;operator exp&amp;#41; env&amp;#41;
                                      &amp;#40;list-of-values &amp;#40;operands exp&amp;#41; env&amp;#41;&amp;#41;
            :else &amp;#40;error &amp;quot;Unknown expression type -- EVAL&amp;quot; exp&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When we call &lt;code&gt;eval&lt;/code&gt; with a quoted expression to evaluate (e.g., &lt;code&gt;&amp;#40;eval 'definition 'env&amp;#41;&lt;/code&gt; in an environment, it will look at what type of expression we are dealing with, and then dispatch to another procedure to handle it.&lt;/p&gt;&lt;p&gt;I'll first go over it just describing &lt;code&gt;eval&lt;/code&gt; in words, and next dive deeper into the routines. When an expression &lt;code&gt;exp&lt;/code&gt; is self-evaluating (like a string [&quot;hello&quot;], a number [1] or a boolean [&lt;code&gt;true&lt;/code&gt;]) &lt;code&gt;eval&lt;/code&gt; just gets the expression back. If &lt;code&gt;exp&lt;/code&gt; is a variable (&lt;code&gt;a&lt;/code&gt;), we look up the value of the variable in the environment (we will discuss how this works later). If &lt;code&gt;exp&lt;/code&gt; is a definition we want to define the value in the environment. (If we define (&lt;code&gt;defn a &amp;quot;hello&amp;quot;&lt;/code&gt;) we want &quot;a&quot; stored in the environment to be &quot;hello&quot;, and when we look up the variable a later we want to have &quot;hello&quot; returned.) If &lt;code&gt;exp&lt;/code&gt; is an assignment (&lt;code&gt;set! a &amp;quot;hi&amp;quot;&lt;/code&gt;), we will look up &lt;code&gt;a&lt;/code&gt; in the environment, and set it to a new value. If &lt;code&gt;exp&lt;/code&gt; is a lambda expression (anonymous function) we create a procedure of this lambda expression (we create a list tagged with the flag 'procedure), where we store the parameters and the body of the procedure alongside with the current environment captured in it (see &lt;code&gt;make-procedure&lt;/code&gt; below). Next, we have an if-statement and conditional: a conditional is transformed to a list of if-statements via a routine named &lt;code&gt;cond-&amp;gt;if&lt;/code&gt;. In an if-statement: if the predicate is true the first clause is evaluated, and if false the second clause is evaluated. For example, &lt;code&gt;&amp;#40;if p 'n&amp;lt;sub&amp;gt;1&amp;lt;/sub&amp;gt; 'n&amp;lt;sub&amp;gt;2&amp;lt;/sub&amp;gt;&amp;#41;&lt;/code&gt; leads to &lt;code&gt;n&amp;lt;sub&amp;gt;1&amp;lt;/sub&amp;gt;&lt;/code&gt; if &lt;code&gt;p&lt;/code&gt; is true and to &lt;code&gt;n&amp;lt;sub&amp;gt;2&amp;lt;/sub&amp;gt;&lt;/code&gt; otherwise.&lt;/p&gt;&lt;p&gt;The above is all reasonably straightforward. It is a way to implement all the reserved words. As an aside, Gerald Jay Sussman states:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;The number of reserved words that should exist in a language should be no more than a person can remember on its fingers and toes. I get very upset with languages which have hundreds or reserved words. (&lt;a href='https://www.youtube.com/watch?v=0m6hoOelZH8&amp;t=17m54s'&gt;Source&lt;/a&gt;) &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;If the expression does not start with a reserved word, the  expression is an application. This means we apply the result of evaluating the operator of the expression in the environment, to the list of values that follow, each evaluated in the environment.&lt;/p&gt;&lt;p&gt;First we look at &lt;code&gt;list-of-values&lt;/code&gt;, which is implemented as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn list-of-values &amp;#91;exps env&amp;#93;
  &amp;#40;if &amp;#40;no-operands? exps&amp;#41;
    '&amp;#40;&amp;#41;
    &amp;#40;cons &amp;#40;eval &amp;#40;first-operand exps&amp;#41; env&amp;#41;
          &amp;#40;list-of-values &amp;#40;rest-operands exps&amp;#41; env&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is a recursive definition (like &lt;code&gt;map&lt;/code&gt; above) where we construct a new list with as first argument the first operand evaluated in the environment, and as the rest, the rest of the operands evaluated in the environment. When we come to the empty list &lt;code&gt;'&amp;#40;&amp;#41;&lt;/code&gt; (the second element of the last cons cell in a linked list) the recursion breaks and we return the empty list &lt;code&gt;'&amp;#40;&amp;#41;&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;We will discuss the implementation of &lt;code&gt;apply&lt;/code&gt; after we have looked at the inner definitions of &lt;code&gt;eval&lt;/code&gt; a little bit closer. These consist of routines to detect expression, routines to get information out of expressions, and routines to transform expressions.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;routines&amp;#95;to&amp;#95;detect&amp;#95;expressions.&quot;&gt;&lt;/a&gt;Routines to detect expressions.&lt;/h3&gt;&lt;p&gt;First a little heads up: all definitions used above to get information out of expressions (like &lt;code&gt;first-operand&lt;/code&gt; and &lt;code&gt;rest-operands&lt;/code&gt;) are all implemented with &lt;code&gt;car&lt;/code&gt;s and &lt;code&gt;cdr&lt;/code&gt;s (&lt;code&gt;first&lt;/code&gt; and &lt;code&gt;rest&lt;/code&gt; in Clojure). E.g.,&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn first-operand &amp;#91;args&amp;#93; &amp;#40;first args&amp;#41;&amp;#41;
&amp;#40;defn rest-operands &amp;#91;args&amp;#93; &amp;#40;rest args&amp;#41;&amp;#41;
&amp;#40;defn no-operands? &amp;#91;args&amp;#93; &amp;#40;empty? args&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Detecting what type of an expression we are dealing with, is done by comparing the first element of the list via &lt;code&gt;tagged-list&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn tagged-list? &amp;#91;exp tag&amp;#93;
  &amp;#40;and &amp;#40;list? exp&amp;#41; &amp;#40;= &amp;#40;first exp&amp;#41; tag&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This checks if the expression is a list, and (using the code inspecting facilities of Lisp) if the first expression is equal to the tag.&lt;/p&gt;&lt;p&gt;For example, to see if a variable is a definition or quoted we check if the first element is respectively the symbol &lt;code&gt;'quote&lt;/code&gt; or &lt;code&gt;'defn&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn quoted? &amp;#91;exp&amp;#93; &amp;#40;tagged-list? exp 'quote&amp;#41;&amp;#41;
&amp;#40;defn definition? &amp;#91;exp&amp;#93; &amp;#40;tagged-list? exp 'defn&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And in a similar manner:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn lambda? &amp;#91;exp&amp;#93; &amp;#40;tagged-list? exp 'fn&amp;#41;&amp;#41;
&amp;#40;defn assignment? &amp;#91;exp&amp;#93; &amp;#40;tagged-list? exp 'set!&amp;#41;&amp;#41;
&amp;#40;defn begin? &amp;#91;exp&amp;#93; &amp;#40;tagged-list? exp 'do&amp;#41;&amp;#41;
&amp;#40;defn true? &amp;#91;x&amp;#93; &amp;#40;not &amp;#40;= x false&amp;#41;&amp;#41;&amp;#41;
&amp;#40;defn false? &amp;#91;x&amp;#93; &amp;#40;= x false&amp;#41;&amp;#41;
&amp;#40;defn cond? &amp;#91;exp&amp;#93; &amp;#40;tagged-list? exp 'cond&amp;#41;&amp;#41;
&amp;#40;defn compound-procedure? &amp;#91;p&amp;#93; &amp;#40;tagged-list? p 'procedure&amp;#41;&amp;#41;
&amp;#40;...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;Note that if a definition contains a boolean result (true or false), by convention we end the definition with a question mark &lt;code&gt;?&lt;/code&gt;.&lt;p&gt;This is how routines to detect expressions are implemented.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;routines&amp;#95;that&amp;#95;get&amp;#95;information&amp;#95;out&amp;#95;of&amp;#95;expressions&quot;&gt;&lt;/a&gt;Routines that get information out of expressions&lt;/h3&gt;&lt;p&gt;Beside routines to detect expressions we have some procedures to get information out of expressions. We know the syntax of our language and we know at which position certain elements should be located. First we define some helper methods to get certain elements out of a list besides the rest and the first, so for example the second is:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn second &amp;#91;exp&amp;#93; &amp;#40;first &amp;#40;rest exp&amp;#41;&amp;#41;&amp;#41; ; cadr
&amp;#40;defn rest-after-second &amp;#91;exp&amp;#93; &amp;#40;rest &amp;#40;rest exp&amp;#41;&amp;#41;&amp;#41; ; cddr
&amp;#40;...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;These routines are implemented in Clojure as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn operator &amp;#91;exp&amp;#93; &amp;#40;first exp&amp;#41;&amp;#41;
&amp;#40;defn operands &amp;#91;exp&amp;#93; &amp;#40;rest exp&amp;#41;&amp;#41;
&amp;#40;defn text-of-quotation &amp;#91;exp&amp;#93; &amp;#40;second exp&amp;#41;&amp;#41;
&amp;#40;defn assignment-variable &amp;#91;exp&amp;#93; &amp;#40;second exp&amp;#41;&amp;#41;
&amp;#40;defn lambda-parameters &amp;#91;exp&amp;#93; &amp;#40;second exp&amp;#41;&amp;#41;
&amp;#40;defn lambda-body &amp;#91;exp&amp;#93; &amp;#40;rest-after-second exp&amp;#41;&amp;#41;
&amp;#40;...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Here we see that for example &lt;code&gt;lamba-body&lt;/code&gt; is the &lt;code&gt;rest-after-second&lt;/code&gt;. Which is indeed the case. If we look at:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;fn &amp;#91;a b c d&amp;#93; &amp;#40;+ a b &amp;#40;&amp;#42; c d&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We see that everything after the second element &lt;code&gt;&amp;#40;a b c d&amp;#41;&lt;/code&gt; is the body.&lt;/p&gt;&lt;p&gt;All the other implementations of routines that get information out of expressions are defined in the same manner.&lt;/p&gt;&lt;h3&gt;&lt;a name=&quot;routines&amp;#95;to&amp;#95;manipulate&amp;#95;expressions&quot;&gt;&lt;/a&gt;Routines to manipulate expressions&lt;/h3&gt;&lt;p&gt;As seen in the definition of &lt;code&gt;eval&lt;/code&gt; above, when an expression is a lambda expression (as identified by &lt;code&gt;lambda?&lt;/code&gt;), we make a procedure. This is implemented as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn make-procedure &amp;#91;parameters body env&amp;#93;
  &amp;#40;list 'procedure parameters body env&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So we create a new list via the procedure &lt;code&gt;list&lt;/code&gt; (which is a routine to create a linked list via a chain of &lt;code&gt;cons&lt;/code&gt;'es). Note that the procedure creates a new list where the environment is stored in. This is a way to create something called a closure: the environment at the moment the procedure was called is captured. Next when we look at &lt;code&gt;apply&lt;/code&gt; we will see how this environment is retrieved. Furthermore, we will discuss the difference between two types of scope (dynamic and lexical) and their implementation later.&lt;/p&gt;&lt;p&gt;In a similar manner as &lt;code&gt;make-procedure&lt;/code&gt; we can create a new type of expression from an if-expresion in &lt;code&gt;cond-&amp;gt;if&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Note: using &lt;code&gt;-&amp;gt;&lt;/code&gt; is a convention to signify the routine is a conversion.&lt;/p&gt;&lt;p&gt;Via &lt;code&gt;cond-&amp;gt;if&lt;/code&gt; a &lt;code&gt;cond&lt;/code&gt; expressions (conditional) can be converted using an internal procedure named &lt;code&gt;expand-clauses&lt;/code&gt;. &lt;code&gt;expand-clauses&lt;/code&gt; recursively expands every clause of a &lt;code&gt;cond&lt;/code&gt; expression to nested if-statements.&lt;/p&gt;&lt;p&gt;So &lt;code&gt;eval&lt;/code&gt; evaluated an expression by detecting the type of expression, getting the information out of the expression and possibly converting it to something else, If it does not start with one of the reserved words it is treated as an application. This will be handled with &lt;code&gt;apply&lt;/code&gt; in the next segment.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;apply&quot;&gt;&lt;/a&gt;Apply&lt;/h2&gt;&lt;p&gt;We have arrived at &lt;code&gt;apply&lt;/code&gt;. &lt;code&gt;apply&lt;/code&gt; is called in &lt;code&gt;eval&lt;/code&gt; if the expression is not one of the reserved words (like &lt;code&gt;if&lt;/code&gt;, &lt;code&gt;cond&lt;/code&gt;, &lt;code&gt;fn&lt;/code&gt;, &lt;code&gt;defn&lt;/code&gt; and &lt;code&gt;set!&lt;/code&gt;). An expression is an application if it is not one of the special forms, but still a &lt;code&gt;list&lt;/code&gt;  (e.g., in the case of &lt;code&gt;&amp;#40;+ 1 2&amp;#41;&lt;/code&gt;, &lt;code&gt;+&lt;/code&gt; is not in the list of the reserved words). Then the expression will be handled by this part of &lt;code&gt;eval&lt;/code&gt; (see above):&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;...&amp;#41;
&amp;#40;apply &amp;#40;eval &amp;#40;operator exp&amp;#41; env&amp;#41;
       &amp;#40;list-of-values &amp;#40;operands exp&amp;#41; env&amp;#41;
&amp;#40;...&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We already looked at &lt;code&gt;list-of-values&lt;/code&gt; that evaluated all the operands in an environment. What remains is applying the operator to the arguments. &lt;code&gt;apply&lt;/code&gt; then feeds back the expression and the environment to &lt;code&gt;eval&lt;/code&gt;, et cetera.&lt;/p&gt;&lt;p&gt;&lt;code&gt;apply&lt;/code&gt; is a procedure that takes as input a procedure and its arguments, and produces an expression and an environment:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn apply &amp;#91;procedure arguments&amp;#93;
  &amp;#40;cond &amp;#40;primitive-procedure? procedure&amp;#41;
        &amp;#40;apply-primitive-procedure procedure arguments&amp;#41;
        &amp;#40;compound-procedure? procedure&amp;#41;
        &amp;#40;eval-sequence
         &amp;#40;procedure-body procedure&amp;#41;
         &amp;#40;extend-environment &amp;#40;procedure-parameters procedure&amp;#41;    ; variables
                             arguments                           ; values
                             &amp;#40;procedure-environment procedure&amp;#41;&amp;#41;&amp;#41; ; base environment
        :else &amp;#40;error &amp;quot;Unknown procedure type -- APPLY&amp;quot; procedure&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Again it is a case analysis. Let's go through it. We first check if a procedure is a primitive procedure with &lt;code&gt;primitive-procedure?&lt;/code&gt;. A procedure is a primitive procedure if it is looked up in the environment and it was in the list of primitive procedures defined in the environment. The primitive procedures are defined as follows, and are later added to the environment (how the environment is constructed will be discussed later).&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def primitive-procedures
  &amp;#40;list &amp;#40;list 'first first&amp;#41;
        &amp;#40;list 'rest rest&amp;#41;
        &amp;#40;list 'cons cons&amp;#41;
        &amp;#40;list 'nil? nil?&amp;#41;
        &amp;#40;list 'empty empty&amp;#41;
        &amp;#40;list 'list list&amp;#41;
        &amp;#40;list '+ +&amp;#41;
        &amp;#40;list '- -&amp;#41;
        &amp;#40;list '&amp;#42; &amp;#42;&amp;#41;
        &amp;#40;list '/ /&amp;#41;
        ;;      more primitives
        &amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If the procedure is a primitive procedure we apply the primitive procedure with the underlying apply of Clojure. At the beginning of the evaluator we store the underlying &lt;code&gt;apply&lt;/code&gt; to not confuse it with the newly defined &lt;code&gt;apply&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn apply-from-underlying-lisp &amp;#91;procedure arguments&amp;#93; &amp;#40;apply procedure arguments&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;How this apply that is built into Clojure works, is outside of the scope of this post (to be honest I don't know). Interesting to note is that these types of primitives are not essential for computation. You can do everything with lambda and something called a Y Combinator. But using that is not as convenient.&lt;/p&gt;&lt;p&gt;The application of a primitive procedure is defined as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn apply-primitive-procedure &amp;#91;proc args&amp;#93;
  &amp;#40;apply-from-underlying-lisp
   &amp;#40;primitive-implementation proc&amp;#41; args&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Where &lt;code&gt;primitive-implementation&lt;/code&gt; is a method to retrieve the procedure:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn primitive-implementation &amp;#91;proc&amp;#93; &amp;#40;second proc&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As can be seen above where the &lt;code&gt;primitives-procedures&lt;/code&gt; are defined the primitive-implementation is a symbol like &lt;code&gt;first&lt;/code&gt; or &lt;code&gt;+&lt;/code&gt;. Again, these are evaluated by the underlying Clojure implementation.&lt;/p&gt;&lt;p&gt;If we are dealing with a compound procedure (a list tagged with &lt;code&gt;procedure&lt;/code&gt;), we evaluate the sequence of elements with the routine &lt;code&gt;eval-sequence&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn eval-sequence &amp;#91;exps env&amp;#93;
  &amp;#40;if &amp;#40;last-exp? exps&amp;#41;
    &amp;#40;eval &amp;#40;first-exp exps&amp;#41; env&amp;#41;
    &amp;#40;do
      &amp;#40;eval &amp;#40;first-exp exps&amp;#41; env&amp;#41;
      &amp;#40;eval-sequence &amp;#40;rest-exps exps&amp;#41; env&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that &lt;a href='https://clojuredocs.org/clojure.core/do'&gt;&lt;code&gt;do&lt;/code&gt;&lt;/a&gt; is used to evaluate multiple expressions (in &lt;code&gt;eval&lt;/code&gt; it is detected by &lt;code&gt;begin?&lt;/code&gt;, a similar construct in Scheme).&lt;/p&gt;&lt;p&gt;&lt;code&gt;eval-sequence&lt;/code&gt; is a recursive definition where we, if we have only one expression, only evaluate this one expression in the environment, and if we have more than one expression, we evaluate the first expression and &lt;code&gt;eval-sequence&lt;/code&gt; the rest of the expressions in the environment.&lt;/p&gt;&lt;p&gt;Here &lt;code&gt;last-exp&lt;/code&gt;, &lt;code&gt;first-exp&lt;/code&gt; and &lt;code&gt;rest-exp&lt;/code&gt; are defined as follows:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn last-exp? &amp;#91;seq&amp;#93; &amp;#40;empty? &amp;#40;rest seq&amp;#41;&amp;#41;&amp;#41;
&amp;#40;defn first-exp &amp;#91;seq&amp;#93; &amp;#40;first seq&amp;#41;&amp;#41;
&amp;#40;defn rest-exps &amp;#91;seq&amp;#93; &amp;#40;rest seq&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Naturally the first expression is the first element of the sequence (of expressions). The rest of the expressions is the rest of the sequence. And we are dealing with the last expression if the rest of the sequence after it is empty.&lt;/p&gt;&lt;p&gt;Important to note is that when we use &lt;code&gt;eval-sequence&lt;/code&gt; in the definition of &lt;code&gt;apply&lt;/code&gt; we extend the environment of the evaluation with the procedure parameters, arguments, and the procedure environment itself. This way the environment of the procedure (which was stored when it was created) are available during evaluation.&lt;/p&gt;&lt;p&gt;So what exactly is this extending of an environment? And in what way are symbols added to it?&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;the&amp;#95;environment&quot;&gt;&lt;/a&gt;The environment&lt;/h2&gt;&lt;p&gt;We now go step by step through the environment.&lt;/p&gt;&lt;p&gt;An environment consists of frames stacked together in a list. A frame is empty or consists of two lists: one lists with variables, and one list with values. When a definition is looked up we look at the first frame to see if the variable is defined there. If we find it we return the value. If it is not, we look one frame further to see if it is defined there. Until we finally get to the global environment. If it is not found there we have an error (&quot;Unbound variable&quot;). So the goal of an environment is to store variables and the values associated with them.&lt;/p&gt;&lt;p&gt;A simple environment structure looks like this:&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;https://mitpress.mit.edu/sicp/full-text/book/ch3-Z-G-2.gif&quot; alt=&quot;Simple environment structure from SICP&quot;/&gt;&lt;/p&gt;&lt;p&gt;Source: &lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html#%_sec_3.2'&gt;https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html#%&lt;i&gt;sec&lt;/i&gt;3.2&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Here we see multiple frames (I, II and III) that are connected. A will find that the value of the variable x is 7, but C will find 3.&lt;/p&gt;&lt;p&gt;The environment is crucial to the evaluation process, because it determines the context in which an expression will be evaluated. Each time a procedure is applied, a new frame is created.&lt;/p&gt;&lt;p&gt;It turns out that my assumed immutability (I thought nothing could be changed, which was not completely true from a user's perspective) of Clojure made the implementation quite difficult (for me). Clojure has, unlike Scheme (the language where this evaluator was translated from), no mutable (changeable) cons cells (no actual cons cell at all as described earlier). Where in Scheme you can change the first element or last element of a list respectively with the routines &lt;code&gt;set-car!&lt;/code&gt; and &lt;code&gt;set-cdr!&lt;/code&gt;, this is not possible in Clojure.&lt;/p&gt;&lt;p&gt;We can however accomplish mutation by defining a so-called &lt;a href='https://clojure.org/reference/atoms'&gt;&lt;code&gt;Atom&lt;/code&gt;&lt;/a&gt; (different from the basic building element &lt;code&gt;atom&lt;/code&gt; defined above). An Atom in Clojure is a mutable value, that can be mutated in an atomic way, free of concurrency problems (see this &lt;a href='https://www.braveclojure.com/zombie-metaphysics/#Atoms'&gt;chapter on Metaphysics in Clojure for the Brave and True&lt;/a&gt; for an explanation).&lt;/p&gt;&lt;p&gt;The algorithm used in the Scheme version checks the first frame, loops over it (with a method called scan) and if it finds the variable, it returns the value associated with it. If it does not find anything it will loop over the enclosing environment and scans there.&lt;/p&gt;&lt;p&gt;When redefining a variable in the environment, a similar process is used. When the variable is found however, &lt;code&gt;set-car!&lt;/code&gt; is used to overwrite the variable value in that frame.&lt;/p&gt;&lt;p&gt;After using some environment structures with bugs in them (for example being unable to define recursive definitions) I found a better environment definition in the &lt;a href='https://github.com/jakemcc/sicp-study/blob/master/clojure/section4.2/src/environment.clj'&gt;SICP answers of Jake McCrary&lt;/a&gt;. The implementation has the same behavior as that of the original of the SICP.&lt;/p&gt;&lt;p&gt;We now go step by step through this environment structure by Jake McCrary.&lt;/p&gt;&lt;p&gt;The empty environment is an empty list.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def the-empty-environment '&amp;#40;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;(Note that &lt;code&gt;def&lt;/code&gt; is similar to &lt;code&gt;defn&lt;/code&gt; without arguments.)&lt;/p&gt;&lt;p&gt;To get the enclosing environment (frame) of the current environment (frame), we look at the rest from the frame we are in now.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn enclosing-environment &amp;#91;env&amp;#93; &amp;#40;rest env&amp;#41;&amp;#41;
&amp;#40;defn first-frame &amp;#91;env&amp;#93; &amp;#40;first env&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;To make a frame, we use a routine &lt;a href='https://clojuredocs.org/clojure.core/zipmap'&gt;&lt;code&gt;zipmap&lt;/code&gt;&lt;/a&gt; to add two lists of variables together which &quot;returns a map with the keys mapped to the corresponding vals&quot; (&lt;a href='https://clojuredocs.org/clojure.core/zipmap'&gt;ClojureDocs&lt;/a&gt;). A map is a list of key-value pairs.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn make-frame &amp;#91;variables values&amp;#93;
  &amp;#40;atom &amp;#40;zipmap variables values&amp;#41;&amp;#41;&amp;#41;
&amp;#40;defn frame-variables &amp;#91;frame&amp;#93; &amp;#40;keys @frame&amp;#41;&amp;#41;
&amp;#40;defn frame-values &amp;#91;frame&amp;#93; &amp;#40;vals @frame&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let's illustrate the behavior of this creating of frames with &lt;a href='https://clojuredocs.org/clojure.core/zipmap'&gt;&lt;code&gt;zipmap&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;We have a list of variables to be added to the environment:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def variables &amp;#40;list '+
                     'rest
                     'add1&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;A list of corresponding values (the primitive &lt;code&gt;+&lt;/code&gt; and rest operator, and a lambda expression and a created procedure to be added to the environment:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def values &amp;#40;list +
                  rest
                  '&amp;#40;fn &amp;#40;x&amp;#41; &amp;#40;+ x 1&amp;#41;&amp;#41;
                  '&amp;#40;procedure &amp;#40;x&amp;#41; &amp;#40;fn &amp;#40;x&amp;#41; &amp;#40;+ x 1&amp;#41;&amp;#41; {:+ + :x 2 &amp;#40;...&amp;#41;}&amp;#41;&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;When we zipmap them:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;zipmap variables values&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This leads to the following result:&lt;blockquote&gt;&lt;p&gt;{+ #object[clojure.core$&lt;i&gt;PLUS&lt;/i&gt; (...)],&lt;br&gt;  rest #object[clojure.core$rest_ (...))],&lt;br&gt;  add1 (procedure (x) (fn (x) (+ x 1)) {:+ +, :x 2, (...)})}  &lt;/p&gt;&lt;/blockquote&gt;So a frame is a map (key value pairs, differentiated with &lt;code&gt;{&lt;/code&gt; and &lt;code&gt;}&lt;/code&gt; in Clojure) with variables (keys of the map) bound to values (values of the map) (in this case the primitive objects from the underlying Clojure).&lt;/p&gt;&lt;p&gt;Next we get methods to add bindings to frames:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn add-binding-to-frame! &amp;#91;var val frame&amp;#93;
  &amp;#40;swap! frame assoc var val&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that by convention routines that mutate state are ended with an exclamation mark &lt;code&gt;!&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;&lt;code&gt;add-binding-to-frame!&lt;/code&gt; uses &lt;a href='https://clojuredocs.org/clojure.core/swap!'&gt;&lt;code&gt;swap!&lt;/code&gt;&lt;/a&gt; in combination with &lt;a href='https://clojuredocs.org/clojure.core/assoc'&gt;&lt;code&gt;assoc&lt;/code&gt;&lt;/a&gt; to associate a variable and new value to a frame. This is one of the ways to have (safe) mutable state.&lt;/p&gt;&lt;p&gt;Next we need a way to extend our environment (this is the method used in &lt;code&gt;eval&lt;/code&gt; and &lt;code&gt;eval-sequence&lt;/code&gt; to add variables and values to a frame, for example when storing the variables of a procedure in the environment where it will be evaluated in, or when new definitions are added):&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn extend-environment &amp;#91;vars vals base-env&amp;#93;
  &amp;#40;if &amp;#40;= &amp;#40;count vars&amp;#41; &amp;#40;count vals&amp;#41;&amp;#41;
    &amp;#40;cons &amp;#40;make-frame vars vals&amp;#41; base-env&amp;#41;
    &amp;#40;if &amp;#40;&amp;lt; &amp;#40;count vars&amp;#41; &amp;#40;count vals&amp;#41;&amp;#41;
      &amp;#40;error &amp;quot;Too many arguments supplied &amp;quot; vars&amp;#41;
      &amp;#40;error &amp;quot;Too few arguments supplied &amp;quot; vars&amp;#41;&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;extend-environment&lt;/code&gt; takes variables and values and a base environment. It then makes a frame of the variables and values and &lt;code&gt;cons&lt;/code&gt;es that up to the base environment. The rest is error handling for when the amount of variables and values applied are not the same (e.g., when evaluating &lt;code&gt;&amp;#40;&amp;#40;fn &amp;#40;x&amp;#41; &amp;#40;+ x 1&amp;#41;&amp;#41; 2 3&amp;#41;&lt;/code&gt; it will returns &quot;Too many arguments supplied&quot;).&lt;/p&gt;&lt;p&gt;Next, we have a method to lookup a variable in an environment. This one looks a bit more complicated because of the inner methods.&lt;/p&gt;&lt;p&gt;Know that &lt;a href='https://clojuredocs.org/clojure.core/letfn'&gt;&lt;code&gt;letfn&lt;/code&gt;&lt;/a&gt; is just like &lt;a href='https://clojuredocs.org/clojure.core/let'&gt;&lt;code&gt;let&lt;/code&gt;&lt;/a&gt;, only now we define functions and bind them to a name only available in the scope. Furthermore, &lt;code&gt;contains?&lt;/code&gt; checks if a variable is available in a map and returns true if it does, false it it does not.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn lookup-variable-value &amp;#91;variable env&amp;#93;
  &amp;#40;letfn &amp;#91;&amp;#40;env-loop &amp;#91;env&amp;#93;
            &amp;#40;letfn &amp;#91;&amp;#40;scan &amp;#91;frame&amp;#93;
                      &amp;#40;if &amp;#40;contains? frame variable&amp;#41;
                        &amp;#40;let &amp;#91;value &amp;#40;get frame variable&amp;#41;&amp;#93;
                          value&amp;#41;
                        &amp;#40;env-loop &amp;#40;enclosing-environment env&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#93;
              &amp;#40;if &amp;#40;= env the-empty-environment&amp;#41;
                &amp;#40;error &amp;quot;Unbound variable -- LOOKUP&amp;quot; variable&amp;#41;
                &amp;#40;let &amp;#91;frame &amp;#40;first-frame env&amp;#41;&amp;#93;
                  &amp;#40;scan @frame&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;env-loop env&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;What happens at the bottom of &lt;code&gt;lookup-variable-value&lt;/code&gt; is that we start an &lt;code&gt;env-loop&lt;/code&gt; with the &lt;code&gt;env&lt;/code&gt;. &lt;code&gt;env-loop&lt;/code&gt; defines a method &lt;code&gt;scan&lt;/code&gt; to look for a variable in a frame.&lt;/p&gt;&lt;p&gt;If the frame contains the variable we &lt;a href='https://clojuredocs.org/clojure.core/get'&gt;&lt;code&gt;get&lt;/code&gt;&lt;/a&gt; (get is a way to retrieve the value belonging to a key) the value belonging to the variable from the frame. Otherwise, we start a new &lt;code&gt;env-loop&lt;/code&gt; over the enclosing environment (the next frame or frames).&lt;/p&gt;&lt;p&gt;When the &lt;code&gt;env-loop&lt;/code&gt; is started we first check if we are dealing with the empty environment. If that is the case we break the recursion: we have scanned all frames in scope and we are therefore dealing with an unbound variable. If we are not dealing with the empty environment, we are getting the first frame from the (remaining) environment (remember that the environment is a list of frames), get the value from the atom by using &lt;a href='https://www.braveclojure.com/zombie-metaphysics/#Atoms'&gt;&lt;code&gt;@&lt;/code&gt;&lt;/a&gt;, and scan that.&lt;/p&gt;&lt;p&gt;So now we can understand how to lookup a variable, we also need a way to define a variable value in the environment. To accomplish this we have a similar procedure, which uses a similar scanning method as above.&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn set-variable-value! &amp;#91;variable value env&amp;#93;
  &amp;#40;letfn &amp;#91;&amp;#40;env-loop &amp;#91;env&amp;#93;
            &amp;#40;letfn &amp;#91;&amp;#40;scan &amp;#91;frame&amp;#93;
                      &amp;#40;if &amp;#40;contains? @frame variable&amp;#41;
                        &amp;#40;swap! frame assoc variable value&amp;#41;
                        &amp;#40;env-loop &amp;#40;enclosing-environment env&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#93;
              &amp;#40;if &amp;#40;= env the-empty-environment&amp;#41;
                &amp;#40;error &amp;quot;Unbound variable -- SET!&amp;quot; variable&amp;#41;
                &amp;#40;scan &amp;#40;first-frame env&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#41;&amp;#93;
    &amp;#40;env-loop env&amp;#41;&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The difference with &lt;code&gt;lookup-variable-value&lt;/code&gt; is that in &lt;code&gt;set-variable-value!&lt;/code&gt; we are trying to find the variable, and in the first frame we find which contains the variable we change this variable's value for the current value. If the frame doesn't contain it we start the &lt;code&gt;env-loop&lt;/code&gt; over the enclosing environment. The recursion breaks when we end up with the empty environment (unbound variable) or when we find a variable and have set it.&lt;/p&gt;&lt;p&gt;Furthermore,to define a variable we get the first frame of the environment and add the variable as a key with the value as a value. (So we add it to the top-level frame, the global environment.)&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn define-variable! &amp;#91;variable value env&amp;#93;
  &amp;#40;swap! &amp;#40;first-frame env&amp;#41; assoc variable value&amp;#41;&amp;#41;

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, at the beginning we setup the environment:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn setup-environment &amp;#91;&amp;#93;
  &amp;#40;let &amp;#91;initial-env
        &amp;#40;extend-environment primitive-procedure-names
                            primitive-procedure-objects
                            the-empty-environment&amp;#41;&amp;#93;
    initial-env&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We load the primitive procedures in the environment and we set &lt;code&gt;the-empty-environment&lt;/code&gt; as our base environment.&lt;/p&gt;&lt;p&gt;Now you've seen everything but a way to interact with this evaluator.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;interacting&amp;#95;with&amp;#95;the&amp;#95;evaluator&quot;&gt;&lt;/a&gt;Interacting with the evaluator&lt;/h2&gt;&lt;p&gt;Last but not least we have a way to interact with the evaluator. When we run the code a &lt;code&gt;driver-loop&lt;/code&gt; asks for input, and when it has received input it will evaluate the input in our environment:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;def input-prompt &amp;quot;;;; Eval input:&amp;quot;&amp;#41;
&amp;#40;def output-prompt &amp;quot;;;; Eval value:&amp;quot;&amp;#41;

&amp;#40;defn driver-loop &amp;#91;&amp;#93;
  &amp;#40;prompt-for-input input-prompt&amp;#41;
  &amp;#40;let &amp;#91;input &amp;#40;read&amp;#41;&amp;#93;
    &amp;#40;user-print input&amp;#41;
    &amp;#40;let &amp;#91;output &amp;#40;eval input the-global-environment&amp;#41;&amp;#93;
      &amp;#40;announce-output output-prompt&amp;#41;
      &amp;#40;user-print output&amp;#41;&amp;#41;&amp;#41;
  &amp;#40;driver-loop&amp;#41;&amp;#41;

&amp;#40;defn prompt-for-input &amp;#91;string&amp;#93;
  &amp;#40;newline&amp;#41; &amp;#40;println string&amp;#41; &amp;#40;newline&amp;#41;&amp;#41;

&amp;#40;defn announce-output &amp;#91;string&amp;#93;
  &amp;#40;newline&amp;#41; &amp;#40;println string&amp;#41; &amp;#40;newline&amp;#41;&amp;#41;

&amp;#40;defn user-print &amp;#91;object&amp;#93;
  &amp;#40;if &amp;#40;compound-procedure? object&amp;#41;
    &amp;#40;println &amp;#40;list 'compound-procedure
                   &amp;#40;procedure-parameters object&amp;#41;
                   &amp;#40;procedure-body object&amp;#41;
                   '&amp;lt;procedure-env&amp;gt;&amp;#41;&amp;#41;
    &amp;#40;println object&amp;#41;&amp;#41;&amp;#41;

'METACIRCULAR-EVALUATOR-LOADED

&amp;#40;def the-global-environment &amp;#40;setup-environment&amp;#41;&amp;#41;

&amp;#40;driver-loop&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That's it. Works like a charm.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;example&amp;#95;interaction&quot;&gt;&lt;/a&gt;Example interaction&lt;/h2&gt;&lt;p&gt;The goal of this thing was to be able to feed the evaluator program a Lisp expression, and have it return the result. So when we feed it &lt;code&gt;&amp;#40;eval '&amp;#40;defn add1 &amp;#40;fn &amp;#40;x&amp;#41; &amp;#40;+ x 1&amp;#41;&amp;#41;&amp;#41; &amp;lt;e&amp;gt;&amp;#41;&lt;/code&gt; it should know what this means and add the symbol &lt;code&gt;add1&lt;/code&gt; to the environment.&lt;/p&gt;&lt;p&gt;Here we see some interactions with the evaluator:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/0ECuo9o.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/0ECuo9o.gif&quot; alt=&quot;Interacting with the evaluator&quot; width=&quot;100%&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;p&gt;So &quot;Hello&quot; evaluates to itself since it is self-evaluating. &lt;code&gt;+&lt;/code&gt; is found in the environment and termined to be a primitive operation from the underlying Clojure. And we can also define functions like &lt;code&gt;map&lt;/code&gt; and &lt;code&gt;add1&lt;/code&gt; and apply these to arguments.&lt;/p&gt;&lt;p&gt;If you would like to see a full evaluation of an expression by hand, I can recommend watching the second part of &lt;a href='https://www.youtube.com/watch?v=0m6hoOelZH8&amp;t=36m40s'&gt;Lecture 7A of SICP&lt;/a&gt;. You can also run &lt;a href='https://github.com/transducer/clojure-experiments/blob/master/meta-circular-experiments/mc-evaluator.clj'&gt;the code&lt;/a&gt; of the evaluator and put some break points or &lt;code&gt;println&lt;/code&gt;s at strategic points.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;dynamically&amp;#95;scoped&amp;#95;environment&quot;&gt;&lt;/a&gt;Dynamically scoped environment&lt;/h2&gt;&lt;p&gt;In my journey to create a working version I also stumbled upon &lt;a href='https://github.com/matlux/metacircular-evaluator-clj/blob/master/src/clj_eval/core.clj'&gt;this implementation of Mathieu Gauthron&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;A dynamically scoped environment is a bit simpler to implement, what is defined latest is found first (instead of passing an environment along in a certain procedure scope, we just update the environment). It is a bit harder to reason about though, because in a dynamically scoped environment it is only at runtime defined what is in scope.&lt;/p&gt;&lt;p&gt;After we define what lexical and dynamic scope is, below will follow an experiment with the dynamic evaluator.&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;lexical&amp;#95;scoping&amp;#95;versus&amp;#95;dynamic&amp;#95;scoping&quot;&gt;&lt;/a&gt;Lexical scoping versus dynamic scoping&lt;/h2&gt;&lt;p&gt;Lexical scope means that the structure of the program determines which variables are in scope (for example in C-like languages the scope is defined by curly braces &lt;code&gt;{&lt;/code&gt; and &lt;code&gt;}&lt;/code&gt;. In dynamic scope the scope is defined at runtime, that what was defined latest when the program is evaluated at runtime is found first. Currently there are almost no languages with dynamic scope. Lexical scope is more logical to reason about. Nevertheless there are valid use cases for dynamic scope. A &lt;a href='https://programmers.stackexchange.com/questions/103164/when-would-dynamic-scoping-be-useful#273005'&gt;nice example&lt;/a&gt; is exception handling (throwing an exception and catching it):&lt;blockquote&gt;&lt;p&gt;Exception handling in most languages utilizes dynamic scoping; when an exception occurs control will be transferred back to the closest handler on the (dynamic) activation stack.  &lt;/p&gt;&lt;/blockquote&gt;One way to test if a language is dynamic or static is by the &lt;a href='https://stackoverflow.com/questions/32344615/program-to-check-if-the-scoping-is-lexical-or-dynamic#32347224'&gt;following idea&lt;/a&gt;:&lt;/p&gt;&lt;p&gt;First you define a method that uses a variable &lt;code&gt;scope&lt;/code&gt; in its body:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;defn test &amp;#40;fn &amp;#91;&amp;#93; scope&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;When you call this method:&lt;pre&gt;&lt;code&gt;&amp;#40;test&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;this returns&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Is not a valid symbol &amp;ndash; LOOKUP-VARIABLE-VALUE scope &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;This is because scope is not available in the environment. It is not defined.&lt;/p&gt;&lt;p&gt;Next when you introduce a new binding with the same name (&lt;code&gt;scope&lt;/code&gt;) wherein you call test:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&amp;#40;&amp;#40;fn &amp;#91;scope&amp;#93; &amp;#40;test&amp;#41;&amp;#41; &amp;#40;quote dynamic&amp;#41;&amp;#41;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;A lexically scoped language will return &quot;Is not a valid symbol &amp;ndash; LOOKUP-VARIABLE-VALUE scope&quot; as above, because the environment when the definition of &lt;code&gt;test&lt;/code&gt; was created does not contain this binding. A dynamically scoped language will return &lt;code&gt;'dynamic&lt;/code&gt;. It does not care about what the value of scope was &lt;em&gt;when test was defined&lt;/em&gt; and just looks up the nearest definition. In other words: the lexical environment was not captured.&lt;/p&gt;&lt;p&gt;(The idea for the test was obtained from &lt;a href='https://stackoverflow.com/questions/32344615/program-to-check-if-the-scoping-is-lexical-or-dynamic#32347224'&gt;this Stack Overflow answer&lt;/a&gt;, but slightly modified since our language does not know how to evaluate &lt;code&gt;let&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;As expected from the above description, &lt;a href='https://github.com/transducer/clojure-experiments/blob/master/meta-circular-experiments/mc-evaluator-dynamic.clj'&gt;the evaluator with the dynamic environment&lt;/a&gt; has the following behavior:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://i.imgur.com/fExSUfz.gif&quot;&gt; &lt;img src=&quot;https://i.imgur.com/fExSUfz.gif&quot; alt=&quot;Interacting with the dynamic evaluator&quot; width=&quot;100%&quot; /&gt; &lt;/a&gt;&lt;/p&gt;&lt;h2&gt;&lt;a name=&quot;closing&amp;#95;remarks&quot;&gt;&lt;/a&gt;Closing remarks&lt;/h2&gt;&lt;p&gt;What we have seen above is some nice copy, paste and explaining. For this I was inspired by SICP, and the evaluators of &lt;a href='https://github.com/gregsexton/SICP-Clojure'&gt;Greg Sexton&lt;/a&gt;, &lt;a href='https://github.com/jakemcc/sicp-study/'&gt;Jake McCrary&lt;/a&gt; and &lt;a href='https://github.com/matlux/metacircular-evaluator-clj/blob/master/src/clj_eval/core.clj'&gt;Mathieu Gauthron&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;What we have seen above is an elegant model of computation. Using about seven primitives we can define &lt;code&gt;eval&lt;/code&gt; in which we can implement our language.&lt;/p&gt;&lt;p&gt;The idea that an evaluator is just another program (and such a short one) is remarkable. Once you understand how the meta-circular evaluator works, it becomes possible to change the implementation and create interpreters for other languages.&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Indeed, new languages are often invented by first writing an evaluator that embeds the new language within an existing high-level language. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;(&lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-27.html'&gt;Source&lt;/a&gt;)&lt;/p&gt;&lt;p&gt;The fact that Lisp code trees can be changed at runtime or compile time makes it so that it is possible to deeply influence the language. Where in languages like Java you have to wait for a committee to put a new feature into a language, in Lisp you don't have to wait and can implement these features yourself.&lt;/p&gt;&lt;p&gt;One quote (incorrectly stated according to the supposed author but nevertheless instructive) describes the difference between languages without the ability to modify its structure (like Java or APL) and Lisp as follows:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;APL is like a beautiful diamond - flawless, beautifully symmetrical. But you can't add anything to it. If you try to glue on another diamond, you don't get a bigger diamond. Lisp is like a ball of mud. Add more and it's still a ball of mud - it still looks like Lisp. &lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;One nice example of the ball of mud idea is the &lt;a href='https://clojure.github.io/core.async/'&gt;&lt;code&gt;go&lt;/code&gt;-routine&lt;/a&gt; that is added to Clojure for asynchronous programming (communicating sequential processes). Go also has them, but for Go is it a fundamental language feature. Because the language can be fundamentally and syntactically changed, it could be introduced as a library in Clojure. (See &lt;a href='https://www.leonardoborges.com/writings/2013/07/06/clojure-core-dot-async-lisp-advantage/'&gt;here&lt;/a&gt; for more information.)&lt;/p&gt;&lt;p&gt;In SICP among other things the evaluator is extended and modified to become an evaluator for:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-27.html'&gt;An evaluator with lazy (call-by-name) evaluation&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-29.html#%_sec_4.4'&gt;A declarative Logic Programming language&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;And the same idea is used to create an &lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-32.html#%_sec_5.2'&gt;evaluator for machine language&lt;/a&gt; and to create a &lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-35.html#%_sec_5.5.1'&gt;compiler&lt;/a&gt; that converts Scheme to a machine language. In SICP it is also explained how the mechanisms works by which procedures call other procedures and return values to their callers (which the meta-circular evaluator borrows from the underlying Lisp).&lt;/p&gt;&lt;p&gt;One of the other things that is missing in the above implementation is a way to define &lt;a href='stackoverflow.com/questions/267862/what-makes-lisp-macros-so-special#4621882'&gt;macros&lt;/a&gt;, which are used for defining syntax language extensions. I am not so well-versed in them yet. I might play with them in a later post.&lt;/p&gt;&lt;p&gt;I did learn a great deal from the above implementation. I hope it is useful for others as well.&lt;/p&gt;&lt;p&gt;The source code of the evaluators can be found at:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='https://github.com/transducer/clojure-experiments/blob/master/meta-circular-experiments/mc-evaluator.clj'&gt;Meta-circular evaluator&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://github.com/transducer/clojure-experiments/blob/master/meta-circular-experiments/mc-evaluator-dynamic.clj'&gt;Dynamic evaluator&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Further reading:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href='https://library.readscheme.org/page1.html'&gt;Guy Steele and Gerald Jay Sussman - Lambda papers&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://www.paulgraham.com/rootsoflisp.html'&gt;Paul Graham - The Roots of Lisp&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='https://mitpress.mit.edu/sicp/full-text/book/book.html'&gt;Harold Abelson, Gerald Jay Sussman and Julie Sussman - Structure and Interpretation of Computer Programs&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;
</description>
<enclosure>

</enclosure>
<pubDate>
Mon, 25 Apr 2016 00:00:00 +0200
</pubDate>
</item>
</channel>
</rss>
