<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Iwo Herka on Medium]]></title>
        <description><![CDATA[Stories by Iwo Herka on Medium]]></description>
        <link>https://medium.com/@iwoherka?source=rss-d555b0896ee9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jNTN9Utv061VMp_R5Q6QYw.png</url>
            <title>Stories by Iwo Herka on Medium</title>
            <link>https://medium.com/@iwoherka?source=rss-d555b0896ee9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:14:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iwoherka/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The curse of knowledge]]></title>
            <link>https://medium.com/data-science/the-curse-of-knowledge-8deb4769bff9?source=rss-d555b0896ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8deb4769bff9</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[teaching]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 18:28:57 GMT</pubDate>
            <atom:updated>2019-11-26T18:28:57.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*Vzu1HQyaeQJ0m4DRDRpjeQ.png" /><figcaption>Claude Monet, Cart on the Snow Covered Road with Saint-Simeon Farm, 1865</figcaption></figure><blockquote>Why are competent people often so bad at teaching? It turns out that expertise comes with a cognitive handicap which makes it difficult to transfer the superior knowledge to others.</blockquote><p>“A three-year-old boy comes into a lab, sits down at a table. The experimenter gives him a box of Smarties. He’s all excited. He opens it, and he finds that instead of containing Smarties, the box contains pencils. So the child is surprised. And the experimenter puts the pencils back in the box, closes it, puts it back down on the table. And he says: OK, Well, now another little boy is going to come in, Jason. What does Jason think is in the box? And the boy will say <em>pencils</em>. Even though, of course, Jason has no way of knowing that the box contains pencils, the boy knows it, but a newcomer would not. And in fact, if you ask him, well, when you came into the room, what did you think was in the box? And he’ll say pencils. Now that he knows it, he can no longer recover the innocent state in which he once did not know it.” — Steven Pinker, <em>Linguistics, Style and Writing in the 21st Century </em>[4].</p><p>The term “curse of knowledge” was coined in a 1989 <em>Journal of Political Economy</em> article by economists Colin Camerer, George Loewenstein, and Martin Weber to describe a cognitive bias that makes people project their own knowledge and experience of the world onto others. The curse of knowledge makes it really hard to accurately reconstruct our own’s previous, less knowledgeable state of mind in which we did not know or understand something. In effect, we have a strong tendency to unknowingly assume that others know what we know or that it would be easier to learn it than it actually is. In his paper on hindsight bias, a related inclination for people to perceive events that had already occurred as having been more predictable than they actually were before the events took place, Fischhoff theorized that the inability to empathize with ourselves in less knowledgeable states was because we are “anchored in the hindsightful state of mind created by receipt of knowledge” [5].</p><p>In his article, Richard Fisher points out that in the 1980s, some behavioral economists observed this phenomenon when car salesmen where misjudging how much money could be made from their vehicles. Because they knew their cars backward and forwards, they unconsciously assumed that their customers did too, including cars’ flaws. In fact, however, ignorant customers would happily pay more [2].</p><p>One of the first psychologists to study the problem was Pamela Hinds of Stanford Unversity in California. In one of her experiments, she asked experienced salesmen to estimate how long it would take a novice to learn how to perform a series of tasks using a cellular telephone. She found that experts greatly underestimated the time needed. On average, it took the unskilled novices twice as long as it was predicted. “Findings from these studies suggest that experts may have a cognitive handicap that leads to underestimating the difficulty novices face and that those with an intermediate level of expertise may be more accurate in predicting novices’ performance” [1]. Two other groups consisting of novices and intermediate users were asked the same question. Both gave better estimates.</p><p>Why are we so bad at guessing what other people know? Why is it so easy to underestimate how long it will take for someone to learn something? Firstly we must acknowledge that simply because of the fact that you know something and your audience does not, there must be a gap between you two. Distilling years of experience is hard, because often times it’s not easily verbalized. Muscle memory, mental habits, unconscious biases all play a major role.</p><p>In discussing the challenges of good writing, Steven Pinker notices that it simply does not occur to the writer that the readers haven’t learned their jargon, don’t know the intermediate steps that seem too obvious to mention and can’t visualize a scene currently in the writer’s mind’s eye. In effect, they don’t bother to explain the jargon, spell out the logic, and supply the reader with concrete details and examples. Pinker goes on to say that, unfortunately, this happens even when writing for professional peers, giving the following example of a passage from a paper in the journal Trends in Cognitive Science:</p><p>“The slow and integrative nature of conscious perception is confirmed behaviorally by observations such as the ‘rabbit illusion’ and its variants, where the way in which a stimulus is ultimately perceived is influenced by poststimulus events arising several hundreds of milliseconds after the original stimulus.”</p><p>“I’ve been in this business for almost forty years, and I have no idea what they are talking about.”</p><p>In increasing complex, rapidly changing Information Age, the ability to transfer one’s knowledge is extremely important. The curse of knowledge, thus, presents a thorny problem to our modern civilization. The teacher, who already possesses the knowledge, as we saw, is often not able to convey the knowledge in a way suited for those who do not possess it already. As Chip and Dan Heath add, in the business world, managers and employees, marketers and customers, corporate headquarters and the front line, all rely on ongoing communication but suffer from enormous information imbalances.</p><blockquote>Fischhoff theorized that the inability to empathize with ourselves in less knowledgeable states was because we are “anchored in the hindsightful state of mind created by receipt of knowledge”.</blockquote><h3>What can we do about it?</h3><p>Fortunately, there are things we can do to minimize the negative effects. A traditional solution, Pinker says, is always to keep your reader over your shoulder. “That is, to emphasize with the reader, see the world from her point of view, try to feel her pain, walk a mile in her moccasins.” However, he adds, this does not always work, as a lot of research in psychology shows that we are not very good at figuring out what other people know, even when we try really really hard [sic]. A better solution would be to engage your audience directly and gain as much feedback as possible. Show your draft to your students or colleagues, or even to yourself after some time has passed, and the material is no longer familiar. “If you’re like me, you’ll find yourself thinking ‘that wasn’t clear’ or ‘what did I mean by that?’, or all too often, ‘who wrote this crap?‘” Pinker jokingly says. Then, rewrite the material (ideally, several times), keeping in mind the many things your audience may not know and, at the same time, not assuming your audience knows something already.</p><p>The second important piece of advice comes from Chip and Dan Heath of the bestseller <em>Made to Stick, </em>which teaches how to create ideas that last and “stick” in the memory of the audience. The authors say that “concrete language and stories defeat the curse of knowledge.“ According to Heath brothers, the idea which has a strong visualization is much easier to comprehend and member. “Language is often abstract, but <em>life</em> is not abstract.” Therefore, the authors propose that to express complicated ideas we should use simple language and as many examples as possible, at the same time avoiding overly-abstract language.</p><p>Finally, acknowledge and embrace your ignorance. Unsurprisingly, one of the more obvious places to see the curse of knowledge is in the classroom. “It’s an oxymoron, but ignorance can be a virtue in education,” says psychologist Susan Birch of the University of British Columbia [2]. To transfer your knowledge onto others, you not only have to distill years of experience into words, which is hard enough on its own, but you also need to see things from the naive perspective of the novice. “Sometimes a less-experienced teacher can be better at pitching the message at the right level.”</p><p>Ignorance is bliss.</p><h3>References</h3><ol><li>Hinds, P. J. (1999). The curse of expertise: The effects of expertise and debiasing methods on prediction of novice performance. <em>Journal of Experimental Psychology: Applied</em>, <em>5</em>(2), 205.</li><li><a href="https://sites.williams.edu/nk2/files/2011/08/Curse_of_Knowledge.pdf">Richard Fisher.<em> </em>Don’t get smart: The curse of knowledge. <em>New Scientist.</em></a></li><li>Chip Heath, Dan Heath. Made to Stick: Why Some Ideas Survive and Others Die. <em>Random House.</em></li><li><a href="https://www.youtube.com/watch?v=OV5J6BfToSw">Steven Pinker. Linguistics, Style and Writing in the 21st Century.</a></li><li><a href="https://hbr.org/2006/12/the-curse-of-knowledge">Chip Heath, Dan Heath. The Curse of Knowledge. <em>Harvard Business Review.</em></a></li><li>Fischhoff, Baruch (1975). “Hindsight is not equal to foresight: The effect of outcome knowledge on judgment under uncertainty”. <em>Journal of Experimental Psychology: Human Perception and Performance</em>. <strong>1</strong> (3): 288–299.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8deb4769bff9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-curse-of-knowledge-8deb4769bff9">The curse of knowledge</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A few points on the state of software engineering]]></title>
            <link>https://medium.com/data-science/a-few-points-on-the-state-of-software-engineering-9256c98fac4b?source=rss-d555b0896ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9256c98fac4b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Sat, 12 Oct 2019 15:53:20 GMT</pubDate>
            <atom:updated>2019-10-12T15:53:20.504Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this short essay, I present a brief discussion on the challenges of contemporary software engineering practice, identifying some of the potential causes of its current state. In subsequent essays, I will present and discuss strategies mainstream paradigms employ to minimize the complexity of the software. Observations laid here are mostly drawn from my own experience in the field. The examination undertaken here, therefore, makes no claim to be exhaustive. Readers who are stimulated to pursue the subject further are strongly recommended to study the works mentioned in the references.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*HNy7DZ3-05qx_OV-oT6XrA.png" /><figcaption>Monet’s <a href="https://en.wikipedia.org/wiki/Rouen_Cathedral_(Monet_series)">Rouen Cathedral</a> (cropped). It reminds me of <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.102.7366&amp;rep=rep1&amp;type=pdf">Concepts, Techniques, and Model of Computer Programming</a>.</figcaption></figure><p>It comes as no surprise that software engineering involves significant cognitive effort. To take all aspects of software and come up with a finished product, it requires an interdisciplinary endeavor: from the requirement analysis to the specification, to the design, to the code, to the testing, to the evaluation, and the maintenance. Software engineering uses computer science to devise and analyze algorithms, engineering tools to build infrastructures, and management techniques to define trade-offs, risks, to oversee personnel, and monitor progress. E. E. David Jr points out [1]:</p><blockquote>Too few people recognize that the high technology so celebrated today is essentially a mathematical technology.</blockquote><p>Software engineering is, contrary to what some would like to believe, a lot more than just writing code. However, one way of studying software engineering is to study programming, which is the main interest of this paper. According to Brooks, the essence of programming is the construction and representation of interlocking concepts: algorithms, data structures, functions, and relationships among them [2], while to Dijkstra it is <em>“the art of organizing complexity”</em> [3]. Both insights complement each other, as, in most cases, the elements of a software system interact with each other in a nonlinear fashion, and the complexity of the whole increases much quicker. Because of this, in most situations, reasoning about the correctness of a program, both formal and informal, ranges from non-trivial to nearly impossible. Despite this, the ability to demonstrate that a program has the required properties is one of the basic responsibilities of a programmer.</p><p>In that vein, the complexity of a large software system often surpasses the comprehension and control of any one individual. From this comes the need for efficient communication. To be able to coordinate the development of the project across many professionals, one must not only master inner-workings of intricate social systems but also organize the efficient transfer of knowledge between individuals, as lack of thereof may result in misunderstandings of the requirements and loss of vision. Dijkstra points out: <em>“it does not suffice to hone your own intellect (that will join you in your grave), you must teach others how to hone theirs”</em> [4]. Unfortunately, current educational systems do not seem to meet extremely high demand for skilled software developers. J. C. Adams notes that <em>“companies in need of advanced computing skills are finding stiff competition for a scarce resource — people with those skills”</em> [5]. The software engineering shortage is not a lack of just any individuals — it is a lack of experienced professionals.</p><p>However, one must keep in mind that programming emerged as a profession only as of the early 1980s. Accordingly, it is relatively new and immature, and many of the software companies and practitioners lack a deep understanding of the craft. In Dijkstra’s terms, many of the much-needed tools require honing. The strengths, limitations, and needs of the available technologies are dubious. The same applies to software paradigms, techniques, and, specifically, to languages designed to represent current trends in computer programming. Tens of different languages have been introduced and abandoned in the last two decades. In my experience, many mainstream tools, like JavaScript, have the almost universal reputation of being deeply flawed.</p><p>The young age of the discipline is also mirrored by its scientific research. Although vigorous, the research community has been, so far, unable to accurately sort out many of the basic concepts concerning software engineering. Baragry points out, for example, that although software architecture was discussed since the 1950s, only Shaw’s 1989 <em>Larger Scale Systems Require Higher Level Abstractions</em> [6], and Perry and Wolf’s subsequent paper <em>Foundations for the Study of Software Architecture</em> [7], laid the groundwork for the emergence of software architecture as a major area of study. Even the most widely used definition, given by Garlan and Shaw, is not universally accepted by the community [8].</p><p>One must keep in mind that, although incredibly fruitful, both technology and science of programming are incredibly young and that there exists an apparent correlation between this property and quality of the software produced. To know this, one can examine the fruits of programming labor.</p><h3>State of the industry</h3><p>The emergence period of the software industry was a difficult one. Although it led to one of the greatest engineering achievement of the twentieth century, Apollo Guidance System, it was plagued with notorious quality issues [9]. Many budget overruns (such as OS/360), property damage (Trans-Siberian gas pipeline explosion) and even severe injuries and death (infamous Therac-25 incidents) led to the identification of the software crisis in 1968/1969. Many software problems led the NATO Science Conference to identify software that was unreliable, unmaintainable, delivered late and over budget [10]. In 1972, Dijkstra pointed to the same problem [11].</p><h3>Recent failures</h3><p>While software engineering has come a long way since the 1960s, it remains unclear if the crisis has abated completely. Unfortunately, there is no lack of tragic software failures in recent history. In 1991, a ballistic missile struck a U.S. Army barracks in Saudi Arabia, resulting in 28 deaths and 96 injuries [12]. In 1997, a buggy ground-based altitude warning system was partially responsible for a Korean Air crash that killed 228 people [13]. In 2018, a software miscalculation in one of Uber’s self-driving cars caused the death of a pedestrian [14]. Finally, following the crash of Lion Air Boeing 737 Max 8 jetliner into the Java Sea in 2018, which killed all 189 passengers and crew, the Federal Aviation Administration issued an emergency notice to operators of Boeing 737 Max 8 and 9 planes, warning that faulty “Angle of Attack” sensor readings <em>“could cause the flight crew to have difficulty controlling the airplane.”</em> Investigators of the crash described the malfunction of the plane’s flight-control system as a glitch [15]. One hundred thirty-two days later Ethiopian Airlines Boeing 737 crashed just outside Addis Ababa killing 157.</p><p>In view of an alarming number of aerospace accidents, N. G. Leveson warned about the overwhelming complexity of tightly coupled systems and dysfunctional interactions among them [16]:</p><blockquote>All the accidents investigated for this paper displayed some aspects of system accidents. System accidents are caused by interactive complexity and tight coupling. Software allows us to build systems with a level of complexity and coupling that is beyond our ability to control; in fact, we are building systems where the interactions among the components (often controlled by software) cannot all be planned, understood, anticipated, or guarded against.</blockquote><h3>Standish Report and its critique</h3><p>In 1994, the Standish Group, an independent international IT research organization, published the infamous Chaos report that showed a shocking 16% software project success rate. In 2004, 29% of the projects were successful, 53% were challenged and 18% failed. In two first reports, the success of the project was judged based on whether it was completed <em>“within a reasonable estimated time, stayed within budget, and contained a good number of the estimated features and functions.”</em> In 2015, the results were similar with 29% projects successful, 52% considered challenged and 19% failed, where the success of the project was based on whether it was “resolved within a reasonable estimated time, stayed within budget, and delivered customer and user satisfaction regardless of the original scope” [17].</p><p>Original and recent figures by Standish are often taken as proof of the software industry’s failure. However, over the years, many objections were raised, questioning Standish’s methodology. Many judges the Standish figures as <em>“unreliable and not necessarily reflecting the reality” </em>[18] [19] [20].</p><p>El Emam et al. state that [21]:</p><blockquote>Despite various industry reports about the failure rates of software projects, there’s still uncertainty about the actual figures. Researchers performed a global Web survey of IT departments in 2005 and 2007. The results suggest that the software crisis is perhaps exaggerated and that most software projects deliver. However, the overall project failure rate, including canceled and completed but poorly performing projects, remains arguably high for an applied discipline.</blockquote><h3>Software craftsmanship</h3><p>Regardless of the actual state, as the technology advanced, and the new workforce entered the market, the debate about the crisis died down. From the authors’ personal experience, it seems that the quality of the software products is distributed very unevenly across the industry, with significant differences between specific areas of endeavor. This is related to differing quality standards of emerging markets with no established practices, varying levels of expectations and importance of the produced software, as well as prioritization of financial profit over accountability. It should come as no surprise that the low quality of the software is easier to ignore in markets where craftsmanship is simply not a concern.</p><p>In response to rising concerns about the future of the industry, Robert C. Martin, co-author of the Agile manifesto, SOLID principles and proponent of the craftsmanship movement, proposed an oath to the programmers (akin to Declaration of Geneva) to <em>“defend and preserve the honor of the profession”</em>. Those who take the Programmer’s Oath should swear, among others, to <em>“fearlessly and relentlessly improve the code at every opportunity”</em> [22].</p><h3>Industry demographics</h3><p>When discussing the perceived ills of the profession, one has to keep in mind how young current industry workforce is. Software engineering has only been a widespread occupation since the 1980s. Robert C. Martin speculated that by 1980, highly-skilled individuals (often in their thirties or forties), previously drawn from fields such as engineering, science or mathematics, were replaced by millions of young, recently-graduated men [23]. Up until that point, programmers were disciplined professionals, hired out other job functions, generally old and more mature, who did not require much management. In part, this revolution was enabled by the advent of home and business computing. Martin goes on to say that, roughly speaking, the programmer population doubles every five years (or had so in the past), which means that, at all times, half of the programmers have less than five years of experience. Regardless of how correct this observation is, it is an undeniable fact that, nowadays, the average programmer is very young.</p><p>In 2018, StackOverflow, a popular Q&amp;A website dedicated to programming, performed a 30- minute survey spanning over 100,000 developers around the world [24]. Topics of the survey ranged from artificial intelligence to ethics in coding. Results showed that among professional developers:</p><ul><li>30.1% programs professionally for 0–2 years, 27.4% for 3–5 years and 14.6% for 6–8 years. In other words, 72.1% of professional respondents have between 0 and 8 years of experience;</li><li>46.1% has a Bachelor’s degree and 22.6% has a Masters degree, and among undergraduate majors, only 63.7% degrees are computer science, computer engineering, or software engineering;</li><li>26.1% is younger than 25 years old and 49.2% is between 25 and 34 years old.</li></ul><p>In summary, StackOverflow findings seem to support Martin’s claim about the perpetual inexperience of the computer programming industry. Martin also suggests that because educational systems cannot compensate for the massive rate of growth of the industry, young people are doomed to repeat the same mistakes over and over again. Some programmers refer to this phenomenon as the industry’s <em>ten-year amnesia</em> [26].</p><h3>Summary</h3><p>Resolution to the ongoing debate seems elusive, and possibly always will be. Regardless, it is important not to give in to complacency. Moseley and Marks suggest that complexity is the root cause of the vast majority of problems with software today [25]:</p><blockquote>Unreliability, late delivery, lack of security — often even poor performance in large-scale systems can all be seen as deriving ultimately from unmanageable complexity. The primary status of complexity as the major cause of these other problems comes simply from the fact that being able to understand a system is a prerequisite for avoiding all of them, and of course, it is this which complexity destroys.</blockquote><p>In his classic paper <em>No Silver Bullet</em>, Brooks states that the complexity of software is an essential property [2]. From this, we can conclude that the lion’s part of the complexity in software systems is essential. Moseley and Marks disagree with this sentiment, noting that most of the complexity in software systems is, in fact, incidental and can be get rid off [25]. Specifically, they believe that the primary source of complexity is mishandling the state in mainstream languages.</p><p>We will investigate this idea in future articles. Until then, stay tuned and thank you for reading.</p><p>If you have any feedback whatsoever (especially critical) please comment or send me an e-mail at<strong><em> </em></strong><em>iwoherka@gmail.com</em>.</p><h3>References</h3><ol><li>W. L. A. Friedman. Industrial Mathematics: A Course in Solving Real-World Problems. Society for Industrial and Applied Mathematics, 1st edition, 1987.</li><li>F. P. Brooks, Jr. No silver bullet essence and accidents of software engineering. Computer, 20(4):10–19, Apr. 1987.</li><li>E. Dijkstra, O. Dahl, and C. Hoare. Notes on structured programming. APIC studies in data processing, 8, 1972.</li><li>E. W. Dijkstra. My hopes of computing science (ewd709). In Proceedings of the 4th International Conference on Software Engineering, ICSE ’79, pages 442–448, Piscataway, NJ, USA, 1979. IEEE Press.</li><li>Computing is the safe stem career choice today. <a href="https://cacm.acm.org/blogs/blog-cacm/">https://cacm.acm.org/blogs/blog-cacm/</a> 180053-computing-is-the-safe-stem-career-choice-today/fulltext. Accessed: 2019–03–30.</li><li>M. Shaw. Larger scale systems require higher-level abstractions. In Proceedings of the 5th International Workshop on Software Specification and Design, IWSSD ’89, pages 143–146, New York, NY, USA, 1989. ACM.</li><li>D. E. Perry and A. L. Wolf. Foundations for the study of software architecture. SIGSOFT Softw. Eng. Notes, 17(4):40–52, Oct. 1992.</li><li>J. Baragry and K. Reed. Why is it so hard to define software architecture? In Proceedings of the Fifth Asia Pacific Software Engineering Conference, APSEC ’98, pages 28–, Washington, DC, USA, 1998. IEEE Computer Society.</li><li>P. Naur and B. Randell, editors. Software Engineering: Report of a Conference Sponsored by the NATO Science Committee, Garmisch, Germany, 7–11 Oct. 1968, Brussels, Scientific Affairs Division, NATO. 1969.</li><li>P. Naur and B. Randell, editors. Software Engineering: Report of a Conference Sponsored by the NATO Science Committee, Garmisch, Germany, 7–11 Oct. 1968, Brussels, Scientific Affairs Division, NATO. 1969.</li><li>E. W. Dijkstra. The humble programmer. Commun. ACM, 15(10):859–866, Oct. 1972.</li><li>R-17 vs patriot: a rounding issue. <a href="https://www.viva64.com/en/b/0445/">https://www.viva64.com/en/b/0445/.</a> Accessed: 2019–03–30.</li><li>Fatigue and errors are cited in crash of jetliner on guam. <a href="https://www.nytimes.com/1999/11/03/us/">https://www.nytimes.com/1999/11/03/us/</a> fatigue-and-errors-are-cited-in-crash-of-jetliner-on-guam.html. Accessed: 2019–03–30.</li><li>Report: Software bug led to death in uber’s self-driving crash. <a href="https://arstechnica.com/tech-policy/">https://arstechnica.com/tech-policy/</a> 2018/05/report-software-bug-led-to-death-in-ubers-self-driving-crash/. Accessed: 2019–03- 30.</li><li>Hard questions raised when a software ’glitch’ takes down an airliner. <a href="https://www.viva64.com/en/b/">https://www.viva64.com/en/b/</a> 0445/. Accessed: 2019–03–30.</li><li>N. G. Leveson. Role of software in spacecraft accidents. Journal of Spacecraft and Rockets, 41(4):564–575, 2004.</li><li>S. Group. The chaos report: 2015, 2015</li><li>R. L. Glass. The standish report: Does it really describe a software crisis? Commun. ACM, 49:15–16, 08 2006.</li><li>M. Jorgensen and K. Molokken-Ostvold. How large are software cost overruns? a review of the 1994 chaos report. Inf. Softw. Technol., 48(4):297–301, Apr. 2006</li><li>C. V. J. Eveleens. The rise and fall of the chaos report figures. IEEE Software, 27(1):30–36, Jan 2010.</li><li>K. E. Emam and A. G. Koru. A replicated survey of it software project failures. IEEE Softw., 25(5):84–90, Sept. 2008.</li><li>The programmer’s oath. <a href="https://blog.cleancoder.com/uncle-bob/2015/11/18/TheProgrammersOath.">https://blog.cleancoder.com/uncle-bob/2015/11/18/TheProgrammersOath.</a>html. Accessed: 2019–03–30.</li><li>The future of programming. <a href="https://www.youtube.com/watch?v=ecIWPzGEbFc.">https://www.youtube.com/watch?v=ecIWPzGEbFc.</a> Accessed: 2019–03–30.</li><li>Stack overflow — developer survey results: 2018. <a href="https://insights.stackoverflow.com/survey/2018/">https://insights.stackoverflow.com/survey/2018/.</a> Accessed: 2019–03–30.</li><li>B. Moseley and P. Marks. Out of the tar pit. In SOFTWARE PRACTICE ADVANCEMENT (SPA), 2006.</li><li>Functional Geekery — Episode 1 — Robert C. Martin. <a href="https://www.functionalgeekery.com/episode-1-robert-c-martin/">https://www.functionalgeekery.com/episode-1-robert-c-martin/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9256c98fac4b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-few-points-on-the-state-of-software-engineering-9256c98fac4b">A few points on the state of software engineering</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hiccup Lightning Tutorial]]></title>
            <link>https://medium.com/makimo-on-software-development/hiccup-lightning-tutorial-6494e477f3a5?source=rss-d555b0896ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6494e477f3a5</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clojure]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Sun, 15 Sep 2019 16:03:50 GMT</pubDate>
            <atom:updated>2019-10-13T14:25:54.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMlHUW4VO-j_bEWr6C6wkw.png" /></figure><p>Hiccup is a Clojure DSL for writing HTML. Here is a quick tutorial for the busy. It contains most of the information you’re going to need in a typical project.</p><h3>Introduction</h3><p><a href="https://github.com/weavejester/hiccup">Hiccup</a> is a <a href="https://en.wikipedia.org/wiki/Domain-specific_language">domain-specific language</a> for generating HTML in Clojure. In other words, it turns Clojure into HTML. Let’s look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df062c8b850f88b27aee723f95838ed1/href">https://medium.com/media/df062c8b850f88b27aee723f95838ed1/href</a></iframe><p>As you can see, it uses literal data structures — in fact, it’s just Clojure’s vectors containing keywords (representing tags) and maps (for HTML properties). The above example compiles down to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcf49211ce507b78623a0459706c6485/href">https://medium.com/media/dcf49211ce507b78623a0459706c6485/href</a></iframe><p>…which is simple <em>div </em>with a single button which increments some atom counter. Everything is represented as a plain Clojure data-structure.</p><h3>The advantages</h3><ol><li>No need to create separate files for templates. Hiccup is typically used in Reagent/re-frame projects, where views are just Clojure functions returning HTML (or functions returning functions).</li><li>HTML represented as plain vectors which can be easily processed and generated using all the tools of the host language. This means that repetitive code can be abstracted away into functions and mechanically manipulated.</li><li>A thin layer of abstraction allows improving HTML semantics while not being new enough to require re-learning.</li></ol><h3>The gist of it</h3><h4>Vectors and maps</h4><p>If you’re building front-end using Reagent/re-frame, you will probably spend most of the time using Hiccup’s literals. In Hiccup, HTML nodes are represented as Clojure’s vectors. The first element of the vector is always a keyword (e.g. :div) designating HTML tag. Immediately after the tag, we specify special options which act as a syntactic sugar (explained below). The second argument is an optional map of the tag’s attributes. We will specify here things such as inline styles, classes, event listeners, and so on. Lastly, we pass arguments to the element itself, such as a string for the label. Putting it all together, we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f37d10fc8463740cd5f79f2cd81655d/href">https://medium.com/media/2f37d10fc8463740cd5f79f2cd81655d/href</a></iframe><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d29926de6bdcb06d41e8d9163c1e76f9/href">https://medium.com/media/d29926de6bdcb06d41e8d9163c1e76f9/href</a></iframe><p><em>Tip</em><strong>: Because Hiccup uses vectors to represent HTML trees, use lists to represent sequences. </strong>Mixing vector sequences with HTML vectors may confuse Hiccup.</p><h4>Constructor functions</h4><p>Hiccup provides constructors for many of the standard HTML elements. Use them to remove some of the boilerplate. For example, instead of slightly verbose:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8ef4c051a24556ccb81c40d5ad6d54d/href">https://medium.com/media/e8ef4c051a24556ccb81c40d5ad6d54d/href</a></iframe><p>…we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e97ad72eec9459566a238a98dbbf42/href">https://medium.com/media/c5e97ad72eec9459566a238a98dbbf42/href</a></iframe><p>For a comprehensive listing, consult <a href="http://weavejester.github.io/hiccup/index.html">the API documentation</a>.</p><h4>Inline styling</h4><p>Styles can be added on the fly to elements via the :style map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/115f5394f2096764b34d1715f75700f8/href">https://medium.com/media/115f5394f2096764b34d1715f75700f8/href</a></iframe><p>By default, integers are interpreted as pixels. If you want to use a different unit, use a string instead: {:padding &quot;50rem&quot;}.</p><h4>Sugar for the id and class attribute</h4><p>Hiccup provides a convenient syntax for adding id and class attributes to an element. The following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d24db2802ea51118f9c3f43d8f1e292/href">https://medium.com/media/1d24db2802ea51118f9c3f43d8f1e292/href</a></iframe><p>…can be rewritten as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26a7d13712440af59d8e31be1200935a/href">https://medium.com/media/26a7d13712440af59d8e31be1200935a/href</a></iframe><p>The word after the <em>#</em> denotes the element’s ID, and each word after a dot corresponds to one of the element’s classes. The ID must always come first.</p><p><em>Tip</em>: <strong>Specify permanent classes using sugar and dynamic ones via </strong><strong>:class. </strong>Sometimes you will use a particular class only in certain conditions. For example, the class &quot;active&quot; may depend on the Boolean active?:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddcf6116fb69c4528b468fb7fcce5069/href">https://medium.com/media/ddcf6116fb69c4528b468fb7fcce5069/href</a></iframe><p><em>(Strings to </em><em>:class are concatenated, so we need whitespace to separate classes). </em>My suggestion is to specify classes that are static using sugar notation and leave everything else in the attribute map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25cc0f094ac8c91109fd6931ef99045/href">https://medium.com/media/f25cc0f094ac8c91109fd6931ef99045/href</a></iframe><h4>Conditional rendering</h4><p>nil values are ignored. This means that we don’t have to worry about them slipping into our HTML. For example, Clojure’s function (when test &amp; body) will return body if test is true and nil otherwise. Therefore, we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/784615166e43638133e91ac056f9ff2b/href">https://medium.com/media/784615166e43638133e91ac056f9ff2b/href</a></iframe><p>If is-true? is false, the value of the expression will simply be ignored, and only element a will end up in the output.</p><h4>Sugar for nested tags</h4><p>To avoid repetitive nesting of HTML tags:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceb454cc7ce4910f921a0e854dd8f7fb/href">https://medium.com/media/ceb454cc7ce4910f921a0e854dd8f7fb/href</a></iframe><p>…you can use the &gt; sugar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0181d1477feb0183c25aaf6677e02b82/href">https://medium.com/media/0181d1477feb0183c25aaf6677e02b82/href</a></iframe><h4>Escape strings with h to avoid XSS</h4><p>Hiccup concatenates strings without asking questions. Therefore, whenever you receive a string from unsafe sources (such as user form or foreign API) you should escape the string with hiccup.core/h:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a40c784e00045b18824bcd19af93304/href">https://medium.com/media/8a40c784e00045b18824bcd19af93304/href</a></iframe><h4>Abstraction</h4><p>One of the biggest advantages of using Hiccup is the ability to abstract away all the repetitiveness of manual HTML-writing. Instead of typing each li, we can use a loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2002476dea495de1aa736b6fcf4d4f/href">https://medium.com/media/3f2002476dea495de1aa736b6fcf4d4f/href</a></iframe><p>Often, it’s a good idea to write a generator function for a commonly occurring element. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c75fc240845535482173d07b71d1e9/href">https://medium.com/media/c1c75fc240845535482173d07b71d1e9/href</a></iframe><p>…which yields a button with an internal counter variable. We can stack and nest those endlessly. However, as <a href="https://purelyfunctional.tv/mini-guide/hiccup-tips/">Eric Normand points out</a>, there is one problem:</p><blockquote>[..] because the Hiccup compiler doesn’t do a full examination of your code, it can’t compile everything. It inserts run time fallbacks for stuff it can’t handle at compile time which will interpret it at run time. So, for instance, <strong>if you’re calling a function that returns some Hiccup, it can’t compile that automatically</strong>. It has to wait till the function returns to know what it is. That is, unless . . .</blockquote><blockquote><strong>The fix:</strong> The way to get Hiccup to compile something is with the <a href="http://weavejester.github.io/hiccup/hiccup.core.html#var-html"><em>hiccup.core/html</em></a> macro. That’s the macro that does the compilation and it will do it anywhere.</blockquote><p>For most projects, this shouldn’t be a problem; however, a large codebase may lose some performance. To avoid this, we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bee38c7b54713b34340ba9dddfaccb57/href">https://medium.com/media/bee38c7b54713b34340ba9dddfaccb57/href</a></iframe><h4>Rendering</h4><p>To force HTML generation directly, use hiccup.core/html function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgmJ3kQ6ELWcF1MN-W_JUw.png" /></figure><p>That’s it — the gist of Hiccup. Thanks for reading. Take a look at the resources below if you want to delve deeper and maybe my other stuff. If you have any questions, please feel free to send me an e-mail or leave a comment.</p><h3>Resources</h3><ul><li><a href="https://github.com/weavejester/hiccup/wiki">https://github.com/weavejester/hiccup/wiki</a></li><li><a href="http://weavejester.github.io/hiccup/index.html">http://weavejester.github.io/hiccup/index.html</a></li><li><a href="https://github.com/yokolet/hiccup-samples">https://github.com/yokolet/hiccup-samples</a></li><li><a href="https://purelyfunctional.tv/mini-guide/hiccup-tips/">https://purelyfunctional.tv/mini-guide/hiccup-tips/</a></li><li><a href="http://www.rkn.io/2014/03/13/clojure-cookbook-hiccup/">http://www.rkn.io/2014/03/13/clojure-cookbook-hiccup/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6494e477f3a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/hiccup-lightning-tutorial-6494e477f3a5">Hiccup Lightning Tutorial</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Lisp in 15 minutes]]></title>
            <link>https://medium.com/makimo-on-software-development/on-lisp-in-15-minutes-3286c179584f?source=rss-d555b0896ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3286c179584f</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[clojure]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Fri, 24 May 2019 12:03:23 GMT</pubDate>
            <atom:updated>2019-07-06T11:19:19.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmTwv0MN_IQMgdGj83N20w.jpeg" /></figure><blockquote>LISP is simple and difficult, elegant and ad hoc; it is a beautiful blend of foresight and fortuity.¹</blockquote><p>Whether you agree with this statement or not, Lisp’s historical importance is indisputable. Even though a beautiful language in its own right, Lisp turned to be one of the most influential models<em> </em>of computer programming. It also gave birth to many widespread concepts in the industry today and, as mainstream is steadily shifting from von Neumann style to λ-calculus, we can suspect many to be adopted in the future. In effect, Lisp is of interest to both a historian and a futurist. Paul Graham suggested that what John McCarthy did for programming was something like what Euclid did for geometry². What is so important that McCarthy discovered? To answer this question we have to put aside decades’ worth of Internet mythos and take a look at Lisp’s humble beginnings — <em>Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I</em>³ by John McCarthy. In this article, I will follow his steps in order to explain how Lisp was constructed.</p><p><em>I’m writing this article to practice my understanding and appreciation of McCarthy’s work. The goal of this article is to explain how Lisp came to be and discuss properties that make it special. Hopefully, someone will find it useful. I highly recommend reading the original paper, and Paul Graham’s take on it, after this short introduction (see References).</em></p><h3>1. Preliminaries</h3><p>Lisp is constructed from the bottom. It is only appropriate that we start by laying out basic ideas and notations concerning functions which we will use later on. Most of the concepts presented here are well-known, so feel free to skip this section.</p><h4>1.1. Partial functions</h4><p><a href="https://en.wikipedia.org/wiki/Partial_function"><em>Partial functions</em></a> (not to be confused with the partial application!) are functions that are defined only for parts of their domains. The <a href="https://en.wikipedia.org/wiki/Domain_of_a_function"><em>domain of a function</em></a><em> </em>is a collection of all possible arguments to a function. Most of the functions in computer programs are partial (at least in imperative languages). Consider the following example (in Python):</p><pre>def one_nth(n):<br>    return 1 / n</pre><p>or, a bit more involved:</p><pre><strong>def </strong>query_purchases(client: BillingClient) -&gt; List[Purchase]:<br> <strong>   if </strong>client.is_initialized:<br>        return client.query_purchases()<br>    <strong>else:</strong><br>        raise Exception(&#39;Billing client is not set up&#39;)</pre><p>The behavior of these functions (in a mathematical sense) is undefined for certain inputs, as passing zero to one_nth or uninitialized client to query_purchases will result in an exception. Another possibility is that functions may not terminate, e.g. when caught in infinite recursion. It derives from the fact that the type systems are often too weak to constrain the type as much as the programmer would like or the penalty of assigning more precise type is too high. In mathematics, we don’t have this problem. In case of one_nth, we could simply say that the domain of the function is ℝ \ {0}.</p><blockquote>One example of a more “expressive type” system is Idris’, which supports dependent types. Although dependent types are a story for another time, in short, it simply means that types themselves are dynamic and first-class, in the sense that they possess properties related to values they take. For example, a function taking argument N may return the type of list which is no longer than N.</blockquote><p>In general, any function that can result in an error, or does not terminate for some of its inputs, is considered partial.</p><blockquote>In some languages, such as Haskell, a computation which never completes successfully is referred to as “bottom” and denoted with “⊥”. Therefore, when the evaluation of a partial function results in a partial behavior (such as a crash), its value is ⊥.</blockquote><blockquote>In Racket, Lisp dialect, the programmer can explicitly mark a function as partial.</blockquote><blockquote>Sometimes, when it is desirable to suppress errors and exceptions, a special value might be returned acting as a bottom, such as IEEE floating point’s <a href="https://en.wikipedia.org/wiki/NaN">not-a-number</a> (<em>NaN</em>).</blockquote><p>Analogically, when a function is <em>total</em>, we can say that it produces a valid result for all possible inputs. For example, the <a href="https://docs.racket-lang.org/hackett/reference-datatypes.html#%28def._%28%28lib._hackett%2Fmain..rkt%29._not%29%29">f</a>unction not is obviously defined for both True and False, which are the only possible values of the bool type. Total functions allow a programmer to reason about programs using the types alone; a function with the type <em>A</em>→<em> B</em> implies that it is always possible to get a <em>B</em> when you have an <em>A</em>.</p><h4>1.2. Predicates</h4><p>A <a href="https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)">predicate</a> is a function whose codomain (set of all possible outputs) consists only of truth values (i.e., truth or falsehood). A common convention is to denote truth with t and falsehood with f (in the original paper McCarthy used uppercase letters). Simply put, a predicate must return a Boolean.</p><h4>1.3. Pure functions</h4><p>One of the most important advantages of purely functional approach over imperative one (and by extension OOP) is <em>referential transparency</em>, which guarantees that for a specific set of arguments a function (or generally, an expression) will always return the same result (it is entirely predictable). In other words, an evaluation of an expression can have no effect other than to compute its value. As a result, one can freely replace expressions by their values. Functions with this property are called <em>pure</em>. Almost all functions in imperative environments are impure.</p><h4>1.4. Conditional Expressions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*dUJOTjCsp6QI7Q8FuX_Z1g.png" /></figure><p>The function above is a well-known <em>absolute value</em>. Because its value depends on the condition (whether <em>x</em> is greater-or-equal to zero), we can say that it is <em>conditional</em> in its behavior. However, this notation is not suited for expressing symbolically the dependence of quantities on truth values — it has to rely on English words.</p><p>A better notation for representing conditional expressions was proposed by McCarthy (now referred to as <a href="https://en.wikipedia.org/wiki/McCarthy_Formalism">McCarthy formalism</a>):</p><pre>(p₁ → e₁, … , pₙ → eₙ)</pre><p>Here, the <em>p</em>’s are propositional expressions and the <em>e</em>’s are expressions of any kind. It may be read as:</p><p><em>If p₁ then e₁ otherwise if p₂ then e₂, … , otherwise, if pₙ then eₙ.</em></p><p>Notice how we are assuming here the evaluation order — we consider <em>pᵢ</em> from left to right. With this notation under our belt, we can express the absolute value function simply as:</p><pre>(x ≥ 0 → x, x &lt; 0 → -x)</pre><p>More importantly, however, this notation is sufficient to express <strong>any</strong> <em>if-then</em> statement. For example:</p><pre>if n % 3 == 0 and n % 5 == 0:<br>    return &#39;FizzBuzz&#39;<br>elif n % 3 == 0:<br>    return &#39;Fizz&#39;<br>elif n % 5 == 0:<br>    return &#39;Buzz&#39;<br>else:<br>    return n</pre><p>…can be expressed as:</p><pre>(3 ∣ n ∧ 5 ∣ n → &#39;Fizzbuzz&#39;,<br> 3 ∣ n → &#39;Fizz&#39;,<br> 5 ∣ n → &#39;Buzz&#39;,<br> t → n)</pre><blockquote><em>m | n</em> means that <em>n</em> is divisible by <em>m</em>, or <em>m</em> divides <em>n</em>.<em>∧</em> is standard logical conjunction, or AND in Boolean algebra.</blockquote><blockquote>Notice how by exploiting the left-to-right evaluation order we can encode the <em>else</em> clause using the <em>t</em> value.</blockquote><p>Conditionals were introduced by Lisp. In effect, <em>if</em> statements, as we know them today, are thanks to McCarthy. As of 1958, Fortran only had a conditional <em>goto </em>which was based on the branch instruction in the underlying hardware. McCarthy also got conditionals into Algol 60, whence they spread to most other languages⁸.</p><h4>1.5. Recursive functions and label</h4><p>Thanks to conditional expressions given above, we can now define functions recursively. For example, we can define <a href="https://en.wikipedia.org/wiki/Factorial">factorial</a> as:</p><pre>n! = (n = 0 → 1, t → n · (n − 1)!)</pre><p>Note, however, that we are making here one very important assumption — the body of the function can reference the function itself by its name (or symbol — ! in this case).</p><blockquote>In most actual languages this is not a problem, but remember — we do not have any language yet!</blockquote><p>In general, we can solve this problem with something called <a href="https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus"><em>Y combinator</em></a>, but that’s a topic for another time. As McCarthy most likely was not aware of Y combinator at the time of writing his paper, he introduced his notation instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*qd4-nDagTCigcG6avrrVMg.png" /><figcaption><strong>Fig 1.</strong> McCarthy in his AI laboratory at Stanford</figcaption></figure><p>label(a, e) denotes the expression e, with the special property that all occurrences of a<em> </em>within e are to be interpreted as referring to the expression e itself. Therefore, by combining <em>label</em> with conditional expressions, we can define <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid&#39;s_algorithm">Euclid’s algorithm</a> for calculating the greatest common divisor as follows:</p><pre>label(gcd, (m &gt; n → gcd(n, m),<br>            m | n → m,<br>            t → gcd(n % m, m)))</pre><p>It is important to note that although recursion existed as a mathematical concept before Lisp, Lisp was the first programming language to support it.</p><h3>2. S-expressions</h3><p>First, we define <em>a</em> <em>symbolic expression (s-expression, </em>or just <em>expression</em> for<em> </em>short<em>)</em>. An s-expression is either:</p><ul><li><em>an atom</em>, which is a sequence of characters, e.g. spam, ham, eggs or f*&amp;o$o. An atom cannot start with (, which is reserved for lists.</li><li><em>a list </em>of zero or more s-expressions which are separated by whitespace and enclosed by parentheses. For example: (abc) , (), (a (bc)).</li></ul><p>In simplified <a href="https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form">extended Backus-Naur form</a> (commonly used for describing the syntax of a language), s-expressions can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBmVpeV2l9ZID5eM63rkZw.png" /><figcaption><strong>Fig. 2</strong> Simplified <a href="https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form">EBNF</a> for s-expressions</figcaption></figure><p>— which is the exact restatement of the definition given above (except that atoms are assumed to be alphanumeric).</p><p>The above definition is recursive, as we are referring to s-expressions while defining lists of s-expressions. Some examples of valid s-expressions include:</p><pre>()<br>foo<br>(bar)<br>(foo bar)<br>((spam) (ham ()) eggs ())</pre><p>— but also:</p><pre>(+ 1 2 3 5 8 13)<br>(&gt; 24 512 12)<br>(and true false true)</pre><h3>3. Abstract machine</h3><p>“The most practical way to think about the meaning of a program is what it does — when we run the program, what do we expect to happen? How do different constructs in the programming language behave at run time, and what effect do they have when they’re plugged together to make larger programs? This is the basis of operational semantics, a way of capturing the meaning of a programming language by defining rules for how its programs execute on some kind of device. This device is often an abstract machine: an imaginary, idealized computer that is designed for the specific purpose of explaining how the language’s programs will execute. Different kinds of a programming language will usually require different designs of an abstract machine in order to neatly capture their runtime behavior.”⁷ In order to construct Lisp, we first construct an imaginary machine on which it will operate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rfd8XQqc8ze-iMvgvuUN9w.jpeg" /><figcaption><strong>Fig. 3</strong> <a href="https://zeptobars.com/en/read/ST-UA741-opamp-operational-amplifier">ST µA741 op-amp</a>, or: imaginary Lisp machine</figcaption></figure><h4>3.1. Elementary functions</h4><p>We start by defining seven (<em>The Magnificent Seven, </em>in fact) elementary functions on s-expressions. We call them elementary because we assume they exist on the abstract machine (just like we assume axioms to be true in some mathematical system). A function on s-expression receives an s-expression and returns a new one. By convention, we will refer to such functions as <em>operators</em>.</p><blockquote>To keep our notation simple, we <strong>represent</strong> operators using atoms and lists — if an s-expression is a list, the first element is an operator, and remaining ones are <em>arguments</em>. This means that functions on s-expressions are encoded using s-expressions themselves. For example, the <em>car</em> operator expects one argument, and so its invocation will take the form:</blockquote><pre>(car x)</pre><p>Atom “car&quot; on its own refers to the function itself. If car expected an argument which is a function (it doesn’t), we could write (car car).</p><h4>atom</h4><p>atom is a very simple operator; it just returns t if the argument passed is an atom, and otherwise.</p><pre>&gt; (atom f)<br>t<br>&gt; (atom foo)<br>t<br>&gt; (atom atom)<br>t</pre><h4>quote</h4><p>quote is even simpler, it returns whatever was passed into it.</p><pre>&gt; (quote x)<br>x</pre><pre>&gt; (quote (atom x))<br>(atom x)</pre><pre>&gt; (quote (1 2 3 4 5))<br>(1 2 3 4 5)</pre><p>It is crucial to understand how quote behaves and why is useful. The second example — (quote (atom x)) —will reduce to the list containing atom and x. (atom x) is not “evaluated” further (at this point we do not know what evaluation even is, but let us ignore that for a second). In essence, quote is used to stop the evaluation — normally in(1 2 3), 1 would be assumed to be an operator but we want to treat the list as a regular list. This is why we would use quote. It is usually abbreviated with &#39;, which gives us:</p><pre>&gt; &#39;(1 2 3)<br>(1 2 3)</pre><p>Now that we have quote , we can go back to atom for one more example:</p><pre>&gt; (atom &#39;(foo bar baz))<br>f</pre><p>If the code would eventually be evaluated by some kind of program capable of doing that, quote would prevent evaluation of any s-expression given as its argument, which is very important when passing data around.</p><h4>eq</h4><p>eq returns t if the values of its arguments are the same atom and f otherwise.</p><blockquote>Some languages, such as Scheme, use <em>eq?</em>. Clojure uses <em>=</em>.</blockquote><h4>car</h4><p>car expects a list as an argument and returns its first element. It&#39;s name, similar to cdr, is a historical legacy.</p><pre>&gt; (car &#39;(1 2 3 4))<br>1</pre><blockquote>Certain languages, such as Clojure, rename <em>car</em> with something more intuitive, e.g. <em>first</em>. The “car” and “cdr” names are derived from the machine architecture that Lisp was designed for and nowadays languages use more familiar names.</blockquote><h4>cdr</h4><p>cdr expects a list as an argument and returns its back without the first element. For example:</p><pre>&gt; (cdr &#39;(1 2 3 4))<br>(2 3 4)</pre><blockquote>In Clojure, <em>cdr</em> behavior is provided via<em>rest</em>.</blockquote><h4>cons</h4><p>cons (<em>construct</em>) takes two arguments, second of which must be a list, and prepends the list with the first argument:</p><pre>&gt; (cons 1 &#39;(2 3))<br>(1 2 3)</pre><blockquote>Why would we prepend to lists instead of appending them is a topic on its own. In short, lists constructed as the head and rest are simpler to manipulate recursively, which is a huge benefit for a language such as Lisp.</blockquote><h4>cond</h4><p>We will now translate conditional expressions into s-expressions using cond. cond has the following form:</p><pre>(cond (p₁ e₁) ... (pₙ eₙ))</pre><p>The value is evaluated as follows. We evaluate p expressions from left to right. If any predicate evaluates to t, the value of the cond expression is taken to be the value of the corresponding expression e. For example:</p><pre>&gt; (cond (t 1) (f 2))<br>1</pre><p>Moreover, because we evaluate from left to right:</p><pre>&gt; (cond (t 1) (t 2))<br>1</pre><h4>3.2. Denoting non-elementary functions</h4><p>With basic functionality in place, we define a general scheme for defining new functions on the abstract machine. A function is expressed as</p><pre>(lambda (p₁ … pₙ) e)</pre><p>where <em>p₁ -pₙ</em> are called <em>parameters</em> and <em>e </em>is an <em>expression</em>. If you ever tinkered with lambda calculus (or with lambdas/anonymous functions in pretty much any modern programming language), you will recognize this notation.</p><p>An expression whose first element is a lambda, i.e., is of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*GPsMQKDkxsH9NwqowLTTHw.gif" /></figure><p>— is called a function call and its value is computed as follows. Each expression <em>aᵢ</em> is evaluated. Then <em>e</em> is evaluated. During the evaluation of <em>e</em>, the value of any occurrence of one of the <em>pᵢ</em> is the value of the corresponding <em>aᵢ</em> in the most recent function call.</p><p>Do you remember <em>label </em>notation<em>?</em> We can now translate it to s-expression form and use it on our abstract machine to obtain a general method for defining functions. The label s-expression will have the following form:</p><pre>(label <em>name lambda</em>)</pre><p>— where <em>name </em>is an atom representing the name of the function and <em>lambda </em>is the function body, also called to <em>form</em>.</p><p>Using label and the <em>Magnificent Seven</em> our expressive power is limitless.</p><p>For example, we can define the Boolean operator <strong>NOT</strong>:</p><pre>(label not (lambda (x)<br>    (cond (x f) (t t))))</pre><pre>&gt; (not t)<br>f</pre><pre>&gt; (not f)<br>t</pre><p>As you can see, <strong>NOT </strong>expects one argument — <em>x</em>. In the body of the function, we perform a conditional check of <em>x</em>. If the value is equal to t, we return f and otherwise t (t in the last positional of the <em>cond</em> acts as the <em>else</em> clause in modern languages, since the condition is always true).</p><p>Next, we can define a bit more involved Boolean<strong> AND</strong>:</p><pre>(label and (lambda (x y)<br>    (cond (x (cond (y t) (t f)))<br>          (t f))))</pre><pre>&gt; (and t f)<br>f</pre><pre>&gt; (and t t)<br>t</pre><p>This body can be summarized as: If <em>x</em> is true, check if <em>y</em> is true and if so, return t. If <em>y</em> is not true, or <em>x</em> is not true, return f (we have two <em>else</em> clauses).</p><p>We can write functions to manipulate lists, Boolean expressions, pair elements, rewrite expressions, and so on. For example:</p><ul><li>(not x) returns t if its argument returns f and t otherwise.</li><li>(pair x y) takes two lists of the same length and returns a third one containing two-element lists of corresponding elements in argument lits. Nowadays we would more likely call this function zip.</li><li>(append x y) takes two lists and concatenates them.</li><li>(assoc x y) takes an atom x and a y of the form return by pair and returns a second-element from a pair in y whose first element is x. This function emulates a lookup into a dictionary (alternatively called a hash table or associative array).</li></ul><blockquote>It is important to note that in Lisp, functions are first class objects — they’re data, just like numbers and strings. Therefore, functions can be stored in variables, passed around as arguments, and so on. The idea of a first-class function was pioneered by Lisp.</blockquote><h4>3.3. Evaluation</h4><p>More importantly, however, we can write a function that takes arbitrary Lisp expression and returns its value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e32cbaa4fa84da8db305b5db750c85e1/href">https://medium.com/media/e32cbaa4fa84da8db305b5db750c85e1/href</a></iframe><p>That is a bit of mouthful. If you want a step by step description, which is beyond the scope of this article, I recommend reading <em>Recursive Functions…</em> by McCarthy³ and Paul Graham’s <em>The Roots of Lisp</em>², which take a thorough look at eval‘s inner-workings.</p><p>The important thing is this: eval <strong>is a Lisp interpreter</strong>, and thus, implements the language. Any valid Lisp code can be passed to it for evaluation and we don’t need any other infrastructure. With only seven functions and a bit of notation, we were able to implement the whole language and allow it to define new functions. That’s neat and very elegant, but so what? Now that we understand how Lisp operates, let’s step back and consider what it means.</p><blockquote>If you’re curious how Lisp can be implemented in a few hundred lines of code, check out my toy Lisp implementation: <a href="http://github.com/iwoherka/kite">Kite</a>.</blockquote><h3>4. Chemical X: Homoiconicity</h3><p>In Lisp, as we saw, both code and data are represented in the same form: as s-expressions (forming trees) which are available for unrestricted mutation and execution. This means that <strong>the Lisp code is <em>first-class</em></strong>. It can be explicitly constructed from scratch, passed around, modified and executed. In other words, in Lisp <em>everything is data</em>. A language in which the internal «representation matches the external representation is called <em>homoiconic </em>(from the Greek words <em>homo</em> meaning “the same” and <em>icon</em> meaning “representation”). Other examples of a language with this property include Prolog (logic programming) and Julia (numerical analysis and computational science). One of the immediate consequences of homoiconicity is that by using just a few functions: quote, atom, eq, car, cdr, cons, and cond, we can define eval, that fully implements the language, and with label and eval we can define any additional function we need. In fact, it is a famous fact that the core of the Lisp can be written in about 20–30 lines of Lisp. In (an unfair) comparison, the average person who writes a C compiler or interpreter requires about 20,000 lines of C to do so and must be moderately expert about compilers or interpreters (of course, we rely on <em>meta-circularity</em> in doing so, but that’s a topic for another post). At this point, you may be asking yourself — what’s the big deal?</p><p>The big deal, as it turns out, that when the representation of the program (code) is the same as the representation for that data, you can manipulate code like you would manipulate data. This allows, for example, for syntactic extensibility, which is the ability to extend (or completely) change the syntax of the language. For example, in a normal language, if you wished that you had the <em>for-each </em>construct, you would have to wait until creators of the language add it in the next version. In Lisp, you can write a macro in a matter of minutes. In many Lisp languages, program transformation is an explicit part of the evaluation strategy of the language.</p><p>Moreover, in Lisp, programs composed of expressions. Lisp programs are trees of expressions, each of which returns a value. At the time, this was a revolutionary idea, in contrast to languages such as Fortran which distinguish between expressions and statements. This was largely dictated by the limitations of the hardware available in the late 1950s.</p><p>Finally, what McCarthy discovered is not just a programming language but a very elegant <em>model of computation</em>, just a notch above lambda calculus. We can say that Lisp was discovered, and not invented, because McCarthy built it from axioms so fundamental that it would be very hard to make an argument for the otherwise.</p><p>Core Lisp corresponds to <em>an untyped, call-by-value lambda calculus extended with constants. </em>As it turned out, lambda calculus* corresponds to natural deduction in logic. Specifically, by Curry-Howard isomorphism, types in a program are propositions, programs are proofs and evaluation of programs is the simplification of proofs. This discovery is phenomenal. Among others, it means that we can reason about programs using logic and that we get theorems in logic for free in programming (and vice versa).</p><p>The big difference between Lips and lambda calculus is that lambda calculus doesn’t contain any non-functional data. In lambda calculus, everything is a function, even a number (if you’re curious how this is achieved see <a href="https://en.wikipedia.org/wiki/Church_encoding">Church encodings</a> or <a href="https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encoding">Mogensen-Scott encodings</a>). Lisp, on the other hand, operates on atoms and numbers (hence, <em>constants</em>). This is most likely what makes Lisp readable to mortal humans — a property that lambda calculus lacks.</p><p>The adherence to mathematically sound principles of computation allows Lisp to reap the benefits in the form of simple semantics, clarity, consistency, and other nice things such as referential transparency (original Lisp formulation is completely value-based). In contrast, almost all imperative languages are “just” tools (sometimes very good tools nonetheless) with undefined formal semantics, which makes reasoning about them rigorously very hard or almost impossible.</p><p>Thank you for reading. Please check out the references and maybe my other <a href="http://iwoherka.eu/">stuff</a>. If you have any questions, please feel free to send me an e-mail at <em>hi@iwoherka.eu</em> or leave a comment.</p><p>*Specifically, typed lambda calculus. For more details, I highly recommend great talk by Philip Wadler, co-creator of Haskell —<a href="https://youtu.be/IOiZatlZtGU"> Propositions as Types</a>.</p><h4>References</h4><ol><li><a href="https://archive.org/details/byte-magazine-1979-08"><em>BYTE Magazine, August 1979</em></a></li><li><a href="http://www.paulgraham.com/rootsoflisp.html"><em>The Roots of Lisp</em></a></li><li><a href="http://Recursive functions of symbolic expressions and their computation by machine, Part I"><em>Recursive functions of symbolic expressions and their computation by machine, Part I</em></a></li><li><a href="https://twobithistory.org/2018/10/14/lisp.html"><em>How Lisp Became God’s Own Programming Language</em></a></li><li><a href="http://c2.com/cgi/fullSearch?search=HomoiconicLanguages"><em>Homoiconic Languages</em></a></li><li><a href="http://www.paulgraham.com/onlisp.html"><em>On Lisp</em></a></li><li><a href="https://computationbook.com/"><em>Understanding Computation</em></a></li><li><a href="http://www.paulgraham.com/diff.html"><em>What Made Lisp Different</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3286c179584f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/on-lisp-in-15-minutes-3286c179584f">On Lisp in 15 minutes</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with pdb in Python]]></title>
            <link>https://medium.com/makimo-on-software-development/https-medium-com-iwoherka-working-with-pdb-in-python-8d4f3b42f3f4?source=rss-d555b0896ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d4f3b42f3f4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Fri, 26 Apr 2019 09:47:14 GMT</pubDate>
            <atom:updated>2019-06-18T13:45:45.457Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Yep, this is another introductory-level article about </em><em>pdb— sue me! The goal is to teach the essentials (and to give a few helpful tips) to those who don’t feel like reading the docs (or get heebie-jeebies when thinking about the console). It is intended for Python 3.</em></blockquote><blockquote>You can watch recorded demonstrations for selected commands on asciinema (links are in the text).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWqi_GCi8IXsC-CzoHFwhw.png" /></figure><h3>Why bother?</h3><blockquote><em>Skip to </em>Getting started<em> if you get bored easily</em>.</blockquote><p>As with every console tool, <a href="https://docs.python.org/3.8/library/pdb.html">pdb</a> may seem a bit intimidating. It doesn’t have a nice GUI to hold your hand, and it can feel very cryptic at times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*s52w1-MNaxdaD1nrth5G-A.png" /><figcaption>What’s this all about?</figcaption></figure><p>However, you probably shouldn’t use <em>print</em> to debug your programs, and if you do, it won’t hurt to know what to do when good ol’ <em>print</em> doesn’t cut it. So, unless you can spare a few bucks on a fancy IDE (like PyCharm) there is no avoiding it — you’re going to need pdb sooner or later. However, that’s not necessarily a bad thing; knowledge of the “lightweight” solution can turn out to be very handy. First of all, pdb is textual, and in the long run, typing is a lot faster than clicking. Secondly, it’s optimized for speed — minimal, textual interface doesn’t get in your way. This makes for a slightly steep learning curve, but with a bit of practice, you will start saving on those precious keystrokes in no time. Finally, pdb is a standard module, which means that — regardless of a Python distribution — it is <em>always</em> available (it’s also free and open source, so no vendor locking — yay!). You just need to import it:</p><pre>import pdb</pre><p>In CPython, reference Python implementation, the source code for standard modules resides in the <a href="https://github.com/python/cpython/tree/master/Lib">Lib</a> catalog.<em> </em>Therefore, the pdb’s source code can be found in <a href="https://github.com/python/cpython/blob/master/Lib/pdb.py">Lib/pdb.py</a>. If you have an evening to spare, I recommend taking a look at the source code. There is no better way to understand software than by reading its code. It’s very short too — last time I checked the main file was around 1700 lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*acgYVKmjRKeAabB_w0tMUQ.jpeg" /><figcaption><a href="https://github.com/python/cpython/blob/master/Lib/pdb.py">Lib/pdb.py</a></figcaption></figure><h3>A bit of jargon</h3><p>pdb is a debugger, which means that it allows you to “spy” on a program while it executes — by inspecting or modifying its runtime — or to see what the program did when it crashed. The latter technique is called <em>post-mortem debugging</em>.</p><p>pdb offers four basic features to help to find bugs:</p><ul><li>Execute the program step by step, under the direct control and supervision of the programmer (which is called <em>single-stepping</em> or <em>program animation</em>).</li><li>Make the program stop on specified lines (so-called <em>breakpoints</em>). pdb also supports <em>conditional breaking</em>, i.e., breakpoints with corresponding Boolean expressions which determine whether debugger should stop upon reaching the breakpoint.</li><li>Examine why or what had happened, when the program had stopped (via symbol resolver or expression interpreter).</li><li>Change the runtime of the program, by modifying the variables, to experiment with the effects it has on the program behavior.</li></ul><p>The program might be executing on the same machine as pdb, on another machine (e.g., with <a href="https://pypi.org/project/remote-pdb/">remote-pdb</a>), might be called by the programmer, or third-party (e.g., when debugging with <a href="https://pytest.org/">pytest</a>).</p><p>*There is also this thing called <em>reverse debugging</em>, but we will talk about it later.</p><h3>Getting started</h3><p>With the introduction out of the way, it’s time to get started with pdb. There are a couple of options to run it.</p><blockquote>Here is the <a href="https://docs.python.org/3.8/library/pdb.html#debugger-commands">documentation</a> for the commands. It’s good to keep it at hand, as we go through the tutorial.</blockquote><h4>Starting from the script</h4><p>Firstly, because the debugger is included in Python’s standard library, we can import it the same way we would any library. Then, we can call <a href="https://docs.python.org/3.8/library/pdb.html#pdb.set_trace">pdb.set_trace()</a> to hard-code a breakpoint (place in which program should halt the execution and yield the control to the programmer). The typical way to do it is:</p><pre>import pdb; pdb.set_trace()</pre><p>However, it implies editing the source code itself. This is invasive and may be considered awkward, but for most of the time, it’s good enough. I highly recommend adding a shortcut to your text-editor for inserting the setup line.</p><p><a href="https://asciinema.org/a/228096">Starting pdb via set_trace</a></p><blockquote><strong><em>New in version 3.7: </em></strong><em>You can use built-in </em><a href="https://docs.python.org/3.8/library/functions.html#breakpoint"><em>breakpoint</em></a><em>() instead of </em><em>import pdb; pdb.set_trace().</em></blockquote><h4>Starting from pdb</h4><p>Secondly, we can reverse the flow of control and run pdb before a single line of code is executed. When invoking Python interpreter with the <em>module</em> option (of the form -m &lt;module-name&gt;), the specified module (given it is located on the Python module path) is executed as a script. By calling python -m pdb &lt;script&gt;, then, we call pdb as a script to debug other scripts. This will result in breaking on the first line in the file:</p><pre>$ python3 -m pdb script.py<br>&gt; /home/siegmeyer/script.py(1)&lt;module&gt;()<br>-&gt; x = 1 # First line in the file.<br>(Pdb)</pre><p>Here &lt;script.py&gt;(1)&lt;module&gt;() means that we are at the first line in the file script.py and no code has been executed yet. If you’re executing from a string, the first part will read &lt;string&gt; (e.g., when starting via <a href="https://docs.python.org/3.8/library/pdb.html#pdb.run">pdb.run</a>).</p><p><a href="https://asciinema.org/a/228099">Starting pdb as a script</a></p><p>Oh, I almost forgot — to exit the debugger type <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-quit">quit</a> or exit. If you’ve started with set_trace , quit/exit will raise bdb.BdbQuit exception, and crash the program (it will <em>not</em> be resumed).</p><blockquote>Side-note: <em>pdb offers three functions (provided by the library, not the prompt) — </em><a href="https://docs.python.org/3.8/library/pdb.html#pdb.run"><em>run</em></a><em>, </em><a href="https://docs.python.org/3.8/library/pdb.html#pdb.runeval"><em>runeval</em></a><em> and </em><a href="https://docs.python.org/3.8/library/pdb.html#pdb.runcall"><em>runcall</em></a><em> which allow you to execute a statement, expression and a function under the debugger control, respectively. One can use them directly from the code or Python interpreter. In my estimation they are pretty much useless, so I’m not covering them. Here is an example usage (straight out of the </em><a href="https://docs.python.org/3.8/library/pdb.html"><em>documentation</em></a><em>):</em></blockquote><pre><strong>&gt;&gt;&gt; import</strong> <strong>pdb</strong><br><strong>&gt;&gt;&gt; import</strong> <strong>mymodule</strong><br><strong>&gt;&gt;&gt; </strong>pdb.run(&#39;mymodule.test()&#39;)<br>&gt; &lt;string&gt;(0)?()<br>(Pdb) continue<br>&gt; &lt;string&gt;(1)?()<br>(Pdb) continue<br>NameError: &#39;spam&#39;<br>&gt; &lt;string&gt;(1)?()<br>(Pdb)</pre><h3>Getting help</h3><p>The first and the last thing one needs when learning a new tool is a good help-system. Like every decent piece of software, pdb has a built-in one. We can access it via <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-help">h(elp)</a> command. To get help on help type: h help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*2MSX6yGbrtWmdzEyQBvcww.png" /></figure><p>Without arguments, h(elp) prints available commands (see above).</p><h4>Shortening names</h4><p>Please note the brackets around the last part of the command. The brackets indicate that the rest of the word is optional. This can save up a lot of keystrokes. However, you need to remember that commands take precedence over names. In effect, short cryptic variable like b will issue a command (break in this case) instead. Of course, this should not be a problem if your naming hygiene is well-maintained.</p><h4>Command signatures</h4><p>help is here to tell us about commands; but how can we know which commands accept which arguments? What about commands that accept multiple arguments in different forms? What if they are optional? To specify that pdb is using quasi-<a href="https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form">EBNF</a> (it’s not really it, but somewhat similar).</p><p>In short, arguments to commands must be separated by whitespace. Optional arguments are enclosed in square brackets: []. Alternatives in the command syntax are enclosed by parenthesis and separated by a vertical bar:(|).</p><p>Let’s look at the example (nevermind the actual command; we will focus on the notation for now):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*bCOdupa1CF2HmpQV7sHuMQ.png" /></figure><p>What this means is that:</p><ul><li>break can be called with or without any argument — [] means <em>optional</em>.</li><li>break can be given [filename:]lineno or function —( | ) means <em>alternative</em> (here, again, first argument form has an optional part).</li><li>break always accepts zero or more conditions, separated by a comma.</li></ul><h3>Getting things done</h3><p>Here are the absolute basics.</p><h4>Inspection</h4><p>Debugging is all about spying on a running program. For that, we need to able to inspect variables. To evaluate a name, just type it in. If the naming is poor, and the variable clashes with pdb commands, you can use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-p">p(rint)</a> to explicitly print it. For example:</p><pre>(Pdb) p a_list<br>[&#39;a&#39;, &#39;list&#39;, &#39;of&#39;, &#39;strings&#39;]</pre><p>There is also <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-pp">pp</a> (for <em>pretty print</em>) which takes care of a bit more sane formatting in some cases — for example when printing lists (however, to be honest, I do not remember using it once).</p><p>If you want to quickly print all the arguments passed to the currently inspected function, <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-args">args</a> is your friend:</p><pre>(Pdb) list<br>  1     def foo(spam, ham, eggs)<br>  2         import pdb<br>  3  -&gt;     pdb.set_trace()<br>  4<br>  5<br>  6 foo(1, 2, 3)<br>[EOF]<br>(Pdb) args<br>spam = 1<br>ham = 2<br>eggs = 3</pre><p>*list displays source code. We will talk about it in more depth a bit later.</p><p><a href="https://asciinema.org/a/228089">Inspecting variables</a></p><h4>Interpretation</h4><p>Before we go into topics such as single-stepping or breakpoints, let’s cover features not specific to debuggers.pdb supports expression interpretation (with some restrictions), so any valid Python expression is executable in pdb’s prompt. This allows us to modify the runtime (e.g., by introducing variables or calling functions) and inspecting what’s already available. Please note, however, the usage of the word “expression”. pdb is not a full interpreter, and so multiline statements are out the window. This includes things like class or function declarations (lambdas are ok because they are expressions).</p><pre>(Pdb) 1 / 2 * 3<br>1.5<br>(Pdb) foo = lambda bar: bar * 2<br>(Pdb) foo(&#39;bzz&#39;)<br>bzzbzz</pre><p>If for some reason pdb doesn&#39;t recognize command as a valid Python expression, you can explicitly execute it as such using the bang ! operator:</p><pre>(Pdb) !x, y = 1, 2<br>(Pdb) !x, y = y, x + y</pre><p>*Note the lack of the whitespace after the exclamation mark.</p><h4>Navigation</h4><p>Next, we need to be able to navigate the source code. For that, we will use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-list">list</a>. Without arguments, list displays 11 lines around the current position in the file or continues going through the previous listing.</p><p>Seems straightforward, except for that last part. It turns out that default list behavior is somewhat counterintuitive — list displays code at the pointer which is shifted down every time the command is called. When executed for the first time, the pointer is taken to be the current position.</p><p>Therefore, if we keep repeating the command, we keep going down through the code. To list the same chunk of code, use l . (there is another fix for this which we will discuss later). You can also specify lines to print, for example list 9 11. Since Python 3.2 we also have ll (or <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-ll">longlist</a>), which displays the whole source code for the current function or a lexical block. When debugging module-level code, this will print the entire file!</p><p>Next up, we have <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-next">n(ext)</a> — execute until the next line is reached or the function returns. This is self-explanatory. However, one big gotcha is that next refers to the next <em>logical</em> line. This means that if we are at the end of the loop body, we will jump to its beginning (given that loop condition holds).</p><p><a href="https://asciinema.org/a/229402">Stepping with next</a></p><p>Stepping through the loop with n(ext) gets tiresome pretty quickly. Luckily, we have <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-until">unt(il)</a> — without argument, it continues the execution until the line with a greater number than the current one is reached. If a line number is specified, continue until that line. This means that when at the end of the loop body, until will not loop around, but instead break out of the loop.</p><p><a href="https://asciinema.org/a/2bqBRzqm42sWKBf8nzA7wMnbg">Stepping in and out of the loop with &quot;until&quot;</a></p><p>If you want to break out of the function, use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-return">return</a>. It allows following the execution and breaking at the last (logical) statement in the function. If there are multiple return statements, return will stop at the one determined by the control flow. If you want to check the value of the last returned function, use retval.</p><p><a href="https://asciinema.org/a/229409">Skipping the function body with &quot;return&quot;</a></p><p>To continue execution of the program (i.e., to give up the control and effectively end the debugging), use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-continue">continue</a>.</p><blockquote>Pro-tip<em>: If you started your session via </em><em>set_trace, and the setup line is placed in a loop (or any block of code being called repeatedly), you might easily find yourself caught in a seemingly endless spiral of </em><em>pdb&#39;s prompts. In such case </em><em>continue won’t help you (since it can only refer to the current session, not the future ones). To break out of it, use this hack: </em><em>pdb.set_trace = None</em></blockquote><h4>Jumping around</h4><p>Reversing time and stepping back through program state is called reverse debugging. It’s a very advanced technique and pdb does not support it at the time (although there are some other experimental implementations for Python). Nonetheless, in order to jump back and forth between/through/around executable lines, without resetting the program state, we can use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-jump">jump</a>. To jump forth, simply type jump specifying the next line that should be executed. Please note that all the lines between the current and the target are not going to be executed. To jump back, use the same format. This time we will move up to line 100. Please note that every line between the current one and the target (which has smaller line number this time around) still remains executed.</p><p><a href="https://asciinema.org/a/229527">Moving up and down with &quot;jump&quot;</a></p><p>To summarize:</p><ul><li>list displays code;</li><li>next continues execution until the next logical step;</li><li>until continues execution until the next physical line;</li><li>continue continues execution indefinitely;</li><li>return jumps to the end of the current function;</li><li>jump allows moving up and down along the executable lines without changing the program state.</li></ul><h4>Breakpoints</h4><p>Before we can really start getting things done, we need one last component — dynamic breakpoints. Until now, we’ve used set_trace to specify where debugger should stop the execution. With <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-break">break</a> we can create breakpoints dynamically, during an active session. Let’s look at the signature one more time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*bCOdupa1CF2HmpQV7sHuMQ.png" /></figure><p>That’s a mouthful, so let’s unpack it. Simplest usage (what you will do most of the time) is just ordering pdb to break at a line. To set a breakpoint, type break &lt;lineno&gt;.</p><p>Additionally, we can specify a filename in which interesting line is located by prepending it to the invocation:</p><pre>(Pdb) break some_file:123</pre><p>If you don’t feel like counting lines, you can use function name:</p><pre>(Pdb) break some_function</pre><p>In such a case, the debugger will stop at the first line of the function body.</p><p>To clear a breakpoint, use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-clear">clear</a> lineno (clear without any arguments will delete all breakpoints).</p><p>To list all existing breakpoints, simply type break (without any arguments):</p><pre>(Pdb) break<br>Num Type         Disp Enb   Where<br>1   breakpoint   keep yes   /script.py:3<br>2   breakpoint   keep yes   /script.py:5</pre><h4>Conditional breakpoints</h4><p>If you’re interested only in certain conditions when setting up a breakpoint (i.e., conditions under which the debugger should stop), you can specify them as the last argument, condition:</p><pre>(Pdb) b 15, x == 7</pre><p>The above command says that the debugger should stop whenever line 15 is reached and x is equal to 7. In general, all valid expressions are allowed, and all expressions are to be evaluated in the scope in which the breakpoint was defined.</p><p><a href="https://asciinema.org/a/229507">Setting up breakpoints</a></p><h3>Advanced topics</h3><h4>Post-mortem debugging</h4><p><em>Post-mortem debugging</em> is a technique which allows us to debug a crashed program, at the time it died, using its traceback object. Naturally, because it is no longer running, we cannot step through it and are restricted to inspecting the last state of its execution context (which is represented by the traceback).</p><blockquote><strong><em>A traceback</em></strong><em> is a stack trace (a report on the state of the call stack) from the point of an exception handler (code catching the error) down the call chain to the origin of the error (where the exception was thrown).</em></blockquote><p>The usual way of entering post-mortem is via <a href="https://docs.python.org/3.8/library/pdb.html#pdb.pm">pdb.pm()</a> or <a href="https://docs.python.org/3.8/library/pdb.html#pdb.post_mortem">pdb.post_mortem()</a>. Those methods are available when <a href="https://docs.python.org/3/library/sys.html#sys.last_traceback">sys.last_traceback</a> is not null:</p><pre>&gt;&gt;&gt; import script<br>Traceback (most recent call last):<br>  File &quot;script.py&quot;, line 1, in &lt;module&gt;<br>    0/0<br>ZeroDivisionError: division by zero<br>&gt;&gt;&gt; pdb.pm()<br>&gt; &lt;...&gt;/script.py(1)&lt;module&gt;()<br>-&gt; 0/0<br>(Pdb)</pre><p>The catch is, this will only work when Python interpreter is handling the error. (so that last_traceback is properly set up). The following code:</p><pre>try:<br>    0/0<br>except:<br>    import pdb; pdb.pm()</pre><p>will throw an error:</p><pre>Traceback (most recent call last):<br>  File &quot;exc.py&quot;, line 2, in &lt;module&gt;<br>    0/0<br>ZeroDivisionError: division by zero</pre><pre>During handling of the above exception, another exception occurred:</pre><pre>Traceback (most recent call last):<br>  File &quot;exc.py&quot;, line 4, in &lt;module&gt;<br>    import pdb; pdb.pm()<br>  File &quot;/usr/lib/python3.7/pdb.py&quot;, line 1625, in pm<br>    post_mortem(sys.last_traceback)<br>AttributeError: module &#39;sys&#39; has no attribute &#39;last_traceback&#39;</pre><p>Of course, it doesn’t make much sense to enter pm in the <em>except</em> clause anyway.</p><p>Additionally, you can call post_mortem with explicit traceback:</p><pre>pdb.post_mortem(exception_obj.__traceback__)</pre><h4>Traversing the stack</h4><p>So far we’ve only seen navigation around the code and stepping inside functions. However, pdb allows traversing the <a href="https://en.wikipedia.org/wiki/Call_stack">call stack</a> (chain of function calls in the running program). This is very handy when you want to know what function called what, and when. It is achieved with three commands: <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-where">where</a>, <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-up">up</a> and <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-down">down</a>.</p><ul><li>where — print the stack trace, with the most recent frame at the bottom.</li><li>up — move to the previous frame in the stack trace.</li><li>down — move to next frame in the stack trace (if applicable).</li></ul><p><a href="https://asciinema.org/a/229529">Moving up and down the stack trace with &quot;up&quot; and &quot;down&quot;</a></p><h4>Remote debugging</h4><p>If you are trying to debug a program running on a distant machine (or one that you have no direct access to), it is often useful to use remote debugging. pdb does not support it out-of-the-box, but luckily we have <a href="https://pypi.org/project/remote-pdb/">remote-pdb</a> package. Setting up a remote session is very simple:</p><pre>&gt;&gt;&gt; import remote_pdb as rpdb                                                                                                                                                                                      <br>&gt;&gt;&gt; rpdb.set_trace(&#39;0.0.0.0&#39;, 46485)                                                                                                                                                                                               <br>CRITICAL:root:RemotePdb session open at 0.0.0.0:46485, waiting for connection ...                                                                                                                                <br>RemotePdb session open at 0.0.0.0:46485, waiting for connection ...</pre><p>As you can see, this opens up a connection on the displayed port (46485). We can connect to it using Telnet:</p><pre>telnet 0.0.0.0 46485<br>Trying 0.0.0.0...<br>Connected to 0.0.0.0.<br>Escape character is &#39;^]&#39;.<br>--Return--<br>&gt; &lt;stdin&gt;(1)&lt;module&gt;()-&gt;None<br>(Pdb)</pre><p>or, from another host:</p><pre>telnet 10.3.39.124 46485</pre><h4>Configuration</h4><p>pdb can be configured via .pdbrc file:</p><blockquote>If a file <em>.pdbrc</em> exists in the user’s home directory or in the current directory, it is read in and executed as if it had been typed at the debugger prompt. This is particularly useful for aliases. If both files exist, the one in the home directory is read first and aliases defined there can be overridden by the local file.</blockquote><p>For details, consult the <a href="https://docs.python.org/3/library/pdb.html?highlight=pdb#debugger-commands">documentation</a>.</p><h4>Extensions</h4><p>As with most open-source software, pdb has community extensions. Their description is beyond the scope of this article, but take a look at <a href="https://pypi.org/project/ipdb/">ipdb</a> and <a href="https://pypi.org/project/pdbpp/">pdb++</a>. One of the best additions to look out for is <em>sticky</em> mode.</p><h3>Summary</h3><p>In conclusion, we’ve looked at all most-used pdb features. We learned:</p><ul><li>different ways of starting a pdb session;</li><li>how to get help;</li><li>how to read command signatures;</li><li>how to inspect variables;</li><li>how to use pdb as an interpreter;</li><li>how to navigate through the code;</li><li>how to inspect the stack;</li><li>how to use breakpoints;</li><li>what is post-mortem debugging;</li><li>how pdb can be utilized to debug remotely;</li><li>how pdb can be configured.</li></ul><p>This should give you a good start in incorporating pdb in your usual Python workflow.</p><p>Thank you for reading! You can find me on <a href="https://github.com/IwoHerka">GitHub</a> or <a href="http://iwoherka.eu/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4f3b42f3f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/https-medium-com-iwoherka-working-with-pdb-in-python-8d4f3b42f3f4">Working with pdb in Python</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>