<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  <id>https://dawranliou.com/atom.xml</id>
  <title>Daw-Ran Liou's website</title>
  <updated>2024-03-01T00:00:00Z</updated>
  <link href="https://dawranliou.com/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="https://dawranliou.com"/>
  <author>
    <name>Daw-Ran Liou</name>
  </author>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/the-biggest-positive-for-emacs</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>The Biggest Positive for Emacs</title>
    <updated>2021-03-18T00:00:00Z</updated>
    <published>2021-03-18T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/the-biggest-positive-for-emacs" type="text/html"/>
    <content type="html">&lt;p&gt;I came across &lt;a href="https://youtu.be/LKegZI9vWUU"&gt;the interview with Henrik Lissner&lt;/a&gt;, the creator of Doom Emacs, and it really resonated with me about the biggest positive for Emacs (starting at &lt;a href="https://youtu.be/LKegZI9vWUU?t=2917"&gt;48:37&lt;/a&gt;):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The biggest positive for Emacs, hands down (that addresses all its negatives) is self-documenting, which primarily means documentation is a first-class citizen in ELisp. You can easily look it up any variable, function, macro, face, whatever, even something that’s not defined in ELisp but defined in the C code you can look it up. […]&lt;/p&gt;
&lt;p&gt;If you use Emacs you’re living in a REPL: you have direct, unfeathered access to its guts. And if you want to know anything about the current state of Emacs, you can just ask it directly. That’s something I don’t think any other editors can do quite at that level.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Living inside the REPL (or working inside a running program) is such a powerful technique in programming. That’s also one of the reasons drove me towards Emacs after learning Clojure, even though the two LISPs have very different ideals or philosophies.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/rewriting-my-emacs-config</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Rewriting My Emacs Config</title>
    <updated>2020-11-06T00:00:00Z</updated>
    <published>2020-11-06T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/rewriting-my-emacs-config" type="text/html"/>
    <content type="html">&lt;p&gt;Since the last post, I had switched over to &lt;a href="https://github.com/hlissner/doom-emacs"&gt;Doom Emacs&lt;/a&gt; for a while and then, hopefully, have switched back to my hand-crafted emacs config for the last time. I wanted to try Doom for some reasons:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;I didn’t like the startup time of my previous handcrafted emacs config,&lt;/li&gt;
&lt;li&gt;I found painful to look at my emacs config, and&lt;/li&gt;
&lt;li&gt;I wanted to learn more from this very successful community-driven project.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Even prior to switching over to Doom, I took a lot of inspirations from it to enhance my config. One main frustration of using Spacemacs was its think layers of abstracts. I didn’t find such frustration with Doom. Doom is very well documented and stays true to its mantras:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Close to metal.&lt;/strong&gt; There’s less between you and vanilla Emacs by design. That’s less to grok and less to work around when you tinker. Internals ought to be written as if reading them were part of Doom’s UX, and it is!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Trying various modules, it’s fun exploring various pre-configured packages without the hustle to configure them pre-maturely. As an example, I like the &lt;a href="https://github.com/hlissner/doom-emacs/tree/develop/modules/lang/org"&gt;&lt;code&gt;org&lt;/code&gt; module&lt;/a&gt; just work out of the box with various of plugins.&lt;/p&gt;
&lt;p&gt;However, eventually I grew tired of looking at all the keybindings that I wasn’t using. All the keybindings and functionalities that I wasn’t using, or didn’t spark joy in me, made me sad. For every single unused keybinding, it is an extra mental burden in my workflow. If I get rid of all the unnecessary keybindings I could improve the efficiencies on the ones I use most often, because I no longer need the long nested key strokes anymore.&lt;/p&gt;
&lt;p&gt;Also, I found the &lt;a href="https://www.youtube.com/channel/UCAiiOTio8Yu69c3XnR7nQBQ"&gt;System Crafters&lt;/a&gt; YouTube serious &lt;a href="https://www.youtube.com/playlist?list=PLEoMzSkcN8oPH1au7H6B7bBJ4ZO7BXjSZ"&gt;Emacs From Scratch&lt;/a&gt;. It really was a godsend to me to help me start writing my Emacs config again. &lt;a href="https://github.com/dawranliou/emacs.d"&gt;My current Emacs Config&lt;/a&gt; drew a lot of inspirations from it and from the author’s, David Wilson’s, &lt;a href="https://github.com/daviwil/dotfiles/blob/master/Emacs.org"&gt;own config&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;So far, I really like that I have total control over my emacs configuration, and the start time wasn’t too terrible either.&lt;/p&gt;
&lt;p&gt;Links: - &lt;a href="https://github.com/hlissner/doom-emacs"&gt;Doom Emacs&lt;/a&gt; - &lt;a href="https://www.youtube.com/playlist?list=PLEoMzSkcN8oPH1au7H6B7bBJ4ZO7BXjSZ"&gt;Emacs From Scratch&lt;/a&gt; - &lt;a href="https://github.com/dawranliou/emacs.d"&gt;My current Emacs Config&lt;/a&gt; - &lt;a href="https://github.com/dawranliou/emacs.d/blob/master/themes/sketch-white-theme.el"&gt;My current Emacs theme&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/advise-eglot-to-support-clojure-monorepo-setup</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Advise Eglot to Support Clojure Monorepo Setup</title>
    <updated>2022-03-28T00:00:00Z</updated>
    <published>2022-02-27T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/advise-eglot-to-support-clojure-monorepo-setup" type="text/html"/>
    <content type="html">&lt;h2 id="updates-2022-03-28-a-better-solution"&gt;&lt;em&gt;Updates 2022-03-28: A Better Solution&lt;/em&gt;&lt;/h2&gt;
&lt;p&gt;Since I published the original solution, I've found certain things were not working as I claimed. There's a better solution, which is mentioned shortly in this section, without hacking Emacs lisp code. Because my intent to write this article is less about giving you the solution but more about demonstrating a way to tweak Emacs' package to fit your own desires, I decided to keep its original content alive, with the hope that it would still be insightful to some of you.&lt;/p&gt;
&lt;p&gt;Here's the updated solution! Since &lt;a href="https://github.com/clojure-lsp/clojure-lsp/issues/752"&gt;clojure-lsp issue #752&lt;/a&gt;, &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; uses the classpath to discover the source code to analyze. The trick is to merge all the classpaths from the monorepo's sub-projects. Conveniently, &lt;code class="verbatim"&gt;lein-monolith&lt;/code&gt; provides a way to &lt;a href="https://github.com/amperity/lein-monolith#merged-source-profile"&gt;Merge Source Profile&lt;/a&gt;. Therefore we can invoke the command &lt;code class="verbatim"&gt;lein monolith with-all classpath&lt;/code&gt; instead. Your &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; configuration file that goes to &lt;code class="verbatim"&gt;&amp;lt;monorepo-root&amp;gt;/.lsp/config.edn&lt;/code&gt; should look like this:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;{:project-specs [{:project-path &amp;quot;project.clj&amp;quot;
                  :classpath-cmd [&amp;quot;lein&amp;quot; &amp;quot;monolith&amp;quot; &amp;quot;with-all&amp;quot; &amp;quot;classpath&amp;quot;]}]}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that if you have a large monorepo, you might need to bump the &lt;code class="verbatim"&gt;eglot-connect-timeout&lt;/code&gt; to a larger number to let &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; finish analyzing all the source code. I set my &lt;code class="verbatim"&gt;eglot-connect-timeout&lt;/code&gt; to &lt;code class="verbatim"&gt;600&lt;/code&gt; currently.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;em&gt;The following is the original content.&lt;/em&gt;&lt;/p&gt;
&lt;h2 id="abstract"&gt;Abstract&lt;/h2&gt;
&lt;p&gt;The advice system and dynamic scoping are two powerful facilities in Emacs. In this article, I'll show you how to use them to tweak Emacs' behaviors and facts to workaround the &lt;code class="verbatim"&gt;eglot&lt;/code&gt; package while setting up &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; for a monorepo.&lt;/p&gt;
&lt;h2 id="background"&gt;Background&lt;/h2&gt;
&lt;p&gt;In Emacs, there are two popular LSP clients: &lt;a href="https://emacs-lsp.github.io/lsp-mode/"&gt;&lt;code class="verbatim"&gt;lsp-mode&lt;/code&gt;&lt;/a&gt; and &lt;a href="https://github.com/joaotavora/eglot"&gt;&lt;code class="verbatim"&gt;eglot&lt;/code&gt;&lt;/a&gt;. Although &lt;a href="https://github.com/joaotavora/eglot#historical-differences-to-lsp-modeel"&gt;historically, there were more noticeable differences between the two packages&lt;/a&gt; in terms of their usage and their UI, these days, I'm pretty happy with both of them. I can achieve pretty minimal UI in &lt;code class="verbatim"&gt;lsp-mode&lt;/code&gt; (as &lt;code class="verbatim"&gt;eglot&lt;/code&gt; always is &#128578;) by tweaking several custom settings, and both work well with built-in packages, which I've grown accustomed to over the years.&lt;/p&gt;
&lt;p&gt;Over the past few years of using Emacs, I started to prefer the class of packages that work very closely with the Emacs' built-in facilities instead of inventing their isolated world&lt;a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;. Such packages provide a narrow focus that enhances a specific part of Emacs. I love this class of packages because I can simply reject a dependency if it's not essential to my workflow. Therefore, I decided to hop back from &lt;code class="verbatim"&gt;lsp-mode&lt;/code&gt; to &lt;code class="verbatim"&gt;eglot&lt;/code&gt; for its simplicity.&lt;/p&gt;
&lt;p&gt;Because of &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt;'s limitation on discovering source code (&lt;a href="https://github.com/clojure-lsp/clojure-lsp/issues/191"&gt;issue #191&lt;/a&gt; and &lt;a href="https://github.com/clojure-lsp/clojure-lsp/issues/551"&gt;issue #551&lt;/a&gt;) with the &lt;a href="https://github.com/amperity/lein-monolith"&gt;&lt;code class="verbatim"&gt;lein-monolith&lt;/code&gt;&lt;/a&gt; setup and my needs at work, I didn't change the &lt;code class="verbatim"&gt;:project-paths&lt;/code&gt; setting as others did (e.g., &lt;a href="https://github.com/clojure-lsp/clojure-lsp/issues/191#issuecomment-918373230"&gt;this comment&lt;/a&gt; and &lt;a href="https://gist.github.com/bendlas/4a2a98b1cbe1d1efa8a7ef6850934e13"&gt;this gist&lt;/a&gt;). Instead, I run a different &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; server session for each sub-project. In &lt;code class="verbatim"&gt;lsp-mode&lt;/code&gt;, this can be done by customizing the project root the first time launching the &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt;. Next, I'll show you the issue I faced using &lt;code class="verbatim"&gt;eglot&lt;/code&gt; and how to teach it (or &lt;em&gt;advise&lt;/em&gt; it &#128521;) to work around it.&lt;/p&gt;
&lt;h2 id="problem"&gt;Problem&lt;/h2&gt;
&lt;p&gt;When &lt;code class="verbatim"&gt;eglot&lt;/code&gt; starts the &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; server, it infers&lt;a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; the project root by utilizing the &lt;code class="verbatim"&gt;project.el&lt;/code&gt; built-in package. Out of the box, Emacs consider the project root to be the current version-controlled root directory. If you are using &lt;code class="verbatim"&gt;git&lt;/code&gt;, the project root is the parent folder of the &lt;code class="verbatim"&gt;.git/&lt;/code&gt; folder. While this inference is correct most of the time, I want this to be different for my monorepo project at work, which has the directory structure like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;root/
  |--- .git/
  |--- projects.clj
  |--- project-a/
  |      |--- projects.clj
  |      |--- src/
  |--- project-b/
  |      |--- projects.clj
  |      |--- src/
  .
  .
  .
  |--- project-n
         |--- projects.clj
         |--- src/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code class="verbatim"&gt;root/&lt;/code&gt; is the root of our monorepo, which uses the &lt;code class="verbatim"&gt;projects.clj&lt;/code&gt; file and &lt;code class="verbatim"&gt;lein-monolith&lt;/code&gt; to tie all of its sub-projects together. All sub-projects are version-controlled together under &lt;code class="verbatim"&gt;root/&lt;/code&gt;. The &lt;code class="verbatim"&gt;root/&lt;/code&gt; project itself does not contain any source code, whereas the sub-projects do.&lt;/p&gt;
&lt;p&gt;With this setup, editing any source file in any sub-project will connect to the &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; server session at &lt;code class="verbatim"&gt;root&lt;/code&gt; by default. The question is: how to tweak &lt;code class="verbatim"&gt;eglot&lt;/code&gt; to use the sub-project root as the &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; server session?&lt;/p&gt;
&lt;h2 id="solution"&gt;Solution&lt;/h2&gt;
&lt;p&gt;I came up with this solution that ensures the &lt;code class="verbatim"&gt;eglot-ensure&lt;/code&gt; function will try to locate the &lt;code class="verbatim"&gt;clojure-project-dir&lt;/code&gt; as the project root when launching an LSP session. If &lt;code class="verbatim"&gt;clojure-project-dir&lt;/code&gt; isn't found, it falls back to using the version-control root to launch the LSP server.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;;; My personal settings that you might not require
;;(add-hook &amp;#39;clojure-mode-hook &amp;#39;eglot-ensure)
;;(custom-set-variables &amp;#39;(eglot-connect-timeout 300))

(defun project-try-clojure-project (dir)
  &amp;quot;Try to locate a Clojure project.&amp;quot;
  (when-let ((found (clojure-project-dir)))
    (cons &amp;#39;transient found)))

(defun find-clojure-project-advice (orig-fun &amp;amp;rest args)
  &amp;quot;Fix project-root for the clojure monorepo setup.&amp;quot;
  (let ((project-find-functions
         (cons &amp;#39;project-try-clojure-project project-find-functions)))
    (apply orig-fun args)))

(advice-add &amp;#39;eglot-ensure :around #&amp;#39;find-clojure-project-advice)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But how does this work?&lt;/p&gt;
&lt;h2 id="teaching-emacs-new-tricks-by-giving-it-dynamic-advices"&gt;Teaching Emacs new tricks by giving it dynamic advices&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming"&gt;Aspect-Oriented Programming&lt;/a&gt; page on Wikipedia:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by &lt;strong&gt;adding additional behavior to existing code (an advice) without modifying the code itself&lt;/strong&gt;, instead separately specifying which code is modified via a "pointcut" specification, such as "log all function calls when the function's name begins with 'set'".&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I only learned the concept of AOP because of Emacs. It fits surprisingly well for a plug-in system in programs like Emacs. The users of Emacs are empowered to enrich their experience with third-party packages and are empowered to hack the behaviors (functions) of any package from afar through &lt;a href="https://www.gnu.org/software/emacs/manual/html_node/elisp/Advising-Functions.html"&gt;the advice system&lt;/a&gt; without touching the source code of those packages.&lt;/p&gt;
&lt;p&gt;Not only are the behaviors hackable, but the facts (variables) are also modifiable thanks to &lt;a href="https://www.emacswiki.org/emacs/DynamicScoping"&gt;Dynamic Scoping&lt;/a&gt;. Dynamic Scoping gives the Emacs users the power to change variable bindings with a dynamic extend.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(defun project-try-clojure-project (dir)
  &amp;quot;Try to locate a Clojure project.&amp;quot;
  (when-let ((found (clojure-project-dir)))
    (cons &amp;#39;transient found)))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here we define a backend for the &lt;code class="verbatim"&gt;project-find-functions&lt;/code&gt;. If a &lt;code class="verbatim"&gt;clojure-project-dir&lt;/code&gt; is found, &lt;code class="verbatim"&gt;project-try-clojure-project&lt;/code&gt; returns the tuple &lt;code class="verbatim"&gt;(transient . &amp;lt;PROJECT DIR PATH STRING&amp;gt;)&lt;/code&gt;, otherwise &lt;code class="verbatim"&gt;nil&lt;/code&gt;. This function's signature will satisfy as an element in the &lt;code class="verbatim"&gt;project-find-functions&lt;/code&gt;. However, we don't want to change the behavior across the board. We want to limit the scope of the modified &lt;code class="verbatim"&gt;project-find-functions&lt;/code&gt; variable. So we use a let-binding to change the dynamic scope:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(defun find-clojure-project-advice (orig-fun &amp;amp;rest args)
  &amp;quot;Fix project-root for the clojure monorepo setup.&amp;quot;
  (let ((project-find-functions
         (cons &amp;#39;project-try-clojure-project project-find-functions)))
    (apply orig-fun args)))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code class="verbatim"&gt;find-clojure-project-advice&lt;/code&gt; function binds the &lt;code class="verbatim"&gt;project-find-functions&lt;/code&gt; variable with the &lt;code class="verbatim"&gt;project-try-clojure-project&lt;/code&gt; function as the first element in the list. This binding only exists to the extent of this function call. Therefore, invoking &lt;code class="verbatim"&gt;project-current&lt;/code&gt; function under other contexts will not be affected.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(advice-add &amp;#39;eglot-ensure :around #&amp;#39;find-clojure-project-advice)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Lastly, we use the &lt;code class="verbatim"&gt;add-advice&lt;/code&gt; to advise the &lt;code class="verbatim"&gt;eglot-ensure&lt;/code&gt; function to invoke the &lt;code class="verbatim"&gt;find-clojure-project-advice&lt;/code&gt;. The &lt;code class="verbatim"&gt;:around&lt;/code&gt; keyword denotes that we want to compose the advising function (&lt;code class="verbatim"&gt;find-clojure-project-advice&lt;/code&gt;) around the advised function (&lt;code class="verbatim"&gt;eglot-ensure&lt;/code&gt;) so the let-binding can enter the dynamic scope of &lt;code class="verbatim"&gt;eglot-ensure&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;To recap, this article:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Provides an alternative way of setting up &lt;code class="verbatim"&gt;clojure-lsp&lt;/code&gt; with the &lt;code class="verbatim"&gt;eglot&lt;/code&gt; LSP client when working with a monorepo,&lt;/li&gt;
&lt;li&gt;Demonstrates how to use Aspect-Oriented Programming and Dynamic Scoping in Emacs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Without modifying any source code of Emacs or its packages, we can change the behavior (the &lt;code class="verbatim"&gt;eglot-ensure&lt;/code&gt; function) and the fact (the &lt;code class="verbatim"&gt;project-find-functions&lt;/code&gt; variable) to satisfy a specific use case while keeping other parts of Emacs intact. I think this is a great example to showcase why Emacs is so powerful and valuable to its users.&lt;/p&gt;
&lt;h2 id="footnotes"&gt;Footnotes&lt;/h2&gt;
&lt;section class="footnotes" role="doc-endnotes"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn1" role="doc-endnote"&gt;&lt;p&gt;This philosophy plays well with my favorite programming language, Clojure. The community has learned to work together by creating single-purpose libraries that strongly prefer to use Clojure data as the universal language.&lt;a href="#fnref1" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn2" role="doc-endnote"&gt;&lt;p&gt;&lt;code class="verbatim"&gt;eglot--guess-contact&lt;/code&gt; is the internal function that makes this inference.&lt;a href="#fnref2" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/compiling-emacs-from-source</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Compiling Emacs from Source on MacOS Big Sur</title>
    <updated>2021-11-09T00:00:00Z</updated>
    <published>2021-11-09T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/compiling-emacs-from-source" type="text/html"/>
    <content type="html">&lt;p&gt;Recently I started to compile the Emacs master branch from source for daily use instead of using one of the popular formulas on Homebrew.&lt;a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; It’s pretty cool to try the latest features like the native compilation and the native emoji before the stable releases. Also it’s quite a satisfying experience to be able to compile Emacs from source. It took me several tries to get it right but I think I documented everything. Here are the steps:&lt;/p&gt;
&lt;h2 id="install-dependencies"&gt;Install dependencies&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;libxml2&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Optional for native compilation
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;gcc&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;libgccjit&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class="sh"&gt;&lt;code&gt;brew install libxml2 gcc libgccjit&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Follow the post-installation instruction from &lt;code&gt;libxml2&lt;/code&gt; to fix the path and environment variables.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;If you need to have libxml2 first in your PATH, run:
  echo &amp;#39;export PATH=&amp;quot;/usr/local/opt/libxml2/bin:$PATH&amp;quot;&amp;#39; &amp;gt;&amp;gt; ~/.zshrc

For compilers to find libxml2 you may need to set:
  export LDFLAGS=&amp;quot;-L/usr/local/opt/libxml2/lib&amp;quot;
  export CPPFLAGS=&amp;quot;-I/usr/local/opt/libxml2/include&amp;quot;

For pkg-config to find libxml2 you may need to set:
  export PKG_CONFIG_PATH=&amp;quot;/usr/local/opt/libxml2/lib/pkgconfig&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="compile"&gt;Compile&lt;/h2&gt;
&lt;p&gt;I configured my Emacs with the following options. I’m not exactly sure what each meant but this combination seems to work on my machine:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;--with-cairo&lt;/code&gt; - enable Cairo drawing&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--with-imagemagick&lt;/code&gt; - enable ImageMagick support&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--with-xwidgets&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--with-native-compilation&lt;/code&gt; - enable native compilation&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class="sh"&gt;&lt;code&gt;./autogen.sh
./configure --with-cairo --with-imagemagick --with-xwidgets --with-native-compilation
# Build MacOS App bundle, `install` doesn’t actually install anything.
make clean install&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The Emacs.app App bundle should now be in the &lt;code&gt;nextstep/&lt;/code&gt; directory. Simply copy it to the &lt;code&gt;/Applications&lt;/code&gt; folder to use it.&lt;/p&gt;
&lt;h2 id="references"&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://stuff-things.net/2020/12/28/building-emacs-27-dot-1-on-macos-big-sur/"&gt;Building Emacs 27.1 on macOS Big Sur&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.freesteph.info/blog/compiling-emacs.html"&gt;Compiling Emacs in the absence of a configurable brew version&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="footnotes"&gt;Footnotes&lt;/h2&gt;
&lt;section class="footnotes" role="doc-endnotes"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn1" role="doc-endnote"&gt;&lt;p&gt;Probably the popular options are: &lt;a href="https://bitbucket.org/mituharu/emacs-mac/src/master/"&gt;&lt;code&gt;emacs-mac&lt;/code&gt;&lt;/a&gt;, &lt;a href="https://github.com/d12frosted/homebrew-emacs-plus"&gt;&lt;code&gt;emacs-plus&lt;/code&gt;&lt;/a&gt;, and &lt;a href="https://github.com/daviderestivo/homebrew-emacs-head"&gt;&lt;code&gt;emacs-head&lt;/code&gt;&lt;/a&gt;. I was mostly using &lt;code&gt;emacs-mac&lt;/code&gt; in the past.&lt;a href="#fnref1" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/think-rationally-talk-emotionally</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Think rationally, talk emotionally</title>
    <updated>2019-11-20T00:00:00Z</updated>
    <published>2019-11-20T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/think-rationally-talk-emotionally" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;The current state of my mind was greatly influenced by John Locke (洛克) and Empiricism (經驗主義). In contrast to René Descartes’s (笛卡爾) Rationalism (理性主義) where human have innate ideas, philosopher and physician John Locke believes that knowledge is instead “determined only by experience derived from sense perception.” This is also known as Empiricism. The ideas we learned in the early days would have significant effects on our thoughts.&lt;/em&gt;&lt;/p&gt;
&lt;!-- more --&gt;
&lt;hr /&gt;
&lt;p&gt;We praise the human mind of being able to think rationally. We induce, we deduct, and we invent. We believe ourselves rational creatures. Yet we rarely act rationally. We are quick to react to instincts, which is not a bad thing to survive in the stone age. Even in modern days, high profile investors would usually rely on his/her gut feeling to bet on startups more than anything else. Because there are just things that words cannot describe.&lt;/p&gt;
&lt;p&gt;Rationally, we must first accept our ignorance, which we define as the state of lacking knowledge.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“Our comforting conviction that the world makes sense rests on a secure foundation: our almost unlimited ability to ignore our ignorance.” Daniel Kahneman, Thinking, Fast and Slow&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We use words and languages to capture ideas. However, languages themselves are flawed. Languages are abstractions. Like any abstraction, we lost the details of the individuals to achieve a more abstract idea. For example, the word “red” is an abstraction of all the colors approximate the 625 nm - 740 nm range on the visible spectrum, or the hex code near #FF0000.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“The limits of my language means the limits of my world.” Ludwig Wittgenstein&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The benefit of abstraction is to convey ideas at a higher level. Having the concept of colors, we can spend our time talking freely about designs and poetry, at the two assumptions that:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;the lost details aren’t necessary, e.g., the exact wavelength or hex code, and,&lt;/li&gt;
&lt;li&gt;we both aware of the lost details.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;However, during any exchange of conversations, questions and misunderstandings usually lie in the very assumptions. We question the importance of the chosen words, i.e., “why did you say red, not coral?” And we examine the lost details, i.e., “did you mean red #FF0000 or red #ff4136?”&lt;/p&gt;
&lt;p&gt;The conversation goes on. We fill in the details and more specifics. Even though we didn’t get lost in the details, frustration still lingered at the end. “Does the other person know why I care so much about the hex code? Why he/she doesn’t seem to care as I did?” “Perhaps he/she will never get it.”&lt;/p&gt;
&lt;p&gt;I think words are a lousy medium to carry ideas. Though words are good enough to convey emotions, for all humans share the same: we love, we hate. Sometimes we feel happy and excited, and sometimes we feel anxious and depressed.&lt;/p&gt;
&lt;p&gt;We are all empathetic. This is common to all of us.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/entering-spring-lisp-game-jam-2021</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Entering Spring Lisp Game Jam 2021</title>
    <updated>2021-04-29T00:00:00Z</updated>
    <published>2021-04-29T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/entering-spring-lisp-game-jam-2021" type="text/html"/>
    <content type="html">&lt;p&gt;From the &lt;a href="https://itch.io/jam/spring-lisp-game-jam-2021"&gt;Spring Lisp Game Jam 2021&lt;/a&gt; site:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Lisp Game Jam is a bi-annual game jam taking place for a full 10 days. After the jam has finished, 3 days are given to everyone to try out the game submissions and vote for their favorites.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;My goal coming into this Game Jam was to finish a playable game. No matter how burnout I felt at the end, I was quite happy to finish the game using just my own free time. The game is quite enjoyable and fun (to me) in many aspects. I submitted my game after 8 days of jamming. You can play my game, Spirited, &lt;a href="https://dawranliou.itch.io/spirited"&gt;here on my itch.io page&lt;/a&gt;, or in the iframe below. If you just want to see the source code, it’s GPL-licensed on my &lt;a href="https://github.com/dawranliou/spirited/"&gt;Github&lt;/a&gt;.&lt;/p&gt;
&lt;iframe src="https://itch.io/embed-upload/3700249?color=140c1c" allowfullscreen width="640" height="380" frameborder="0"&gt;
&lt;a href="https://dawranliou.itch.io/spirited"&gt;Play Spirited on itch.io&lt;/a&gt;
&lt;/iframe&gt;
&lt;p&gt;The game was written in &lt;a href="https://fennel-lang.org/"&gt;Fennel&lt;/a&gt; on &lt;a href="https://tic80.com/"&gt;TIC-80&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Some lessons were learned:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;My Clojure experiences didn’t really matter.&lt;/li&gt;
&lt;li&gt;Making the tile set is a skill worth learning.&lt;/li&gt;
&lt;li&gt;Lua’s Coroutines is a great tool for game programming that I need to learn more for my next game jam.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Some unexpected were found:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;I had a lot more fun than I expected making the game’s soundtrack and SFX.&lt;/li&gt;
&lt;li&gt;I enjoyed a lot doing world building, story telling, and designing dialogues.&lt;/li&gt;
&lt;li&gt;There are a lot more stories I want to tell in the world of Spirited.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Some links were mentioned in this article:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/dawranliou/spirited/"&gt;The source code on Github&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dawranliou.itch.io/spirited"&gt;Spirited on itch.io&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://itch.io/jam/spring-lisp-game-jam-2021"&gt;Spring Lisp Game Jam 2021&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://fennel-lang.org/"&gt;Fennel Lisp&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://tic80.com/"&gt;TIC-80 fantasy console&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/interop-legacy-java-with-clojure</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Interop legacy Java project with Clojure</title>
    <updated>2019-01-31T00:00:00Z</updated>
    <published>2019-01-31T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/interop-legacy-java-with-clojure" type="text/html"/>
    <content type="html">&lt;p&gt;Recently I got the chance to work on a new feature for our existing Java project. The feature itself is a project that set out to be a general-purpose asynchronous data logging library that can be used company-wide, shared with other projects. I was very into Clojure these days. Learning Clojure has this side effect of mutating your brain to view programming difference. At the meanwhile changing your taste of choosing a programming language. (Please be Clojure!)&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;I want to do this project in Clojure because, first of all, it’s Clojure. And I can’t get more excited about this idea along. Then I did a couple of evaluation:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Clojure is a JVM language. It’s designed to be “symbiotic with an established Platform” (see &lt;a href="https://clojure.org/about/rationale"&gt;Rationale&lt;/a&gt;" so I know it’s doable to integrate two languages. I just need to figure out how. This is primarily what this blog post is about.&lt;/li&gt;
&lt;li&gt;Clojure has great concurrency supports. This is also a designed feature to the language. (Also see the rationale link above.) I need to develop APIs that are asynchronous to achieve high performance. And I’ve been thinking of digging into &lt;code&gt;core.async&lt;/code&gt; for some time.&lt;/li&gt;
&lt;li&gt;Our legacy code base really need some new blood and some strategies to split up the project. I think introducing a new language would be a way to draw a line from our current project and potentially for other future features.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And here we go.&lt;/p&gt;
&lt;h2 id="strategy-1---drop-in-clojure-uberjar"&gt;Strategy 1 - Drop-in Clojure Uberjar&lt;/h2&gt;
&lt;p&gt;Recipe: 1. Create a new Clojure project 1. Generate classes/interfaces by instrumenting Clojure 1. Create a uberjar 1. Drop in to existing Java project’s classpath 1. Use the generated classes/interfaces from Java project&lt;/p&gt;
&lt;p&gt;I call this one “air supplying” because, interestingly, our legacy Java project doesn’t use any modern build system like Maven or Gradle. (We use Ant instead.) So I simply copy the uberjar to the project’s classpath to make my compiled code available.&lt;/p&gt;
&lt;p&gt;Here, the goal is to generate the class files that a Java project can use. We start the project with &lt;code&gt;lein new app airsupply&lt;/code&gt;. The project.clj would look like this:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; project.clj
(defproject airsupply &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;FIXME: write description&amp;quot;
  :url &amp;quot;FIXME&amp;quot;
  :license {:name &amp;quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&amp;quot;
            :url &amp;quot;https://www.eclipse.org/legal/epl-2.0/&amp;quot;}
  :dependencies [[org.clojure/clojure &amp;quot;1.10.0&amp;quot;]]
  :main ^:skip-aot airsupply.core   ;; (1)
  :target-path &amp;quot;target/%s&amp;quot;
  :profiles {:uberjar {:aot :all}})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(1) We don’t really use the &lt;code&gt;airsupply.core&lt;/code&gt; ns and we don’t need a main since this isn’t going to be an app but a library. We can just remove the &lt;code&gt;:main&lt;/code&gt; line.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Naively, we’ll create a namespace called airsupply.java-api and use the &lt;code&gt;:gen-class&lt;/code&gt; directive in the &lt;code&gt;ns&lt;/code&gt; declaration to instrument Clojure to compile it. I recommend reading &lt;span class="citation" data-cites="kotarak"&gt;[@kotarak]&lt;/span&gt;(https://twitter.com/kotarak)’s &lt;a href="https://kotka.de/blog/2010/02/gen-class_how_it_works_and_how_to_use_it.html"&gt;gen-class – how it works and how to use it&lt;/a&gt; to know more about &lt;code&gt;gen-class&lt;/code&gt;. If you are still following, we ended up with:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; project.clj
(defproject airsupply &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;FIXME: write description&amp;quot;
  :url &amp;quot;FIXME&amp;quot;
  :license {:name &amp;quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&amp;quot;
            :url &amp;quot;https://www.eclipse.org/legal/epl-2.0/&amp;quot;}
  :dependencies [[org.clojure/clojure &amp;quot;1.10.0&amp;quot;]]
  :aot [airsupply.java-api]
  :target-path &amp;quot;target/%s&amp;quot;
  :profiles {:uberjar {:aot :all}})
  
;; src/airsupply/java_api.clj
(ns airsupply.java-api
  (:gen-class
   :name airsupply.Airsupply
   :state state
   :init init
   :constructors {[] []
                  [String] []}
   :main false
   :methods [[drop [] String]]))

(defn -init
  ([] (-init &amp;quot;supply&amp;quot;))
  ([name] [[] {:name name}]))

(defn -drop
  [this]
  (def -this this)
  (-&amp;gt; this .state :name))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now you can launch the repl and do:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;user&amp;gt; (def a (airsupply.Airsupply.))
#&amp;#39;user/a
user&amp;gt; (.drop a)
&amp;quot;supply&amp;quot;
user&amp;gt; (def a (airsupply.Airsupply. &amp;quot;food&amp;quot;))
#&amp;#39;user/a
user&amp;gt; (.drop a)
&amp;quot;food&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Packaging everything up is one command away: &lt;code&gt;lein uberjar&lt;/code&gt;. You should find the &lt;code&gt;target/uberjar/airsupply-0.1.0-SNAPSHOT&lt;/code&gt; contain everything including Clojure itself. Simply adding this jar to your Java project and you can import &lt;code&gt;airsupply.Airsupply&lt;/code&gt; normally.&lt;/p&gt;
&lt;p&gt;However, here’s the catch: it’s quite difficult to use &lt;code&gt;:gen-class&lt;/code&gt; when the custom methods get more creative, e.g. returning an instance of the class itself like &lt;code&gt;clone&lt;/code&gt; does. The compiler wouldn’t be able to understand &lt;code&gt;airsupply.Airsupply&lt;/code&gt; before compiling it.&lt;/p&gt;
&lt;p&gt;Although the &lt;a href="https://stackoverflow.com/a/29375133/5050657"&gt;StackOverflow has an answer&lt;/a&gt; on this, my opinion is to define an common interface first (either using &lt;code&gt;gen-interface&lt;/code&gt; or just write a Java interface.) Then Airsupply can simply implement the interface instead of defining the custom methods all by itself.&lt;/p&gt;
&lt;p&gt;My recommendation is to turn this into a polyglot project - Java interface and Clojure implementation. Leiningen has this use case support pretty well. I took the &lt;a href="https://github.com/technomancy/leiningen/blob/master/doc/MIXED_PROJECTS.md#source-layout"&gt;official recommendation&lt;/a&gt; and here’s the result. (Note that the layout has changed.):&lt;/p&gt;
&lt;pre class="java"&gt;&lt;code&gt;// src/java/airsupply/Supply.java
package airsupply;

public interface Supply {
    public String drop();
    public Supply spawn();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; project.clj
(defproject airsupply &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;FIXME: write description&amp;quot;
  :url &amp;quot;FIXME&amp;quot;
  :license {:name &amp;quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&amp;quot;
            :url &amp;quot;https://www.eclipse.org/legal/epl-2.0/&amp;quot;}
  :dependencies [[org.clojure/clojure &amp;quot;1.10.0&amp;quot;]]
  :aot [airsupply.java-api]
  :source-paths [&amp;quot;src/clojure&amp;quot;]  ;; (2)
  :java-source-paths [&amp;quot;src/java&amp;quot;]  ;; (3)
  :target-path &amp;quot;target/%s&amp;quot;
  :profiles {:uberjar {:aot :all}})

;; src/clojure/airsupply/java_api.clj
(ns airsupply.java-api
  (:gen-class
   :name airsupply.Airsupply
   :implements [airsupply.Supply]
   :state state
   :init init
   :constructors {[] []
                  [String] []}
   :main false))

(defn -init
  ([] (-init &amp;quot;supply&amp;quot;))
  ([name] [[] {:name name}]))

(defn -drop
  [this]
  (-&amp;gt; this .state :name))

(defn -spawn
  [this]
  (airsupply.Airsupply. (-&amp;gt; this .state :name)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(2) (3) are added for our polyglot project.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;After restarting the repl, Leiningen would know to compile the Java source first and then the Clojure ns that’s in the :aot directive. This default behavior is exactly what we need in the use case. There are other ways to interleaving compilation steps but we’re good so far. Here’s what you can try in the repl after restarting.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;user&amp;gt; (def food (airsupply.Airsupply. &amp;quot;food&amp;quot;))
#&amp;#39;user/food
user&amp;gt; (.drop food)
&amp;quot;food&amp;quot;
user&amp;gt; (def food-2 (.spawn food))
#&amp;#39;user/food-2
user&amp;gt; (.drop food-2)
&amp;quot;food&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you don’t see the class instance working as expected, try a &lt;code&gt;lein clean&lt;/code&gt; to clean up the class files. I don’t exactly know why this has to be done but it helps.&lt;/p&gt;
&lt;p&gt;Once you do a &lt;code&gt;lein uberjar&lt;/code&gt; and drop this into the classpath of your legacy Java project, you can simply import the class/interface and create the object like you normally do, for example:&lt;/p&gt;
&lt;pre class="java"&gt;&lt;code&gt;// import airsupply.Supply;
// import airsupply.Airsupply;

Supply foodSupply = new Airsupply(&amp;quot;food&amp;quot;);
System.out.println(foodSupply.drop());
Supply anotherFoodSupply = foodSupply.spawn();
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="strategy-2---use-legacy-java-jar-as-resource"&gt;Strategy 2 - Use Legacy Java Jar as resource&lt;/h2&gt;
&lt;p&gt;Recipe 1. Compile the legacy Java App (preferrably to a Jar) 1. Add the Jar to project.clj’s resource 1. Use the Jar in Clojure 1. Create a uberjar if we need to use the Clojure library back in the java app&lt;/p&gt;
&lt;p&gt;In this strategy, we want to pull in some dependencies from the Legacy Java app. I found it the easiest just drop in the entire legacy project as a Jar into the Clojure project like:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; project.clj
(defproject airsupply &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;FIXME: write description&amp;quot;
  :url &amp;quot;FIXME&amp;quot;
  :license {:name &amp;quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&amp;quot;
            :url &amp;quot;https://www.eclipse.org/legal/epl-2.0/&amp;quot;}
  :dependencies [[org.clojure/clojure &amp;quot;1.10.0&amp;quot;]]
  :aot [airsupply.java-api]
  :source-paths [&amp;quot;src/clojure&amp;quot;]
  :java-source-paths [&amp;quot;src/java&amp;quot;]
  :target-path &amp;quot;target/%s&amp;quot;
  :profiles {:uberjar {:aot :all}
             :dev     {:aot            [airsupply.java-api]  ;; (4)
                       :resource-paths [&amp;quot;lib/legacy-999.0.0.jar&amp;quot;]}}) ;; (5)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(4) Use the :dev profile for isolation. Also note that the :aot is moved here.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(5) Put the legacy java project jar under the lib directory.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;This way the you can develop the Clojure project that depends on some of the existing Java project.&lt;/p&gt;
&lt;h2 id="strategy-3---connect-clojure-repl-with-java-jvm"&gt;Strategy 3 - Connect Clojure repl with Java JVM&lt;/h2&gt;
&lt;p&gt;Recipe:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Drop-in the uberjar containing Clojure, nrepl, and all other dependencies&lt;/li&gt;
&lt;li&gt;Start the nrepl server in the Java app&lt;/li&gt;
&lt;li&gt;Connect the nrepl&lt;/li&gt;
&lt;li&gt;Access everything in the legacy Java’s JVM&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This one is really amazing. REPL has been the most important part for me to do development in Clojure. With REPL-driven development, you can get immediate feed back about the code change and, best, not loosing the application state in the process.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;I took the inspiration from Gert-Jan van de Streek’s &lt;a href="https://www.avisi.nl/blog/2015/05/18/how-to-inspect-a-legacy-java-application-with-the-clojure-repl"&gt;How to inspect a legacy Java application with the Clojure REPL&lt;/a&gt;. I also use the code example in the post.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We need to make some change to the &lt;code&gt;project.clj&lt;/code&gt; to include the &lt;a href="https://github.com/clojure/tools.nrepl"&gt;&lt;code&gt;nrepl&lt;/code&gt;&lt;/a&gt; first:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; project.clj
(defproject airsupply &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  :description &amp;quot;FIXME: write description&amp;quot;
  :url &amp;quot;FIXME&amp;quot;
  :license {:name &amp;quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&amp;quot;
            :url &amp;quot;https://www.eclipse.org/legal/epl-2.0/&amp;quot;}
  :dependencies [[org.clojure/clojure &amp;quot;1.10.0&amp;quot;]
                 [org.clojure/tools.nrepl &amp;quot;0.2.13&amp;quot;]]]  ;; (6)
  :aot [airsupply.java-api]
  :source-paths [&amp;quot;src/clojure&amp;quot;]
  :java-source-paths [&amp;quot;src/java&amp;quot;]
  :target-path &amp;quot;target/%s&amp;quot;
  :profiles {:uberjar {:aot :all}
             :dev     {:aot            [airsupply.java-api]
                       :resource-paths [&amp;quot;lib/legacy-999.0.0.jar&amp;quot;]}})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(6) Add &lt;code&gt;org.clojure/tools.nrepl&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Then we need to sprinkle some Java in the legacy project to make magic happen:&lt;/p&gt;
&lt;pre class="java"&gt;&lt;code&gt;// legacy java project&amp;#39;s main class
package legacy.code;

import clojure.java.api.Clojure;
import clojure.lang.IFn;

public class App {

    public static void main(String[] args) {
      IFn require = Clojure.var(&amp;quot;clojure.core&amp;quot;, &amp;quot;require&amp;quot;);
      require.invoke(Clojure.read(&amp;quot;clojure.tools.nrepl.server&amp;quot;));
      
      IFn server = Clojure.var(&amp;quot;clojure.tools.nrepl.server&amp;quot;, &amp;quot;start-server&amp;quot;);
      server.invoke(Clojure.read(&amp;quot;:port&amp;quot;), Clojure.read(&amp;quot;8888&amp;quot;));  // (7)
      
      // the rest of the main
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(7) I like to set a determinstic nrepl port but you can also skip this like Gert-Jan van de Streek’s article&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;With the code snippet, we effectively launched a Clojure nrepl inside the legacy app’s JVM, at runtime. Start the application. Now you can connect to the nrepl from the Clojure project to access the application runtime by &lt;code&gt;lein repl :connect 8888&lt;/code&gt; (or from any IDE integration tool.)&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;I really like the way how Clojure is “symbiotic” with JVM. Injecting some new blood into a legacy project usually isn’t easy, but I’m glad to take the initiative to set on this journey. I must say I actually felt quite confident when I worked on the technical issues along the way, even though I was still learning Clojure. It’s amazing to see things just work like I want it to in the end.&lt;/p&gt;
&lt;p&gt;This post hows you 3 strategies that I came across to help you integrate Clojure into your Java project. Hope it helps you to overcome some technical issues faster then I did! The strategies are:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Drop-in Clojure Uberjar&lt;/li&gt;
&lt;li&gt;Use Legacy Java Jar as resource&lt;/li&gt;
&lt;li&gt;Connect Clojure repl with Java JVM&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="action"&gt;Action&lt;/h2&gt;
&lt;p&gt;If you have a Java codebase why not give this article a try and start integrating Clojure?&lt;/p&gt;
&lt;p&gt;&lt;a href="https://twitter.com/home?status=%22Interop%20legacy%20Java%20project%20with%20Clojure%22%20by%20%40dawranliou.%20https://dawranliou.com/interop-legacy-java-with-clojure.html"&gt;Share this article if you like it!&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/twitter-scraper-1</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Twitter scraper tutorial with Python: Requests, BeautifulSoup, and Selenium - Part 1</title>
    <updated>2016-03-26T00:00:00Z</updated>
    <published>2016-03-26T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/twitter-scraper-1" type="text/html"/>
    <content type="html">&lt;p&gt;Inspired by Bruce, my friend’s take-home interview question, I started this bite-size project to play around with some of the most popular PyPI packages: Requests, BeautifulSoup, and Selenium. In this tutorial, I’ll show you the step-by-step process of how I build a Twitter Search web scraper without using their REST API.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;em&gt;“Well, why not use their API?”&lt;/em&gt; you might ask. I have two reasons:&lt;/p&gt;
&lt;p&gt;Not all the websites expose REST APIs to clients. In order to retrieve data from those websites in a programmatic way, it’s good to know how to do web scrapping.&lt;/p&gt;
&lt;p&gt;To use Twitter’s APIs, you’ll need OAuth to authenticate your application. I was just too lazy to figure that out at the time. (Yeah, I’ll figure it out and post another tutorial on that.)&lt;/p&gt;
&lt;p&gt;Here we go! Fire up your favorite browser and go to the url: https://twitter.com/search-home. You’ll see a text box in the middle. That’s where we begin. Try typing in something that you want to search and see what happens. For me, I want to search for all tweets from my twitter account, &lt;span class="citation" data-cites="dawranliou"&gt;@dawranliou&lt;/span&gt;. So I typed it in and hit enter.&lt;/p&gt;
&lt;figure&gt;
&lt;img src="/images/twitter-search-landing-page.png" alt="alt twitter-search-landing-page" /&gt;&lt;figcaption aria-hidden="true"&gt;alt twitter-search-landing-page&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;In the next page, you can see a list of tweets. Let’s make our first note here: what’s the current url? For my search results, it is https://twitter.com/search?q=%40dawranliou. This url is important since the python application we are writing will need it to retrieve the same data we are viewing on the browser now.&lt;/p&gt;
&lt;p&gt;Second, open your developer tool. For me, I use Chrome browser on my Mac so I hit “command-alt-I”. Here’s where a little bit detective in you and me need to come into play. What we are looking for is some hints indicating the tweets that we see on the browser. Later on we could use those hints in the code to find the information we need in a programmatic way. Let’s take a look…&lt;/p&gt;
&lt;figure&gt;
&lt;img src="/images/chrome-developer-tool.png" alt="alt chrome-developer-tool" /&gt;&lt;figcaption aria-hidden="true"&gt;alt chrome-developer-tool&lt;/figcaption&gt;
&lt;/figure&gt;
Actually, Chrome dev tool has a very handy feature to let you inspect the component you see on the browser and highlight the corresponding html element. So what I did was to highlight the tweet content in the browser as the picture below. It shows that the content is using a
&lt;p&gt;
&lt;p&gt;tag and it has the class attributes of “TweetTextSize”, “js-tweet-text”, and “tweet-text.”&lt;/p&gt;
&lt;figure&gt;
&lt;img src="/images/inspection-tool.png" alt="alt inspection-tool" /&gt;&lt;figcaption aria-hidden="true"&gt;alt inspection-tool&lt;/figcaption&gt;
&lt;/figure&gt;
My guss is that all the tweet contents use the same
&lt;p&gt;
&lt;p&gt;tag and the same class attributes. You can verify it by inspect more tweets. Bingo, this is what we need. Let’s get down to the code:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;import requests
from bs4 import BeautifulSoup

url = u&amp;#39;https://twitter.com/search&amp;quot;q=&amp;#39;
query = u&amp;#39;%40dawranliou&amp;#39;

r = requests.get(url+query)
soup = BeautifulSoup(r.text, &amp;#39;html.parser&amp;#39;)

tweets = [p.textfor p in soup.findAll(&amp;#39;p&amp;#39;, class_=&amp;#39;tweet-text&amp;#39;)]

print(tweets)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Boom! Easy huh? Two packages I use are: 1. Requests: it makes sending HTTP requests super easy 1. BeautifulSoup: it makes parsing html super easy. And I love the name :)&lt;/p&gt;
&lt;p&gt;The code is very self-explainatory. Let’s run it!&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;python3 twitter-search.py
[]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What… why? Empty list? That doesn’t make sense. Let’s not panic. Keep calm and open the python interactive mode to see what’s going on in the code.&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;python3 -i twitter-search.py
[]
&amp;gt;&amp;gt;&amp;gt; f = open(&amp;#39;search.html&amp;#39;, &amp;#39;w&amp;#39;)
&amp;gt;&amp;gt;&amp;gt; f.write(r.text)
97075&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here I output the response to our HTTP request to a file. Locate the file and open it up with your browser.&lt;/p&gt;
&lt;p&gt;I do not see the tweets this time. So what’s happening here is that the web application design is very sophisticated that the tweet search results aren’t loaded, YET, when the HTTP response is back from the server. Instead, those tweets were loaded asynchronously using AJAX (stands for Asynchronous JavaScript and XML) calls. With this design, the website could be loaded up very light-weighted at the beginning. As the user scrolls down the page, more contents will be loaded without the need of refreshing the page. This design is called Infinite Scrolling.&lt;/p&gt;
&lt;p&gt;In part 2, I’ll show you how to use Selenium, another very popular PyPI package, to scrape the infinite scrolling page. Stay tuned!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/code-quality-cost</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>The Cost of Code Quality</title>
    <updated>2024-03-01T00:00:00Z</updated>
    <published>2024-03-01T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/code-quality-cost" type="text/html"/>
    <content type="html">&lt;p&gt;I recently came across &lt;a href="https://www.taoensso.com/"&gt;Peter Taoussanis&lt;/a&gt;'s London Clojurians talk - &lt;a href="https://www.youtube.com/watch?v=Jz9NcnQbH5I"&gt;Some controversial truths&lt;/a&gt;, resonated with me a lot. It's funny that I wouldn't be ready for this talk two years ago (and I'd probably dismissed the ideas immediately and called it heresy). As I spent more and more time in the software industry, I'm finally ready for this talk. Similar ideas had been brewing in my mind for the past few years. I want to touch on code quality more with my experiences.&lt;/p&gt;
&lt;p&gt;In his talk, Peter argues that quality doesn't always matter (a statement I would have frowned upon years ago), and I fully agree.&lt;/p&gt;
&lt;p&gt;At work, I had always tried to produce the best code I could and meticulously write documentation/commit messages as thoroughly as possible. "What if someone wants to extend this function? Can I anticipate it and make it easier to change in the future?" "What if someone checked the commit message and wants to learn why we changed this line?" "What if no one else is around in ten years, and someone needs to learn from the documentation?"&lt;/p&gt;
&lt;p&gt;On the other hand, my old colleague Jeff is almost the polar opposite of my working style. He was best described as a one-person army, delivering high-value features at speed while helping the organization tremendously by aligning the product visions. He tended to submit large quantities of messy code in bursts that were impossible for me to review. I used to self-righteously argue against his coding practice. Gradually, I started seeing the bigger picture - judging Jeff's work solely based on the quality wasn't fair. His time and energy have better impacts elsewhere. The opportunity costs were far greater than the value of the additional code quality I complained about.&lt;/p&gt;
&lt;p&gt;Quality is another decision that comes with its tradeoffs. Sometimes, the opportunity costs could be as little as causing a bug in an edge case that no real-life users will ever hit; sometimes, as significant as losing business to competitors, or even worse - going out of business. Similar to what I learned from participating in Game Jams - I could either submit finished games with crapy code or submit crapy unfinished games with beautiful code. (I chose the former for all my past three Game Jams.) The opportunity costs of perfecting code quality were just too high (that it would've impacted the delivery of a playable game).&lt;/p&gt;
&lt;p&gt;Similarly, about code reviews (which is also a typical part of ensuring code quality), there are times to review code meticulously because the efforts and social energies are well justified - perhaps you are onboarding new people, or maybe you are aligning on an architectural decision that is hard to reverse. Yet, there are times to strategically let code quality slides when that gives you something better in return.&lt;/p&gt;
&lt;p&gt;Lastly, I love this quote I learned from Peter's talk:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Any idiot can build a bridge that stands, but it takes an engineer to build a bridge that barely stands.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Being biased heavily on the code quality side for most of my career, I often need to remind myself to set aside my programmer's pride and look at the bigger picture. To end this on a more optimistic note, as I gained more experiences, the quality of work does come more easily. (With the help of Emacs and &lt;code class="verbatim"&gt;magit&lt;/code&gt;, of course!)&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/flask-for-new-dev</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Flask for New Web Developer</title>
    <updated>2016-02-18T00:00:00Z</updated>
    <published>2016-02-18T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/flask-for-new-dev" type="text/html"/>
    <content type="html">&lt;p&gt;Last long weekend after my geek marathon I finally finished reading &lt;a href="http://www.amazon.com/Flask-Web-Development-Developing-Applications/dp/1449372627"&gt;Flask Web Development: Developing Web Applications with Python&lt;/a&gt; and deployed my blog app on Heroku. It was such rewarding to see my web app running online, not only as a novice web application developer but also as a adventurer to this whole new world of DevOps. In this article I want to share some thoughts mostly about Flask — the Python framework for web developing — , and covers a little about what I’d recommend a beginner to start building web apps, and a little bit about the book.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;BTW, here’s the link to my blog: https://dawranliou.com/blog&lt;/p&gt;
&lt;h1 id="flask"&gt;Flask&lt;/h1&gt;
&lt;p&gt;&lt;em&gt;Okay, why Flask? There are tons of web frameworks out there, why Flask?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Just like starting learning a new programming language, you’ll find all kinds of people debating and all kinds of opinions about what’s best for you. But the truth is, &lt;em&gt;I don’t know what I don’t know!&lt;/em&gt; Have you ever had the experience jumping into a late class and got so lost that you had not a single clue where to start asking questions? This was because you don’t have the background knowledge to ask the right question, yet. Yeah, that was my first contact with web development.&lt;/p&gt;
&lt;p&gt;Here’s my suggestion: if you are in the same situation as I did, &lt;strong&gt;go pick the framework that has the coolest icon among those most popular frameworks.&lt;/strong&gt; Sounds ridiculous, isn’t it? Not entirely. Hear me out: the reason those frameworks are popular is because they serve the general purpose of web development well and they are very well-documented. What you need in your situation is a learning tool that ramps up your knowledge and skills to a degree so you can drive along the way. Not fine tuning your product to fit a specific need. Once you are on the way, I’d say it’ll be easy to change lanes to other framework because now you know the right questions to ask even before starting.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“A question well asked is half answered.” — Charles Kettering.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So stop worrying about choosing the first framework and just choose one. You’ll know how to make the right choice along the way. What about the coolest icon thing? Oh, that’s just some none-sense but something I tend to do a lot. I’m a very visual learner and I got motivated to see pretty images. &lt;strong&gt;After all, motivation and perseverance are the two things you’ll need.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you still can’t make up your mind after all the stuffs I talked above, here’s the ultimatum: choose Flask! I have to admit that I’m biased, since I have no other web developing experience with other frameworks, but I hope to convince you in the next section.&lt;/p&gt;
&lt;h1 id="flask-as-a-learning-tool"&gt;Flask as a learning tool&lt;/h1&gt;
&lt;p&gt;I’ve learned some great properties in Flask as a learning tool along my journey.&lt;/p&gt;
&lt;h2 id="starting-small"&gt;Starting Small&lt;/h2&gt;
&lt;p&gt;The first thing you know about Flask is — “&lt;strong&gt;&lt;em&gt;Flask is a microframework for Python…&lt;/em&gt;&lt;/strong&gt;”. Flask is designed to be extended. The core of the framework only provide the bare minimum functionality for you to build a web application. I found this to be very different from the famous “battery-included” philosophy for Python the language itself. But WTH. This is the best part of Flask in my opinion.&lt;/p&gt;
&lt;p&gt;Take a User Login feature for example. The scope could differ by a hundred miles based on the user story. One user story could only need one admin login account; another could be a social networking site allowing login with their Twitter accounts. Flask does not make any assumption of it. In the official tutorial — &lt;a href="http://flask.pocoo.org/docs/0.10/tutorial/introduction/"&gt;Flaskr&lt;/a&gt;, it simply hard coded one set of username and password in the app and that’s it! No database nor SQL code needed for user sign-in. &lt;em&gt;(Here I’m just giving an example. In the tutorial it actually shows you how to create a database for the blog posts. However, there isn’t any restriction if you are going to save all the blog posts into one gigantic text file and retrieve it later.)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;This is great news for a beginner like I was! Instead of learning a rich set of features provided in the framework, I can focus on the minimum set of building an app, and later on, if I need to extend the feature, I can always look out for PyPI packages that serves my need. This leads to my second point— the extensiblility&lt;/p&gt;
&lt;h2 id="extensibility"&gt;Extensibility&lt;/h2&gt;
&lt;p&gt;Because Flask does not make any assumption about anything (besides that you are building a web app of course, stop being picky!), once you acquire the basic knowledge, it’s easy to extend it from there with Flask. Take the User Login feature again for example, if you are looking for a Twitter account login feature, you’ll be able to find several PyPI packages to support it like Flask-OAuth, or Flask-Social (or you can implement it yourself.) Also, you can include the Flask-Login package to deal with the login session for you and have all kinds of goodies to make your code cleaner.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(Note: There are a great community support for Flask extensions and lots of them are great! I won’t talk about those in this article though.)&lt;/em&gt;&lt;/p&gt;
&lt;h2 id="popularity"&gt;Popularity&lt;/h2&gt;
&lt;p&gt;Unarguably Flask is one of the most popular web frameworks. &lt;strong&gt;With great popularity comes great community.&lt;/strong&gt; There are lots of great articles, online tutorials, and resources in all sorts of forms on the Internet. So, in the end if you are not using Flask, be my guest to use any of the popular frameworks out there.&lt;/p&gt;
&lt;h1 id="how-i-learned-in-the-hard-way"&gt;How I learned in the hard way&lt;/h1&gt;
&lt;p&gt;It’s such a long route for me to learn web development now think of it. What I used to do was to read a lot of online tutorials and code along the way. I’ve always been more of a maker than a thinker. I am the kid who always love to get hands dirty before the teacher said go. However, I somehow failed with this approach when I first learning about web developing. The information in the articles or video tutorials I found weren’t sufficient enough to ramp up my speed to where I can cruise for myself even for a short while. I got confused a lot and didn’t know what was missing out.&lt;/p&gt;
&lt;p&gt;Stumbling myself for a few while, finally I decide to consult to the books. Sounds like old-school but it was my savior. The book turned out to fit my needs very well — it is leading you to build a real world application in a very systematic way while introduces you different components of web development. This is what makes all the difference. Eventually I was able to gain the knowledge in each web components and having fun coding along with it. If anyone ask me to recommend a book about Flask, this is it.&lt;/p&gt;
&lt;p&gt;This approach won’t be suitable for everyone. But if you happen to face the difficulty to get into the web development, reading books might be an option.&lt;/p&gt;
&lt;p&gt;There’s only one thing I wished the book to tell me more — deployment. I think the last mile in the book was the longest part. Anyways, the book isn’t about DevOps after all.&lt;/p&gt;
&lt;h1 id="final-words"&gt;Final Words&lt;/h1&gt;
&lt;p&gt;I am sharing my thoughts not because I know a lot about this topic. On the contrary, I am sharing because I am just some dude who knows a little more than a beginner, and I want to help my fellow beginners to get out of the troubles I had. At least I’m not too far from where beginners stand. My memory is still quite fresh and relevant.&lt;/p&gt;
&lt;p&gt;I also plan to write a series of Flask tutorials in the future. Stay tuned!&lt;/p&gt;
&lt;p&gt;Hope you find this article useful for you, even just for a little. I appreciate any comments or feedback. Feel free to reach me on Twitter &lt;span class="citation" data-cites="dawranliou"&gt;@dawranliou&lt;/span&gt; or below in the comment section. Cheers!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/rethink-syntax-highlighting</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Rethink Syntax Highlighting</title>
    <updated>2020-11-06T00:00:00Z</updated>
    <published>2020-11-06T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/rethink-syntax-highlighting" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;Update 2021-02-28: My color themes are now &lt;a href="https://github.com/dawranliou/sketch-themes"&gt;released&lt;/a&gt;! Check it out!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="/images/sketch-theme-white.png" alt="My light editor theme" /&gt; &lt;em&gt;A screenshot of my current editor theme - sketch-white&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I’m a minimalist when it comes to how I like to highlight my code - my code editor is usually almost monochromatic, just black, white, three shades of gray, and an accent color like orange. If those colors sounds a lot to you, I have to assume you either are an extreme minimalist in code highlighting or you’ve never give code highlighting a second thought and just use whatever the theme creators throws at you. If you are the latter, this post is for you.&lt;/p&gt;
&lt;p&gt;&lt;img src="/images/sketch-theme-black.png" alt="My dark editor theme" /&gt; &lt;em&gt;A screenshot of my alternative editor theme - sketch-black&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We live in a world of distractions. Everything is constantly trying to grab your attentions, your text messages, phone notifications, emails, social medias, ads, also your friends and families. It is because: your attentions are, indeed, valuable. We too often got distracted, not because we are bad at focusing, (maybe some of us are), but more importantly, the world around us is constantly demanding our attentions. When everything’s in focus, nothing actually is. When everything are signals, every one becomes a noise.&lt;/p&gt;
&lt;p&gt;Same as your code syntax highlighting. When every single text is highlighted with different colors, they are all just distractions and noises. Take a look at the &lt;a href="https://github.com/tonsky/vscode-theme-alabaster#motivation"&gt;Alabaster theme&lt;/a&gt; by &lt;a href="https://tonsky.me/"&gt;tonsky&lt;/a&gt;:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://raw.githubusercontent.com/tonsky/vscode-theme-alabaster/master/screenshot.png" alt="Alabaster theme screenshot" /&gt; &lt;em&gt;A screenshot of alabaster theme&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I like how the motivations describes:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Most color themes highlight everything they can, ending up looking like a fireworks show. Instead, Alabaster uses minimal highlighting; it defines just four classes: * Strings * All statically known constants (numbers, symbols, keywords, boolean values) * Comments * Global definitions&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This makes a lot of sense to me. The reason that we even need syntax highlighting to begin with is because we, the programmers rather than the machines, need to parse the text differently when we read it. For example, we don’t even need to parse the comments when reading code. Strings are in a sense very similar to code comments. Strings are usually for the end users, not the programmers. When I saw a string in code, I usually just skim through it and make a mental note that “there’s a string here.”&lt;/p&gt;
&lt;p&gt;Personally I don’t like to highlight numbers, symbols, and keywords in code because those to me are just parts of the code. I don’t want them to stand out too much because I still need to read them. I don’t need additional visual aids to help me understand they are different from the rest of the code. There used to be a time that I embolden the keywords and highlight the global definitions, but now I’ve made a conscious decision that leaving keywords unstyled works better for me. I do have global definitions embolden because I like them to stand out a little more.&lt;/p&gt;
&lt;p&gt;How I like to highlight my code aligns with how I think about code. Your mileage might vary. But remember this: less is more. The less colors you use will have greater impacts. Have some thoughts about your syntax highlighting. How do they help you in your work flow? Do you really need all the colors to help you program? It’s pretty easy to customize color themes and syntax highlighting for pretty much all the major code editors. Try building your own color theme if necessary.&lt;/p&gt;
&lt;p&gt;Cheers!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/python36-descriptors</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Writing descriptors in Python 3.6+</title>
    <updated>2017-09-23T00:00:00Z</updated>
    <published>2017-09-23T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/python36-descriptors" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;Special thanks to &lt;a href="https://twitter.com/ramalhoorg"&gt;Luciano Ramalho&lt;/a&gt;. I learned most of the knowledge about descriptors from his workshop in PyBay 2017&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Have you seen this code or maybe have written code like this?&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;from sqlalchemy import Column, Integer, String
class User(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code snippet partially comes from the tutorial of a popular ORM package called &lt;a href="http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping"&gt;SQLAlchemy&lt;/a&gt;. If you ever wonder why the attributes &lt;code&gt;id&lt;/code&gt; and &lt;code&gt;name&lt;/code&gt; aren’t passed into the &lt;code&gt;__init__&lt;/code&gt; method and bind to the instance like &lt;a href="https://docs.python.org/3/tutorial/classes.html#class-objects"&gt;regular class does&lt;/a&gt;. , this post is for you.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;This post starts with explaining descriptors, why to use them, how to write them in previous Python versions (&amp;lt;= 3.5,) and finally writing them in Python 3.6 with the new feature described in &lt;a href="https://www.python.org/dev/peps/pep-0487/"&gt;PEP 487 – Simpler customisation of class creation&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If you are in a hurry or you just want to know what’s new, scroll all the way down to the bottom of this article. You’ll find the whole code.&lt;/p&gt;
&lt;h1 id="what-are-descriptors"&gt;What are descriptors&lt;/h1&gt;
&lt;p&gt;A great definition of descriptor is explained by Raymond Hettinger in &lt;a href="https://docs.python.org/3.6/howto/descriptor.html#definition-and-introduction"&gt;Descriptor HowTo Guide&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol. Those methods are __get__(), __set__(), and __delete__(). If any of those methods are defined for an object, it is said to be a descriptor.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There are three ways to access an attribute. Let’s say we have the &lt;code&gt;a&lt;/code&gt; attribute on the object &lt;code&gt;obj&lt;/code&gt;:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;To lookup its value, &lt;code&gt;some_variable = obj.a&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;To change its value, &lt;code&gt;obj.a = 'new value'&lt;/code&gt;, or&lt;/li&gt;
&lt;li&gt;To delete it, &lt;code&gt;del obj.a&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Python is dynamic and flexible to allow users intercept the above expression/statement and bind behaviors to them.&lt;/p&gt;
&lt;h1 id="why-you-want-to-use-descriptors"&gt;Why you want to use descriptors&lt;/h1&gt;
&lt;p&gt;Let’s see an example:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class Order:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity

    def total(self):
        return self.price * self.quantity

apple_order = Order(&amp;#39;apple&amp;#39;, 1, 10)
apple_order.total()
# 10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Despite the lack of proper documentation, there is a bug:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;apple_order.quantity = -10
apple_order.total
# -10, too good of a deal!&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead of using getter and setter methods and break the APIs, let’s use property to enforce &lt;code&gt;quantity&lt;/code&gt; be positive:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class Order:
    def __init__(self, name, price, quantity):
        self._name = name
        self.price = price
        self._quantity = quantity  # (1)

    @property
    def quantity(self):
        return self._quantity

    @quantity.setter
    def quantity(self, value):
        if value &amp;lt; 0:
            raise ValueError(&amp;#39;Cannot be negative.&amp;#39;)
        self._quantity = value  # (2)
    ...

apple_order.quantity = -10
# ValueError: Cannot be negative&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We transformed &lt;code&gt;quantity&lt;/code&gt; from a simple attribute to a non-negative property. Notice line &lt;code&gt;(1)&lt;/code&gt; that the attribute are renamed to &lt;code&gt;_quantity&lt;/code&gt; to avoid line &lt;code&gt;(2)&lt;/code&gt; getting a &lt;code&gt;RecursionError&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Are we done? Hell no. We forgot about the &lt;code&gt;price&lt;/code&gt; attribute cannot be negative neither. It might be attempting to just create another property for &lt;code&gt;price&lt;/code&gt;, but remember the DRY principle: when you find yourself doing the same thing twice, it’s a good sign to extract the reusable code. Also, in our example, there might be more attributes need to be added into this class in the future. Repeating the code isn’t fun for the writer or the reader. Let’s see how to use descriptors to help us.&lt;/p&gt;
&lt;h1 id="how-to-write-descriptors"&gt;How to write descriptors&lt;/h1&gt;
&lt;p&gt;With the descriptors in place, our new class definition would become:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class Order:
    price = NonNegative(&amp;#39;price&amp;#39;)  # (3)
    quantity = NonNegative(&amp;#39;quantity&amp;#39;)

    def __init__(self, name, price, quantity):
        self._name = name
        self.price = price
        self.quantity = quantity

    def total(self):
        return self.price * self.quantity

apple_order = Order(&amp;#39;apple&amp;#39;, 1, 10)
apple_order.total()
# 10
apple_order.price = -10
# ValueError: Cannot be negative
apple_order.quantity = -10
# ValueError: Cannot be negative&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice the class attributes defined before the &lt;code&gt;__init__&lt;/code&gt; method? It’s a lot like the SQLAlchemy example showed on the very beginning of this post. This is where we are heading. We need to define the &lt;code&gt;NonNegative&lt;/code&gt; class and implement the descriptor protocols. Here’s how:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class NonNegative:
    def __init__(self, name):
        self.name = name  # (4)
    def __get__(self, instance, owner):
        return instance.__dict__[self.name]  # (5)
    def __set__(self, instance, value):
        if value &amp;lt; 0:
            raise ValueError(&amp;#39;Cannot be negative.&amp;#39;)
        instance.__dict__[self.name] = value  # (6)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Line &lt;code&gt;(4)&lt;/code&gt;: the &lt;code&gt;name&lt;/code&gt; attribute is needed because when the &lt;code&gt;NonNegative&lt;/code&gt; object is created on line &lt;code&gt;(3)&lt;/code&gt;, the assignment to attribute named &lt;code&gt;price&lt;/code&gt; hasn’t happen yet. Thus, we need to explicitly pass the name &lt;code&gt;price&lt;/code&gt; to the initializer of the object to use as the key for the instance’s &lt;code&gt;__dict__&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Later, we’ll see how in Python 3.6+ we can avoid the redundancy.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;The redundancy could be avoid in earlier versions of Python, but I think this would take too much effort to explain and is not the purpose of this post. Thus, not included.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Line &lt;code&gt;(5)&lt;/code&gt; and &lt;code&gt;(6)&lt;/code&gt;: instead of using builtin function &lt;code&gt;getattr&lt;/code&gt; and &lt;code&gt;setattr&lt;/code&gt;, we need to reach into the &lt;code&gt;__dict__&lt;/code&gt; object directly, because the builtins would be intercepted by the descriptor protocols too and cause the &lt;code&gt;RecursionError&lt;/code&gt;.&lt;/p&gt;
&lt;h1 id="welcome-to-python-3.6"&gt;Welcome to Python 3.6+&lt;/h1&gt;
&lt;p&gt;We are still repeating ourself in line &lt;code&gt;(3)&lt;/code&gt;. How do I get a cleaner API to use such that we write:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class Order:
    price = NonNegative()
    quantity = NonNegative()

    def __init__(self, name, price, quantity):
        ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s look at the &lt;a href="https://docs.python.org/3/reference/datamodel.html#object.__set_name__"&gt;new descriptor protocol&lt;/a&gt; in Python 3.6:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;object.__set_name__(self, owner, name)&lt;/code&gt;
&lt;ul&gt;
&lt;li&gt;Called at the time the owning class owner is created. The descriptor has been assigned to name.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With this protocol, we could remove the &lt;code&gt;__init__&lt;/code&gt; and bind the attribute name to the descriptor:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class NonNegative:
    ...
    def __set_name__(self, owner, name):
        self.name = name&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To put all the codes together:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class NonNegative:
    def __get__(self, instance, owner):
        return instance.__dict__[self.name]
    def __set__(self, instance, value):
        if value &amp;lt; 0:
            raise ValueError(&amp;#39;Cannot be negative.&amp;#39;)
        instance.__dict__[self.name] = value
    def __set_name__(self, owner, name):
        self.name = name

class Order:
    price = NonNegative()
    quantity = NonNegative()

    def __init__(self, name, price, quantity):
        self._name = name
        self.price = price
        self.quantity = quantity

    def total(self):
        return self.price * self.quantity

apple_order = Order(&amp;#39;apple&amp;#39;, 1, 10)
apple_order.total()
# 10
apple_order.price = -10
# ValueError: Cannot be negative
apple_order.quantity = -10
# ValueError: Cannot be negative&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id="conclusion"&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Python is a general purpose programming language. I love that it not only has very powerful features that are highly flexible and could possibly bend the language tremendously (e.g. Meta Classes,) but also has high-level APIs/protocols to serve 99% of the needs (e.g. Descriptors.) I believe there’s the right tool for the job. Descriptors are clearly the right tool for binding behaviors to attributes. Although Meta Classes could potentially do the same thing, Descriptor could solve the problem more gracefully. It’s also pleasing to see Python evolve for serving general people’s needs better.&lt;/p&gt;
&lt;p&gt;Here’s my conclusion:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Python 3.6 is by far the greatest Python.&lt;/li&gt;
&lt;li&gt;Descriptors are used to bind behaviors to accessing attributes.&lt;/li&gt;
&lt;/ol&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/study-group-at-work</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>What is it like to start a study group at work</title>
    <updated>2018-04-24T00:00:00Z</updated>
    <published>2018-04-24T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/study-group-at-work" type="text/html"/>
    <content type="html">&lt;p&gt;Have you ever had the feeling that you got so passionate about something that you have to share it to everyone around you? You gotta force people to be passionate about it, am I right? I was so thrilled about Python two years ago, on the day I finally understood what list comprehension is. I had never knew programming could be so… enjoyable. Gradually from chit-chatting with colleagues, to going to a local meetup group and writing blog posts, I wish to find yet another way to share this amazing technology and to help people. So I thought about starting a Python study group in my workplace..&lt;/p&gt;
&lt;p&gt;..And I started a Python study group in my workplace 30 minutes later. This is what happened in the 30 minutes:&lt;/p&gt;
&lt;!-- more --&gt;
&lt;blockquote&gt;
&lt;p&gt;Minute 1 — &lt;em&gt;Chatting with my buddy in the office&lt;/em&gt; “Hey I am thinking about starting a Python study group at work. Do you want to help me?” “Yeah, I’ll help you.” “Cool, I’ll write an email and send it to a bunch of people.” Minute 5 — &lt;em&gt;writing email furiously&lt;/em&gt; Minute 10 — &lt;em&gt;re-writing email furiously&lt;/em&gt; &lt;em&gt;thrilled and scared the hell out of myself occasionally&lt;/em&gt; Minute 30 — &lt;em&gt;sent&lt;/em&gt; “PHEW”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Thinking of it today, that single click on the send button, was one of the best feeling in the world. Both frightening, and exciting. Of course my buddy and I encounter obstacles initially and sometimes throughout the two years, but here I want to share the recipe of running a study group at your workplace.&lt;/p&gt;
&lt;h1 id="the-recipe"&gt;The Recipe&lt;/h1&gt;
&lt;p&gt;You’ll need:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;A co-organizer — I wouldn’t have been able to run the study group by myself for 2 years without the help of my buddy.&lt;/li&gt;
&lt;li&gt;Space — Use an unoccupied company conference room. Keep using the same room to form a habit for the group.&lt;/li&gt;
&lt;li&gt;Time — Use you lunch break. Tell everyone to bring their lunch to the group.&lt;/li&gt;
&lt;li&gt;Frequency — Once a week. Initially I thought Friday would be the best because things are usually slower on Friday. Now our group settled on every Wednesday.&lt;/li&gt;
&lt;li&gt;People — Colleagues.&lt;/li&gt;
&lt;li&gt;Materials/topics — The ___ that you totally passionate about.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This recipe is definitely taking advantage of our workplace. So I would make sure to justify myself that the study group is beneficial to my employer. For a tech company, a movie study group might be on the riskier end that I wouldn’t recommend. But Python yes in where I work.&lt;/p&gt;
&lt;h1 id="whats-hard"&gt;What’s hard&lt;/h1&gt;
&lt;p&gt;Keeping the study group running is hard. In the early days, I sometimes feel people are watching us to fail. We had 30+ people show up at the very first meetup; then it quickly went down to 10 by the end of the month. For the first few months, we definitely was putting a lot more efforts preparing the materials before the meetup, almost like giving a conference talk, in hope to retain more people. It finally settled down to around 8 people each time. And I’m happy about the size :) Once we built up enough momentum, it just became easier. We weren’t spending that much time preparing. Occasionally we just let the conversation flow throughout the meetup. I’m not a talkative person, and I enjoy letting other people talk. I think the ultimate goal is the group to continue running even when my buddy and I are absent.&lt;/p&gt;
&lt;h1 id="whats-interesting-unexpected"&gt;What’s interesting (unexpected)&lt;/h1&gt;
&lt;p&gt;The funniest thing is that I somehow establish myself as some sort of a Python guru, which I’m not. I do enjoy sharing and teaching people, but I’m an intermediate Python programmer at best. It definitely put a lot of pressure on me when people start asking you quite a lot of questions that you have no idea what-so-ever. And interestingly, I found myself learning a lot better when I try to teach others. Some people learn better from books, some from videos, and for me, I learn better from teaching! It was very excited to me to realize this.&lt;/p&gt;
&lt;p&gt;And strangely, I gradually got more and more recognition in the company. The co-workers from other division that has Python questions, the new projects need someone who is proficient in Python to prototype things, and that new group working on the Machine Learning model? I got questions here and there. Somehow my buddy and I were getting those attentions. It usually wasn’t a bad thing unless it was a busy day.&lt;/p&gt;
&lt;h1 id="final-thoughts"&gt;Final thoughts&lt;/h1&gt;
&lt;p&gt;I think starting a study group at the workplace is totally worth it. It isn’t hard. The recipe is up there. I had to admit that I wasn’t happy about my work environment years ago, and particularly I wasn’t happy about the technology stack my workplace was using. Everything had changed since we started the study group. Now more people are talking about using Python in the company. We have a nice small community to discuss technology as well. It has been an very enjoyable (and additional) work for two years now. Really. Try it. This isn’t like running a startup. You really don’t have anything to lose for failing.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/practical-boolean-operators</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Practical Uses of Python AND and OR Boolean Operators</title>
    <updated>2016-03-02T00:00:00Z</updated>
    <published>2016-03-02T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/practical-boolean-operators" type="text/html"/>
    <content type="html">&lt;p&gt;In my previous post — Python Truth Value Testing is Awesome, I mentioned about the sweet combo of the truth value testing and the boolean operators, and gave an example for it using the or-operator. One of my colleagues gave me a comment that the or-operator all seems legit, but the and-operator seems pretty anti-intuitive. This raise the question in me: &lt;a href="http://stackoverflow.com/questions/35657101/practical-examples-of-python-and-operator"&gt;is there any practical example of using the and-operator which also takes the advantage of the generic truth value testing&lt;/a&gt;? Here’s what I found.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h1 id="the-definitions"&gt;The Definitions&lt;/h1&gt;
&lt;p&gt;Let’s include &lt;a href="https://docs.python.org/3.5/reference/expressions.html#boolean-operations"&gt;the definitions&lt;/a&gt; again to make this post more comprehensive:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The expression &lt;code&gt;x and y&lt;/code&gt; first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.&lt;/li&gt;
&lt;li&gt;The expression &lt;code&gt;x or y&lt;/code&gt; first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Yes indeed, at first glance neither of the operator seems intuitive compare to the traditional boolean operator that only works for True and False as the operants. Yet this is another thing I love about Python — the consistency. According to &lt;a href="https://www.python.org/dev/peps/pep-0020/"&gt;the Zen of Python&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Special cases aren’t special enough to break the rules.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Go ahead and plug in the True/False value into the above definitions. I’m not kidding. If you haven’t done that, do it now. See where this is going? They still give you the right values the same as what we expected. This more generic form of the operations does not break the rules. Now the million dollar question is, what do we do with these generic boolean operators? Hear me out.&lt;/p&gt;
&lt;h1 id="practical-examples"&gt;Practical examples&lt;/h1&gt;
&lt;p&gt;Here’s my practical example for using both operators:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;my_shopping_list = []

next_item_to_buy = my_shopping_list and my_shopping_list.pop()
# &amp;gt;&amp;gt; next_item_to_buy = []

print(my_shopping_list or &amp;#39;empty list&amp;#39;)
# &amp;gt;&amp;gt; empty list

my_shopping_list = [&amp;#39;eggs&amp;#39;, &amp;#39;kales&amp;#39;, &amp;#39;apples&amp;#39;]

next_item_to_buy = my_shopping_list and my_shopping_list.pop()
# &amp;gt;&amp;gt; next_item_to_buy = &amp;#39;apples&amp;#39;

print(my_shopping_list or &amp;#39;empty list&amp;#39;)
# &amp;gt;&amp;gt; [&amp;#39;eggs&amp;#39;, &amp;#39;kales&amp;#39;]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Also, thanks to &lt;a href="http://stackoverflow.com/users/248296/warvariuc"&gt;warvariuc&lt;/a&gt; on &lt;a href="http://stackoverflow.com/questions/35657101/practical-examples-of-python-and-operator/35662540#35662540"&gt;Stackoverflow&lt;/a&gt; to give an example for getting regex results:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import re

&amp;gt;&amp;gt;&amp;gt; match = re.search(r&amp;#39;\w(\d+)&amp;#39;, &amp;#39;test123&amp;#39;)

&amp;gt;&amp;gt;&amp;gt; number = match and match.group(1)

&amp;gt;&amp;gt;&amp;gt; number
&amp;gt;&amp;gt;&amp;gt; &amp;#39;123&amp;#39;

&amp;gt;&amp;gt;&amp;gt; match = re.search(r&amp;#39;\w(\d+)&amp;#39;, &amp;#39;test&amp;#39;)

&amp;gt;&amp;gt;&amp;gt; number = match and match.group(1)

&amp;gt;&amp;gt;&amp;gt; number&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id="or-is-a-fallback-and-is-a-guard"&gt;OR is a fallback, AND is a guard&lt;/h1&gt;
&lt;p&gt;&lt;a href="http://stackoverflow.com/questions/4477850/python-and-or-operators-return-value/28321263#28321263"&gt;This&lt;/a&gt; is the best analogy I find.&lt;/p&gt;
&lt;p&gt;Think of this way for the OR-operator: the second value serves as a &lt;strong&gt;fallback&lt;/strong&gt; value if something’s wrong (does not exists, or have a False-y value) with the first.&lt;/p&gt;
&lt;p&gt;On the other hand, for the AND-operator, the first value serves as a &lt;strong&gt;guard&lt;/strong&gt; for retrieving the second value. If the first value failed the truth value testing, the second won’t be accessed. With this analogy, when I look at the and keyword in the code above, I tend to read “and” as “and then…,” because there’s this hidden truth value testing behind the scene.&lt;/p&gt;
&lt;p&gt;This is such a nice short-hand, isn’t it? If you’re like me, a Python programmer transitioning from Java, think about the fallback and the guard I talked about when you find yourself in the place to write if-else code blocks just to do variable assignment. You might get your Ah-ha moment just like me while doing the research for this article.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/on-personal-website</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>On Personal Websites</title>
    <updated>2021-04-06T00:00:00Z</updated>
    <published>2021-04-06T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/on-personal-website" type="text/html"/>
    <content type="html">&lt;p&gt;Hi everyone! I want to share some of my thoughts and the benefits of building personal websites. This won’t be a step-by-step guide to building your first personal website. It’ll take me to write another article for it. Instead, hopefully, I can convince you to build a personal website. Here we go.&lt;/p&gt;
&lt;h1 id="learning-the-technologies"&gt;Learning the technologies&lt;/h1&gt;
&lt;p&gt;Building a personal website is a great learning exercise for the underlying technologies because of &lt;strong&gt;the variability of complexity&lt;/strong&gt; and its &lt;strong&gt;visibility&lt;/strong&gt;. People with different experiences may want to deal with different complexities. If you are a technology-savvy person, you can build your website with a state-of-the-art JS framework with whatever latest graph API backend, styled with CSS-in-JS (I’m just throwing a lot of random buzz words here, please don’t take me too seriously &#128539;). If you are a minimalist, you can build a static website with hand-crafted HTML and CSS. You can even use a site builder like Wix to learn the basics of styling and focus on personal branding only. You have a wide range of choices, and no matter your choice of technology, you get a website that is visible to the whole internet. You can share it with anyone, anywhere. The visibility makes it so rewarding.&lt;/p&gt;
&lt;h1 id="personal-branding"&gt;Personal branding&lt;/h1&gt;
&lt;p&gt;IMHO, managing one’s online presence is very important, if not crucial, nowadays. A quick test for your online presence is to search your name on the search engine. What does the first page of the search results say about you? Do you have a say about the search results? I.e., do you have a way to influence the websites/articles that other people see you online? IMO social media profile isn’t the answer. There is so much more to a person’s characters than the news or photos or random rantings they share online. It’s a lot easier for a unique website to stand out in the crowd of the always same-looking social media profiles.&lt;/p&gt;
&lt;p&gt;(I’m a bit biased here because I don’t trust social media, and you probably shouldn’t either &#128521;.)&lt;/p&gt;
&lt;h1 id="self-publishing-articles"&gt;Self-publishing articles&lt;/h1&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Either write something worth reading or do something worth writing.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Benjamin Franklin&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Writing is such a crucial skill to have regardless of your level of experience or your position. I cannot express enough how much my writing skills benefited from publishing articles on my personal blog. When you have your own website, you turn yourself into a publisher as well as an author. Consider this, how hard is it to publish an essay in a renowned science journal? You are practically free to write and publish articles on your website. Of course, the stakes between publishing on a journal are significantly different from publishing on your website. And that’s exactly why writing for your own website is such a good practice ground to develop your writing skills.&lt;/p&gt;
&lt;h1 id="bonus-your-website-your-values"&gt;Bonus: your website, your values&lt;/h1&gt;
&lt;p&gt;This may not be very important to most of us, but don’t let the platforms’ values define you. For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If you are pro-privacy, you don’t need to track your readers using Google analytics on your websites.&lt;/li&gt;
&lt;li&gt;If you hate ads, you don’t have to show ads on your websites.&lt;/li&gt;
&lt;li&gt;If you hate JavaScript, you don’t have to use JavaScript to build your websites.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id="conclusion"&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Yes, you need a personal website.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/i-too-wrote-myself-a-static-site-generator</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>I, too, Wrote Myself a Static Site Generator</title>
    <updated>2022-02-18T00:00:00Z</updated>
    <published>2022-02-18T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/i-too-wrote-myself-a-static-site-generator" type="text/html"/>
    <content type="html">&lt;p&gt;You can view the source code &lt;a href="https://github.com/dawranliou/dawranliou.com"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="story"&gt;Story&lt;/h2&gt;
&lt;p&gt;My history of playing with static site generator starts with Jekyll, Pelican, Hugo, Middleman, and eventually landed on &lt;a href="https://getzola.org"&gt;Zola&lt;/a&gt;, which is my personal favourite among these off-the-shelf static site generators.&lt;a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; There were very little things to complain about Zola, but one major painpoint was that - it isn’t built on Clojure (or any Lisp) so I didn’t know how to hack the sourcecode if there were something I want to change nor could I really understand the code. After reading &lt;a href="https://freeston.me"&gt;Dominic&lt;/a&gt;’s &lt;a href="https://freeston.me/posts/2021-11-29-new-site-generator/"&gt;I wrote myself a static site generator&lt;/a&gt; and &lt;a href="https://blog.hamaluik.ca/posts/build-your-own-static-site-generator/"&gt;Kenton’s Build Your Own Static Site Generator&lt;/a&gt;, I was really inspired and decided to follow suit.&lt;/p&gt;
&lt;p&gt;It took several tries to get to my ideal level of complexity. Initially I was really annoyed by how imparative the main function was, and so I rewrote the logic into a desciptive &lt;code&gt;build-plan&lt;/code&gt;, a series of descriptive steps each with a &lt;code&gt;:build/op&lt;/code&gt; keyword, such as &lt;code&gt;:ensure-folder&lt;/code&gt;, &lt;code&gt;:copy-dir&lt;/code&gt;, or &lt;code&gt;:page&lt;/code&gt;. My main function becomes a &lt;code&gt;doseq&lt;/code&gt; on the &lt;code&gt;build-plan&lt;/code&gt; that will dispatch on the &lt;code&gt;:build/op&lt;/code&gt; key.&lt;a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; This indirection of imparativeness is pleasing to look at but it’s really difficult to fit into my workflow. After a detour into the Common Lisp world with my other gamedev project, I decided to scratch that implementation and imbrace the imparativeness nature of the code. At this time, I also introduced the &lt;code&gt;site-map.edn&lt;/code&gt; file, which is inspired by the flexibility of how Common Lisp assembles a package. I think I just prefer configuration over convention. I decided not to impose any significant meaning to the file structure to the markdown files under the &lt;code&gt;contents&lt;/code&gt; folder. Instead, I explicitly link the source file to a target URI in this &lt;code&gt;site-map.edn&lt;/code&gt; file.&lt;/p&gt;
&lt;p&gt;Building atom feeds (RSS feeds) was also a bit challenging because this is the one thing I really didn’t want to break backward compatibility. (I’m really sorry if I still break your RSS client feed. I tried hard not to.) A really useful resource is &lt;a href="https://validator.w3.org/feed/"&gt;W3G’s Feed Validation Service&lt;/a&gt;. One thing I found weird was that the &lt;code&gt;clojure.data.xml&lt;/code&gt; would compile the Hiccup form &lt;code&gt;[:feed {"xmlns" "http://www.w3.org/2005/Atom"} ...]&lt;/code&gt; into &lt;code&gt;&amp;lt;feed xmlns:b="http://www.w3.org/2005/Atom" ...&lt;/code&gt;. Notice that the &lt;code&gt;xmlns&lt;/code&gt; attribute turned into &lt;code&gt;xmlns:b&lt;/code&gt; here and thus invalidate the feed. For now I just YOLO’d it with a &lt;code&gt;str/replace-first&lt;/code&gt; function.&lt;a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt; &#129335; (Also, did I mention that I use &lt;code&gt;python3 -m http.server&lt;/code&gt; to serve the site locally?)&lt;/p&gt;
&lt;h2 id="outcome"&gt;Outcome&lt;/h2&gt;
&lt;p&gt;With Dominic’s &lt;code&gt;build.sh&lt;/code&gt; script, I was able to deploy my site on Netlify &#127881;&lt;/p&gt;
&lt;p&gt;As the time of writing, my code count is around:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;~180 lines for all hiccup templates&lt;/li&gt;
&lt;li&gt;~110 lines for parsing and generating the site&lt;/li&gt;
&lt;li&gt;And… ~500 lines of site-map.edn&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="footnotes"&gt;Footnotes&lt;/h2&gt;
&lt;section class="footnotes" role="doc-endnotes"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn1" role="doc-endnote"&gt;&lt;p&gt;Zola has a relatively simple templating structure, and it’s very fast.&lt;a href="#fnref1" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn2" role="doc-endnote"&gt;&lt;p&gt;This was highly inspired by the ClojureScript compiler code I read earlier that year.&lt;a href="#fnref2" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn3" role="doc-endnote"&gt;&lt;p&gt;https://github.com/dawranliou/dawranliou.com/blob/master/src/com/dawranliou/build.clj#L65-L69&lt;a href="#fnref3" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/vanilla-cljs</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Vanilla ClojureScript</title>
    <updated>2022-08-09T00:00:00Z</updated>
    <published>2022-08-09T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/vanilla-cljs" type="text/html"/>
    <content type="html">&lt;figure&gt;
&lt;img src="/images/vanilla-cljs-4.gif" alt="On-demand component re-rendering" alt="The vanilla ClojureScript app we&amp;#39;ll be building throughout the article" /&gt;&lt;figcaption aria-hidden="true"&gt;The vanilla ClojureScript app we'll be building throughout the article&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h2 id="introduction"&gt;Introduction&lt;/h2&gt;
&lt;p&gt;When I started writing ClojureScript apps, I was introduced to many tooling that jointly contributed to this fantastic reloadable workflow that was unmatched by anything I knew. I had recently read several ClojureScript-specific questions from both Clojure newcomers and experienced JVM Clojure developers. It occurred to me that however impressive the ClojureScript + tooling experiences were, our ClojureScript community can benefit from some more clarity on what ClojureScript does vs. tooling. &lt;a href="https://twitter.com/thheller"&gt;&lt;span class="citation" data-cites="thheller"&gt;@thheller&lt;/span&gt;&lt;/a&gt; already has &lt;a href="https://code.thheller.com/blog/shadow-cljs/2019/03/01/what-shadow-cljs-is-and-isnt.html"&gt;an article focusing on what shadow-cljs is and isn't&lt;/a&gt;. I wrote this article to demonstrate the various things you can do with vanilla ClojureScript without addition toolings. My goals are:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;For newcomers, I hope this article clarifies what ClojureScript can do without additional tooling and make your Clojure journey a bit less overwhelming.&lt;/li&gt;
&lt;li&gt;For experienced JVM Clojure developers, I hope this article becomes a good reference to ease your way into the ClojureScript ecosystem.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;My intention is not to dissuade you from using toolings like &lt;a href="https://figwheel.org/"&gt;figwheel-main&lt;/a&gt;, &lt;a href="https://shadow-cljs.github.io/docs/UsersGuide.html"&gt;shadow-cljs&lt;/a&gt;, or even &lt;a href="https://cider.mx/"&gt;cider&lt;/a&gt; + &lt;a href="https://nrepl.org/nrepl/index.html"&gt;nREPL&lt;/a&gt; + &lt;a href="https://github.com/nrepl/piggieback"&gt;nrepl/piggieback&lt;/a&gt; combo. Instead, I hope this article makes it even more clear to you why those additional tools are helpful in the first place. Also, I hope to equip you with a mental model to help you deal with problems specific to your workflow.&lt;/p&gt;
&lt;p&gt;I realized that much of what I wanted to demonstrate was already covered by &lt;a href="https://clojurescript.org/"&gt;the official ClojureScript site&lt;/a&gt;. For people want even more in-depth explanations, links to the relevant topics on the official ClojureScript site are included.&lt;/p&gt;
&lt;p&gt;Before diving into the topic, here's more about the ClojureScript REPL, or the many ClojureScript &lt;em&gt;REPLs&lt;/em&gt;. Feel free to &lt;span class="spurious-link" target="Setup"&gt;&lt;em&gt;skip the next section and jump into the project setup&lt;/em&gt;&lt;/span&gt;.&lt;/p&gt;
&lt;h2 id="clojurescript-repls"&gt;ClojureScript REPL(s)&lt;/h2&gt;
&lt;p&gt;From the &lt;a href="https://docs.cider.mx/cider/cljs/overview.html"&gt;Cider documentation&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Unlike the Clojure ecosystem that is dominated by a single REPL, the ClojureScript ecosystem has a number of different choices for REPLs (e.g. &lt;code class="verbatim"&gt;browser&lt;/code&gt;, &lt;code class="verbatim"&gt;node&lt;/code&gt;, &lt;code class="verbatim"&gt;weasel&lt;/code&gt;, &lt;code class="verbatim"&gt;figwheel&lt;/code&gt; and &lt;code class="verbatim"&gt;shadow-cljs&lt;/code&gt;). You’ll have to decide which one you want to run and how you want CIDER to interact with it.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It was a bit confusing when I first read this. Isn't REPL &lt;strong&gt;the thing&lt;/strong&gt;? What's going on with all the different REPLs listed?&lt;/p&gt;
&lt;p&gt;What I didn't understand was that &lt;strong&gt;REPL is the application&lt;/strong&gt;, the runtime, or the service. Just like you can develop applications on different platform/runtime - browser applications, nodejs applications, or webworker applications - the REPLs also comes in different flavours.&lt;/p&gt;
&lt;p&gt;For the rest of this article, we'll be focusing on the browser applications, which is the default&lt;a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;. The nodejs ClojureScript REPL is available too&lt;a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; (but &lt;strong&gt;NOT&lt;/strong&gt; nREPL&lt;a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;FYI, you don't have to use the REPL in ClojureScript if you prefer the less interactive approach to compile and reload the static files in the browser. I'm very into the REPL workflow so please expect to see a lot of REPL interactions throughout this article.&lt;/p&gt;
&lt;p&gt;To learn more about various ClojureScript REPLs, &lt;a href="https://lambdaisland.com/guides/clojure-repls/clojurescript-repls"&gt;go checkout Lambda Island's article "ClojureScript REPLs"&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="/images/vanilla-cljs-sketch.png" alt="A screenshot of our p5.js sketch application" width="100" height="100" /&gt;&lt;/p&gt;
&lt;h2 id="setup"&gt;Setup&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Relevant guide on ClojureScript.org website: &lt;a href="https://clojurescript.org/guides/quick-start"&gt;Quick Start&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;In this example, we are going to build a ClojureScript &lt;a href="https://p5js.org/"&gt;p5.js&lt;/a&gt; browser application to test how much vanilla ClojureScript can do. Here's the project structure:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;vanilla-cljs         # Our project folder
├─ src               # The CLJS source code for our project
│  └─ vanilla_cljs   # Our vanilla-cljs namespace folder
│     ├─ main.cljs   # Our main file that binds everything together
│     └─ sketch.cljs # Our code to interact with p5.js sketch
├─ build.edn         # The compiler options for our dev build
├─ deps.edn          # A file for listing our dependencies
└─ index.html        # The HTML file for our browser application
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class="verbatim"&gt;deps.edn&lt;/code&gt; only needs to contain the ClojureScript as the project dependency:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;{:deps {org.clojure/clojurescript {:mvn/version &amp;quot;1.11.54&amp;quot;}}}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class="verbatim"&gt;index.html&lt;/code&gt; includes the p5.js library and the compiled main entry file. Optionally, &lt;a href="https://p5js.org/download/"&gt;download the p5.js library&lt;/a&gt; to the project root.&lt;/p&gt;
&lt;pre class="html"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&amp;quot;&amp;quot;&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;
  &amp;lt;meta name=&amp;quot;viewport&amp;quot; content=&amp;quot;width=device-width, initial-scale=1.0&amp;quot;&amp;gt;
  &amp;lt;title&amp;gt;Vanilla CLJS with p5.js&amp;lt;/title&amp;gt;
  &amp;lt;style&amp;gt;
    body {
      padding: 0;
      margin: 0;
    }
  &amp;lt;/style&amp;gt;
  &amp;lt;script src=&amp;quot;https://cdn.jsdelivr.net/npm/p5@1.4.2/lib/p5.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;!-- or download a local copy to project root directory --&amp;gt;
  &amp;lt;!-- &amp;lt;script src=&amp;quot;p5.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt; --&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;main&amp;gt;
  &amp;lt;/main&amp;gt;
  &amp;lt;script src=&amp;quot;out/main.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class="verbatim"&gt;build.edn&lt;/code&gt; contains the ClojureScript compiler options for our development build. You can pass all the compiler options to the ClojureScript compiler using the CLI command. However, we'll be passing this filename to the &lt;code class="verbatim"&gt;-co&lt;/code&gt; / &lt;code class="verbatim"&gt;--compile-opts&lt;/code&gt; option in throughout the article. See all the compiler options at &lt;a href="https://clojurescript.org/reference/compiler-options"&gt;ClojureScript's official reference to compiler options&lt;/a&gt;.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;{:main vanilla-cljs.main
 :output-to &amp;quot;out/main.js&amp;quot;
 :output-dir &amp;quot;out&amp;quot;
 :optimizations :none}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class="verbatim"&gt;sketch.cljs&lt;/code&gt; contains the logic to setup and draw the sketch with p5.js. &lt;code class="verbatim"&gt;redraw&lt;/code&gt; and &lt;code class="verbatim"&gt;reseed-redraw&lt;/code&gt; are helper functions for us to play with in the REPL session. You'll see their usages later in this article.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(ns vanilla-cljs.sketch)

(def size 300)
(def step 15)
(def seed 1050879010481460)

(defn setup []
  (js/noLoop)
  (js/randomSeed seed)
  (js/createCanvas size size))

(defn diagonal-line [x y w h]
  (if (&amp;lt; 0.5 (js/random))
    (js/line  x        y  (+ x w)  (+ y h))  ; top-left to bottom-right
    (js/line  x  (+ y h)  (+ x w)       y))) ; bottom-left to top-right

(defn draw []
  (js/background 200)
  (doseq [[x y] (for [x (range 0 size step)
                      y (range 0 size step)]
                  [x y])]
    (diagonal-line x y step step)))

(defn redraw []
  (js/redraw))

(defn reseed-redraw []
  (js/randomSeed seed)
  (redraw))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class="verbatim"&gt;main.cljs&lt;/code&gt; is the main entry point of our application. It provides the side-effect-y code that is required to interact with p5.js, which looks up two global functions &lt;code class="verbatim"&gt;setup&lt;/code&gt; and &lt;code class="verbatim"&gt;draw&lt;/code&gt; to perform its magic. To register global functions in ClojureScript, we'll use &lt;code class="verbatim"&gt;goog.object/set&lt;/code&gt; on the &lt;code class="verbatim"&gt;js/window&lt;/code&gt; global object. Using the extra indirection to bind the anonymous function will make our code more REPL friendly.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(ns vanilla-cljs.main
  (:require [vanilla-cljs.sketch :as sketch]
            [goog.object :as gobj]))

(gobj/set js/window &amp;quot;setup&amp;quot; #(sketch/setup))
(gobj/set js/window &amp;quot;draw&amp;quot; #(sketch/draw))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is the project setup we need for the rests of the article.&lt;/p&gt;
&lt;h2 id="compile-to-javascript"&gt;Compile to JavaScript&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Relevant guide on ClojureScript.org website: &lt;a href="https://clojurescript.org/guides/quick-start"&gt;Quick Start&lt;/a&gt;, &lt;a href="https://clojurescript.org/reference/repl-and-main"&gt;The REPL and main entry points&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;To compile our ClojureScript app, we can invoke the &lt;code class="verbatim"&gt;cljs.main&lt;/code&gt; main option providing our &lt;code class="verbatim"&gt;build.edn&lt;/code&gt; as the compiler options. Use &lt;code class="verbatim"&gt;-c&lt;/code&gt; / &lt;code class="verbatim"&gt;--compile&lt;/code&gt; to explicitly tell ClojureScript compiler to compile the code once.&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main -co build.edn -c
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To compile the source code for production, append the &lt;code class="verbatim"&gt;-O&lt;/code&gt; / &lt;code class="verbatim"&gt;--optimization&lt;/code&gt; option with &lt;code class="verbatim"&gt;advanced&lt;/code&gt; mode:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main -co build.edn -O advanced -c
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="serve-static-assets"&gt;Serve static assets&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Relevant guide on ClojureScript.org website: &lt;a href="https://clojurescript.org/guides/quick-start"&gt;Quick Start&lt;/a&gt;, &lt;a href="https://clojurescript.org/reference/repl-and-main"&gt;The REPL and main entry points&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;ClojureScript has a built-in server to serve static files. You can invoke it via &lt;code class="verbatim"&gt;-s&lt;/code&gt; / &lt;code class="verbatim"&gt;--serve&lt;/code&gt; option:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main -s
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This command option can be combined with the compile option in the previous section to compile and serve the code:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main -co build.edn -c -s
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is useful for testing out the advanced compilation for the production build:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main -co build.edn -O advanced -c -s
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="start-a-browser-repl"&gt;Start a browser REPL&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Relevant guide on ClojureScript.org website: &lt;a href="https://clojurescript.org/guides/quick-start"&gt;Quick Start&lt;/a&gt;, &lt;a href="https://clojurescript.org/reference/repl-and-main"&gt;The REPL and main entry points&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;It wouldn't be fun without a REPL to interact with. Use &lt;code class="verbatim"&gt;-r&lt;/code&gt; / &lt;code class="verbatim"&gt;--repl&lt;/code&gt; option to start an interactive REPL once the compilation finishes. Also use &lt;code class="verbatim"&gt;-v&lt;/code&gt; / &lt;code class="verbatim"&gt;--verbose&lt;/code&gt; for more debugging information:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main -co build.edn -v -c -r

# Observe the browser alert shows up after sending this form
cljs.user=&amp;gt; (js/alert &amp;quot;hi&amp;quot;)
nil
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="interact-with-browser-repl"&gt;Interact with browser REPL&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Relevant guide on ClojureScript.org website: &lt;a href="https://clojurescript.org/guides/quick-start"&gt;Quick Start&lt;/a&gt;, &lt;a href="https://clojurescript.org/reference/repl-and-main"&gt;The REPL and main entry points&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;figure&gt;
&lt;img src="/images/vanilla-cljs-1.gif" alt="This is a gif of live-redrawing the sketch from the REPL" alt="Live-updating the sketch from the REPL" /&gt;&lt;figcaption aria-hidden="true"&gt;Live-updating the sketch from the REPL&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Just like in JVM Clojure that you can redefine Vars on-the-fly in a REPL session, you can also do it in ClojureScript. First we can try typing directly into the REPL. Using the &lt;code class="verbatim"&gt;redraw&lt;/code&gt; helper function, each time the random number generator will give a different sketch. We can also use the &lt;code class="verbatim"&gt;reseed-redraw&lt;/code&gt; function to reset the random seed and thus put the random number generator state back to the first drawing. Changing the step size Var will give you a different result too.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;cljs.user=&amp;gt; (in-ns &amp;#39;vanilla-cljs.sketch)
nil
vanilla-cljs.sketch=&amp;gt; (redraw)          ; Generate a new sketch
nil
vanilla-cljs.sketch=&amp;gt; (redraw)          ; Generate a new sketch
nil
vanilla-cljs.sketch=&amp;gt; (redraw)          ; Generate a new sketch
nil
vanilla-cljs.sketch=&amp;gt; (reseed-redraw)   ; Reset the sketch
nil
vanilla-cljs.sketch=&amp;gt; step              ; Check the original step size
15
vanilla-cljs.sketch=&amp;gt; (set! step 30)    ; Double the step size
30
vanilla-cljs.sketch=&amp;gt; (reseed-redraw)   ; Redraw with the new step size
nil
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="recompile-clojurescript-from-repl"&gt;Recompile ClojureScript from REPL&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Relevant guide on ClojureScript.org website: &lt;a href="https://clojurescript.org/guides/quick-start"&gt;Quick Start&lt;/a&gt;, &lt;a href="https://clojurescript.org/reference/repl-and-main"&gt;The REPL and main entry points&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;figure&gt;
&lt;img src="/images/vanilla-cljs-2.gif" alt="Reload and recompile the whole namespace to persist changes" alt="Reload/recompile code from the REPL" /&gt;&lt;figcaption aria-hidden="true"&gt;Reload/recompile code from the REPL&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Typing into the REPL is fine. However, redefining the step size Var will not persist when the page gets reloaded. Everything typed into the REPL directly will only affect the current REPL session. This is great for exploration but when we need to codify our work, we'll need a slightly different workflow. Thankfully, we can also reload/recompile code from within the REPL. For example, let's double the &lt;code class="verbatim"&gt;step&lt;/code&gt; size to &lt;code class="verbatim"&gt;30&lt;/code&gt; in &lt;code class="verbatim"&gt;sketch.cljs&lt;/code&gt; file:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(def step 30)                           ; This was 15
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can then reload the file and see the code gets recompiled:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;vanilla-cljs.sketch=&amp;gt; (require &amp;#39;vanilla-cljs.main :reload)
Compiling /home/dawran/projects/vanilla-cljs/src/vanilla_cljs/sketch.cljs to out/vanilla_cljs/sketch.js
Copying file:/home/dawran/projects/vanilla-cljs/src/vanilla_cljs/sketch.cljs to out/vanilla_cljs/sketch.cljs
nil
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, refresh the page and you should see the new step size is used to draw the sketch.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: I think &lt;code class="verbatim"&gt;(require 'vanilla-cljs.main :reload)&lt;/code&gt; automatically recompiled all the transitive dependencies. However, I'm not sure if this is guaranteed. If this doesn't work, reload with &lt;code class="verbatim"&gt;(require 'vanilla-cljs.sketch :reload)&lt;/code&gt; to be more specific.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id="bundle-with-npm-dependencies"&gt;Bundle with NPM dependencies&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Relevant guide on ClojureScript.org website: &lt;a href="https://clojurescript.org/guides/webpack"&gt;Webpack&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Unlike how we added the p5.js dependency as a static file and serve it directly, when you start having npm dependencies for browser applications, we need tools to bundle up the JS files so the browser can load them. ClojureScript can integrate with Webpack to bundle our app with a few changes. But first, you need to install node.js and Webpack.&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ echo &amp;quot;{}&amp;quot; &amp;gt; package.json
$ npm install --save-dev webpack webpack-cli
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, we'll install react and react-dom as the npm dependencies:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;npm install --save react react-dom
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Modify the &lt;code class="verbatim"&gt;build.edn&lt;/code&gt; to the &lt;code class="verbatim"&gt;:bundle&lt;/code&gt; target:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;{:main vanilla-cljs.main
 :optimizations :none
 :output-to &amp;quot;out/index.js&amp;quot;
 :output-dir &amp;quot;out&amp;quot;
 :target :bundle
 :bundle-cmd {:none [&amp;quot;npx&amp;quot; &amp;quot;webpack&amp;quot; &amp;quot;./out/index.js&amp;quot; &amp;quot;-o&amp;quot; &amp;quot;out&amp;quot; &amp;quot;--mode=development&amp;quot;]
              :default [&amp;quot;npx&amp;quot; &amp;quot;webpack&amp;quot; &amp;quot;./out/index.js&amp;quot; &amp;quot;-o&amp;quot; &amp;quot;out&amp;quot;]}
 :closure-defines {cljs.core/*global* &amp;quot;window&amp;quot;}} ;; needed for advanced
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, to make our lives easier, I'll cheat and introduce a ClojureScript dependency - reagent to our project. (Sorry this is no longer truly vanilla ClojureScript anymore!) Update the &lt;code class="verbatim"&gt;deps.edn&lt;/code&gt; to:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;{:deps {org.clojure/clojurescript {:mvn/version &amp;quot;1.11.54&amp;quot;}
        reagent/reagent {:mvn/version &amp;quot;1.1.1&amp;quot;
                         ;; Exclude these since we&amp;#39;re providing our own
                         ;; react/react-dom from npm.
                         :exclusions [cljsjs/react cljsjs/react-dom]}}}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we can update the &lt;code class="verbatim"&gt;main.cljs&lt;/code&gt; to:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(ns vanilla-cljs.main
  (:require
   [goog.dom :as gdom]
   [goog.object :as gobj]
   [reagent.core :as r]
   [reagent.dom :as dom]
   [vanilla-cljs.sketch :as sketch]))

(defn canvas-control []
  (let [state (r/atom sketch/step)]
    (fn []
      [:div
       [:label {:for &amp;quot;step&amp;quot;} &amp;quot;Step size:&amp;quot;]
       [:input {:type &amp;quot;number&amp;quot;
                :id &amp;quot;step&amp;quot;
                :name &amp;quot;step&amp;quot;
                :min &amp;quot;5&amp;quot;
                :max &amp;quot;300&amp;quot;
                :value @state
                :on-change (fn [event]
                             (reset! state
                                     (js/parseInt
                                      (gobj/getValueByKeys event
                                                           &amp;quot;target&amp;quot;
                                                           &amp;quot;value&amp;quot;))))}]
       [:br]
       [:input {:type &amp;quot;button&amp;quot;
               :value &amp;quot;Redraw&amp;quot;
                :on-click (fn [_evt]
                            (set! sketch/step @state)
                            (sketch/redraw))}]
       [:br]
       [:input {:type &amp;quot;button&amp;quot;
                :value &amp;quot;Reseed + Redraw&amp;quot;
                :on-click (fn [_evt]
                            (set! sketch/step @state)
                            (sketch/reseed-redraw))}]])))

(defn mount []
  (dom/render [canvas-control] (gdom/getElement &amp;quot;app&amp;quot;)))

;; This only runs once when the page loads.
(defonce start-up
  (do
    (gobj/set js/window &amp;quot;setup&amp;quot; #(sketch/setup))
    (gobj/set js/window &amp;quot;draw&amp;quot; #(sketch/draw))
    (mount)
    true))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can now build the app again. Now you have UI buttons to interact with the p5.js sketch:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;# Compile dev build and launch REPL
$ clj -M -m cljs.main -co build.edn -v -c -r
# Compile prod build and serve the static files
$ clj -M -m cljs.main -co build.edn -O advanced -v -c -s
&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;img src="/images/vanilla-cljs-3.gif" alt="An browser app with controls to redraw the sketch" alt="Using React component to update the p5.js sketch." /&gt;&lt;figcaption aria-hidden="true"&gt;Using React component to update the p5.js sketch.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The UI code is reload-able on demand via invoking the &lt;code class="verbatim"&gt;mount&lt;/code&gt; function. Notice the component local state, the step size input, is preserved on component re-rendering.&lt;/p&gt;
&lt;figure&gt;
&lt;img src="/images/vanilla-cljs-4.gif" alt="On-demand component re-rendering" alt="The vanilla ClojureScript app we&amp;#39;ll be building throughout the article" /&gt;&lt;figcaption aria-hidden="true"&gt;The vanilla ClojureScript app we'll be building throughout the article&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;It's pretty amazing how much things the vanilla ClojureScript can do - compiling code, bundling NPM packages, connecting to a browser, plus other capabilities didn't get included in this article (e.g. &lt;a href="https://clojurescript.org/guides/externs"&gt;Inferred Externs&lt;/a&gt; and &lt;a href="https://clojurescript.org/guides/code-splitting"&gt;Code Splitting&lt;/a&gt;)! Experienced people might already noticed what vanilla ClojureScript doesn't do:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Hot-code reloading - this is where tooling like figwheel-main or shadow-cljs shines.&lt;/li&gt;
&lt;li&gt;Editor integration - This is where nREPL, piggieback, and cider are useful.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Thanks for reading! I hope you find this article and the demos useful. Feel free to give me your feedback. Here is &lt;a href="https://dawranliou.com/contact/"&gt;a list of my public contact channels&lt;/a&gt;. Cheers!&lt;/p&gt;
&lt;h2 id="references"&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://clojurescript.org"&gt;ClojureScript official website&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://clojurescript.org/guides/quick-start"&gt;ClojureScript - Quick Start&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://clojurescript.org/guides/webpack"&gt;ClojureScript - Webpack&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://clojurescript.org/reference/compiler-options"&gt;ClojureScript - Compiler Options&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://lambdaisland.com/guides/clojure-repls/clojurescript-repls"&gt;Lambda Island - ClojureScript REPLs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://code.thheller.com/blog/shadow-cljs/2019/03/01/what-shadow-cljs-is-and-isnt.html"&gt;What shadow-cljs is and isn't&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://figwheel.org/docs/"&gt;Figwheel-main Documentations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://groups.google.com/g/clojure-dev/c/Dl3Stw5iRVA/m/IHoVWiJz5UIJ"&gt;Rich Hickey on nREPL misnomer&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;section class="footnotes" role="doc-endnotes"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn1" role="doc-endnote"&gt;&lt;p&gt;You can check the &lt;code class="verbatim"&gt;cljs.main&lt;/code&gt; options:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main --help

[...]
   -t, --target name          The JavaScript target. Configures environment
                              bootstrap and defaults to browser. Supported
                              values: node or nodejs, webworker, bundle, none
[...]
&lt;/code&gt;&lt;/pre&gt;
&lt;a href="#fnref1" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/li&gt;
&lt;li id="fn2" role="doc-endnote"&gt;&lt;p&gt;Here's a short example of a Node.js REPL:&lt;/p&gt;
&lt;pre class="bash"&gt;&lt;code&gt;$ clj -M -m cljs.main --target nodejs --repl
&lt;/code&gt;&lt;/pre&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(def http (js/require &amp;quot;http&amp;quot;))          ; Or (require &amp;#39;[&amp;quot;http&amp;quot;])

(defn handler [req res]
  (set! (.-statusCode res) 200)
  (.setHeader res &amp;quot;Content-Type&amp;quot; &amp;quot;text/plain&amp;quot;)
  (.end res &amp;quot;Hello from nodejs REPL!&amp;quot;))

(def server
  (.createServer http
                 ;; Extra indirection to allow redefining handler on-the-fly
                 (fn [req res]
                   (handler req res))))

(.listen server 3000 &amp;quot;127.0.0.1&amp;quot;
         #(js/console.log &amp;quot;Server listening at http://127.0.0.1:3000&amp;quot;))
&lt;/code&gt;&lt;/pre&gt;
&lt;a href="#fnref2" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/li&gt;
&lt;li id="fn3" role="doc-endnote"&gt;&lt;p&gt;What about the nREPL? Strictly speaking, &lt;a href="https://groups.google.com/g/clojure-dev/c/Dl3Stw5iRVA/m/IHoVWiJz5UIJ"&gt;an nREPL isn't a REPL&lt;/a&gt;. nREPL is an network layer that communicates between a live Clojure REPL environment and the tooling.&lt;a href="#fnref3" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/reagent-component-vs-react-component</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>The distinction between Reagent component and React component</title>
    <updated>2021-03-21T00:00:00Z</updated>
    <published>2021-03-21T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/reagent-component-vs-react-component" type="text/html"/>
    <content type="html">&lt;p&gt;At work, I rarely have to think about the distinction between a Reagent component and a React component since Reagent does such a good job providing a coherent and simple API to use. (Plus, we don’t use any extern JS component libraries.)&lt;/p&gt;
&lt;p&gt;I came across the &lt;a href="https://stackoverflow.com/q/66714919"&gt;StackOverflow question&lt;/a&gt; the other day. While researching for the answer, it occurred to me that the simplicity of Reagent API can sometimes trick people up. The focus of this article isn’t so much about the original SO question, though I will use the example in the post, but more about sharing some easy-to-overlook information for the Reagent users.&lt;/p&gt;
&lt;h2 id="the-distinction"&gt;The distinction&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://reactjs.org/docs/react-component.html"&gt;React components&lt;/a&gt; are classes that extends the &lt;code&gt;React.Component&lt;/code&gt; class. Example:&lt;/p&gt;
&lt;pre class="js"&gt;&lt;code&gt;// JSX style
class Welcome extends React.Component {
  render() {
    return &amp;lt;h1&amp;gt;Hello, {this.props.name}&amp;lt;/h1&amp;gt;;
  }
}

function Welcome(props) {
  return &amp;lt;h1&amp;gt;Hello, {props.name}&amp;lt;/h1&amp;gt;;
}

// JS style
class Hello extends React.Component {
  render() {
    return React.createElement(&amp;#39;div&amp;#39;, null, `Hello ${this.props.toWhat}`);
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As oppose to React components, Reagent components in the most simplified form (also called as Form-1 component) are just Clojure functions that returns Clojure data in &lt;a href="https://github.com/weavejester/hiccup"&gt;Hiccup&lt;/a&gt; style.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defn welcome [props]
  [:h1 {} (:name props)])&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;There are other ways to define a Reagent component as described in the official documentation on &lt;a href="https://cljdoc.org/d/reagent/reagent/1.0.0/doc/tutorials/creating-reagent-components"&gt;Creating Reagent Components&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Although this may seem counter-intuitive, since I’m already calling it “component”, the Reagent component above is just a pure Clojure function and &lt;strong&gt;there is no more hidden magic behind it&lt;/strong&gt;. You can “invoke” it like any other functions in Clojure, and it’ll return a Hiccup markup without any surprise:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(welcome {:name &amp;quot;Steve&amp;quot;})
;; =&amp;gt; [:h1 {} &amp;quot;Steve&amp;quot;]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The returned markup data is plain Clojure data, no rendering, no reactivity, no magic, just pure Clojure data, persistent and immutable. Please be aware, in a Reagent app, seldom should you “invoke” the Reagent component like this. Instead, you should “render” it by explicitly invoking the &lt;code&gt;reagent.dom/render&lt;/code&gt; function to render the top-level Reagent component.&lt;/p&gt;
&lt;h2 id="rendering"&gt;Rendering&lt;/h2&gt;
&lt;p&gt;What the &lt;code&gt;reagent.dom/render&lt;/code&gt; function does is:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Compile the top level &lt;strong&gt;Reagent&lt;/strong&gt; component (and all the nested children components) into &lt;strong&gt;React&lt;/strong&gt; components,&lt;/li&gt;
&lt;li&gt;Invoke JS function &lt;code&gt;ReactDOM.render(...)&lt;/code&gt; with the compiled &lt;strong&gt;React&lt;/strong&gt; components to render the &lt;strong&gt;DOM&lt;/strong&gt; elements.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Or in the form of a flow chart:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Reagent       Compile   React        Render
Components    --------&amp;gt; Components   -------&amp;gt;  DOM
(Clojure Fns)           (JS Classes)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Most of the time, you don’t have to think about this because all components are Reagent components. Thus it’s easy to overlook the Reagent’s part in compiling the Clojure functions into React Components. &lt;em&gt;(This might be a reason why some other libraries prefer explicit macros to define a Component like rum’s &lt;code&gt;defc&lt;/code&gt; or fulcro’s &lt;code&gt;defsc&lt;/code&gt; - to make the compilation explicit to the user.)&lt;/em&gt; However, when it comes to interop with React component libraries, we need to start thinking more clearly about which components are React and which are Reagent.&lt;/p&gt;
&lt;h2 id="interop-with-react"&gt;Interop with React&lt;/h2&gt;
&lt;p&gt;The official website has an excellent article about &lt;a href="https://cljdoc.org/d/reagent/reagent/1.0.0/doc/tutorials/interop-with-react"&gt;Interop with React&lt;/a&gt;. Check it out if you aren’t so familiar with it. For my brief React interop history, I was almost exclusively using the &lt;code&gt;:&amp;gt;&lt;/code&gt; tag to render React component from the Reagent. However, things could get more tricky like the &lt;a href="https://cljdoc.org/d/reagent/reagent/1.0.0/doc/tutorials/interop-with-react#example-decorator-higher-order-components"&gt;Example: “Decorator” Higher-Order Components&lt;/a&gt;&lt;/p&gt;
&lt;h2 id="gotcha"&gt;Gotcha&lt;/h2&gt;
&lt;p&gt;Contrary to my instinct, &lt;code&gt;r/adapt-react-class&lt;/code&gt; isn’t the reverse of &lt;code&gt;r/reactify-component&lt;/code&gt;. That is, a React component won’t make it a round trip back to itself after threading through &lt;code&gt;r/adapt-react-class&lt;/code&gt; and &lt;code&gt;r/reactify-component&lt;/code&gt;. The &lt;code&gt;r/adapt-react-class&lt;/code&gt; takes a &lt;strong&gt;React component&lt;/strong&gt; and returns a &lt;code&gt;reagent.impl.template.NativeWrapper&lt;/code&gt;, whereas &lt;code&gt;r/reactify-component&lt;/code&gt; takes a &lt;strong&gt;Clojure callable&lt;/strong&gt; and coerce it into a React component. So be aware.&lt;/p&gt;
&lt;h2 id="example-stylized-material-ui-component"&gt;Example: Stylized Material UI Component&lt;/h2&gt;
&lt;p&gt;Below is the example I worked out for the &lt;a href="https://stackoverflow.com/q/66714919"&gt;StackOverflow question&lt;/a&gt;. Pay attention to the the calls to &lt;code&gt;r/adapt-react-class&lt;/code&gt; and &lt;code&gt;r/reactify-component&lt;/code&gt;. Since the MuiValueLabel component is a React component from the external library, we need to use &lt;code&gt;r/adapt-react-class&lt;/code&gt; so we can use it with the other Reagent library. The props value for &lt;code&gt;:ValueLabelComponent&lt;/code&gt; needs to be a React component because &lt;code&gt;slider&lt;/code&gt; is an adapted react class (just as the &lt;code&gt;mui-value-label&lt;/code&gt;), hence the function call to &lt;code&gt;r/reactify-component&lt;/code&gt;.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(ns example.core
  (:require
   [reagent-material-ui.core.slider :refer [slider]]
   [reagent-material-ui.styles :as styles]
   [reagent.core :as r]
   [reagent.dom :as rdom]
   [reagent.impl.util :as rutil]
   [&amp;quot;@material-ui/core/Slider/ValueLabel&amp;quot; :as MuiValueLabel]))

(def mui-value-label
  &amp;quot;The NativeWrapper of Material UI&amp;#39;s ValueLabel class.&amp;quot;
  (r/adapt-react-class (.-default MuiValueLabel)))

(def with-offsets
  &amp;quot;The higher-order component that provides 50px down and right offsets.&amp;quot;
  (styles/with-styles {:offset {:top 50 :left 50}}))

(defn value-label-with-offsets
  &amp;quot;A Reagent component that renders the MUI ValueLabel with offsets of 50px down
  and right.&amp;quot;
  [props]
  [(with-offsets mui-value-label) props])

(defn main
  &amp;quot;The top level Reagent component.&amp;quot;
  []
  [slider
   {:defaultValue        [31 37]
    :valueLabelDisplay   &amp;quot;on&amp;quot;
    :ValueLabelComponent (r/reactify-component
                           ;; Nay
                           #_(with-offsets mui-value-label)
                           ;; Ok
                           #_(fn [props] [(with-offsets mui-value-label) props])
                           ;; Yay
                           value-label-with-offsets)}])

(defn ^{:after-load true, :dev/after-load true}
  mount []
  (rdom/render [main] (js/document.getElementById &amp;quot;app&amp;quot;)))

(defn ^:export init []
  (mount))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is mentioned in the &lt;a href="#gotcha"&gt;Gotcha&lt;/a&gt;. The real tricky part is that &lt;code&gt;reagent-material-ui.styles/with-styles&lt;/code&gt; returns a &lt;code&gt;reagent.impl.template.NativeWrapper&lt;/code&gt; and &lt;code&gt;r/reactify-component&lt;/code&gt; cannot handle it like it handles Reagent components. (See the snippet below.) Therefore, I needed to wrapped it inside another function call to make it work.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(r/reactify-component
  ;; A reagent.impl.template.NativeWrapper
  (r/adapt-react-class
    (.-default MuiValueLabel)))
;; =&amp;gt; nil

(r/reactify-component
  ;; A inline Reagent component
  (fn [props]
    [(r/adapt-react-class
       (.-default MuiValueLabel))
     props]))
;; =&amp;gt; reagent&amp;lt;N&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case, it was extremely helpful to have a running REPL to help me figuring out the types of the components.&lt;/p&gt;
&lt;h2 id="epilogue"&gt;Epilogue&lt;/h2&gt;
&lt;p&gt;Spending time reading the Reagent source code was a lot of fun for me. Here I just want to share a few interesting functions I saw:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;reagent.impl.template&lt;/code&gt; NS: - &lt;code&gt;vec-to-elem&lt;/code&gt;: convert a vec into a JS React element via &lt;code&gt;make-element&lt;/code&gt; - &lt;code&gt;make-element&lt;/code&gt;: make a JS React element - &lt;code&gt;as-element&lt;/code&gt; - &lt;code&gt;valid-tag?&lt;/code&gt;: return true if a tag is a symbol, keyword, string, function, or NativeWrapper.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;reagent.impl.component&lt;/code&gt; NS: - &lt;code&gt;create-class&lt;/code&gt;: Creates JS class (that extends React.Component) based on provided Clojure map.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;reagent.impl.util&lt;/code&gt; NS: - &lt;code&gt;dash-to-prop-name&lt;/code&gt;: turn kebab-case prop names into camelCase.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/wake-up-2-hrs-earlier</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>How I wake up 2 hours earlier every day and become happier</title>
    <updated>2016-01-27T00:00:00Z</updated>
    <published>2016-01-27T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/wake-up-2-hrs-earlier" type="text/html"/>
    <content type="html">&lt;p&gt;Here’s how I kick off my workdays.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;&lt;em&gt;6:00 AM: the alarm went off. I allowed myself to stay in bed 5 more minutes to skim through my phone notifications and got up to do the 8 mins abs workout on my yoga mat.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;6:15 AM: I went to the bathroom to take a hot shower, and 5 minutes later, was looking in the mirror brushing my teeth (and also do some other stuffs I can do without clothes in the bathroom, like, shaving.)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;6:40 AM: I drizzled some oil on the hot pan and started frying an egg for my power breakfast.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;7:00 AM: took a moment to enjoy my power breakfast with a cup of fresh made pour over coffee. (Mmmmmmm.)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;7:15 AM: sit back at my desk and started my morning learning session.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;9:00 AM: time to hit the road! Great, the traffic is calmer now. I shall be in the office by 9:50. [Press the play button on my favorite Podcast]&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I was nothing like the person described above at all three months ago. What I’d like to tell you is the story of &lt;strong&gt;the routine I used to do three months ago&lt;/strong&gt; and &lt;strong&gt;what happens after adopting my new routine.&lt;/strong&gt;&lt;/p&gt;
&lt;h2 id="background"&gt;Background&lt;/h2&gt;
&lt;p&gt;A little bit story about myself. I’m a software developer working in the San Francisco Bay Area. Like lots of people based in the Bay Area, we commutes! And a lot! The commute between my office and my place without traffic is around 45 minutes oneway. However, if you happen to be courageous enough to go on highway during rush hour, guess what, 45 minutes is the time you spend stuck in the traffic with the speed a dog can easily walk pass you.&lt;/p&gt;
&lt;h2 id="my-old-routine"&gt;My old routine&lt;/h2&gt;
&lt;p&gt;The traffic is bad, so what? I avoid them. To hit the road at 9 AM, I used to wake up 8:30 in the morning and rushed out my door without eating breakfast. Like everyone else who enjoys sleeping and believe me I still am, I need at least 7 hours of sleep every day in order to gain enough energy for a day of work plus my noon workout routine (this is another story). So at this period of time, I went to bed around 1 AM, typically.&lt;/p&gt;
&lt;p&gt;Now looking back, I was consistently feeling pressures from work and life because I felt my free time was shrinking so much by the commute. Quite often I found myself working in my off time and tended to stay up late just to get more free time for work and myself. This system wasn’t working right for me.&lt;/p&gt;
&lt;h2 id="the-motivation"&gt;The motivation&lt;/h2&gt;
&lt;p&gt;I don’t have any legit reason to set up my mind for this change. It’s just one day I came up the crazy idea: “I’m going to challenge myself to wake up at 6 everyday for 21 days in a row because it sounds a healthy thing to do.” Just kidding, I was first inspired by this YouTube video — &lt;a href="https://www.youtube.com/watch?v=jjDmhNBtEfU"&gt;How To Develop A Kick Ass Morning Routine | 5 Tips For Starting Your Day&lt;/a&gt; . This video help me to gather some great ideas to design my morning routine from this video. I also made a mental note that if the challenge was completed, I’ll hang on to it and see how long could the streak goes on. (It’s 81 days BTW.)&lt;/p&gt;
&lt;h2 id="my-challenge-started"&gt;My challenge started&lt;/h2&gt;
&lt;p&gt;In order to get enough sleep, I forced myself to go to bed earlier than before at 11 PM. Like most challenges, &lt;strong&gt;you gotta push yourself and hang in there!&lt;/strong&gt; The hardest part for me was the weekends. While still going out late with friends I still need to wake up at 6 the next day because I don’t want to fail the challenge. On the craziest weekend I was partying out till 3 AM for two days in a row and still manage to go on a snowboard trip on the third day. Man, good old days.&lt;/p&gt;
&lt;p&gt;In order to get to bed by 11, I made one of the best decisions ever since working — not working after work hours. Why? Because I don’t have time after work anymore. On a normal day, I took off at 7 and get home by 8. After dinner, doing the dishes, cleaning up here and there, and maybe some video games, it’s almost 10 PM. Doing any sort of work an hour before sleep will cause my brain not wanting go to bed in time. Plus, with my extra 2 hours in the next morning I could catch them up later. Someone would call me if it is THAT urgent. My sleep quality boosted so much ever since.&lt;/p&gt;
&lt;p&gt;In the morning, I’d do a quick workout, any sort of workout. Since I’m already keeping a regular workout everyday at lunch time, I found the best workout I could do is for my abs. I tend to skip abs in my regular noon workout easily so why not tackle it the first thing in the morning? The last line sounds like an awesome gym motivation quote. Cool. [Self-five]&lt;/p&gt;
&lt;p&gt;About my power breakfast, there are three building blocks: proteins, carbs, and fruits. An example of my breakfast is english muffin with a fried egg, 2 slices of turkey breasts, lettuce, half of a avocado, lean cream cheese and 2 kiwis.&lt;/p&gt;
&lt;h2 id="result"&gt;Result&lt;/h2&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;More energy&lt;/strong&gt; — I don’t have any scientific fact to back me up but I feel much more energetic even with the same amount of sleep. Rarely do I feel sleepy during the workday now (except when my workout at noon is too intense.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;More time on the right tasks&lt;/strong&gt; — Instead of stuck in the traffic, now I’m using the best part of my entire day (morning!) to on the most valuable thing — learning (sometimes some urgent work). Driving is just a break before working.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Less pressure&lt;/strong&gt; — Instead of dealing with work late at night, dealing them in the morning gives me much more control of time and less pressure by the time I go to bed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Healthier&lt;/strong&gt; — I’m eating proper breakfast everyday!&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;To sum up all above, I’m a happier developer now!&lt;/strong&gt;&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/twitter-scraper-2</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Twitter scraper tutorial with Python: Requests, BeautifulSoup, and Selenium - Part 2</title>
    <updated>2016-04-09T00:00:00Z</updated>
    <published>2016-04-09T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/twitter-scraper-2" type="text/html"/>
    <content type="html">&lt;p&gt;This is the part 2 of my Twitter scraper tutorial. If you haven’t checkout part 1, the link is right here. In the last part, I left the tutorial with an unsolved problem — how to scrape the web page that uses infinite scrolling design? Two solutions came into my mind: one more sophisticated, the other more naive:&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h1 id="the-more-sophisticated-approach"&gt;The more sophisticated approach&lt;/h1&gt;
&lt;p&gt;In this approach, you need to understand how the infinite scrolling works. In the case of this tutorial, when the tweet search page loaded, none of the tweets contents were loaded at the time. It is the frontend javascript code that sends the HTTP request to get tweets from the server asynchronously, and manipulates the HTML file to render those tweets. This technology is called AJAX. You may find more information online if you are interested.&lt;/p&gt;
&lt;p&gt;Anyways, do you spot the flaw in the approach of part 1? The original HTTP request wasn’t the right request to get the tweets! It merely loads a page with right the javascript code, which load the tweets on the fly. So listen carefully: If you are able to track down the right HTTP request object, which gets the tweets result, the only thing left is to replace the original request with this one. Voila! This is my so-called more sophisticated approach. However, I didn’t go with this approach simply I didn’t spend the time to :P&lt;/p&gt;
&lt;h1 id="the-more-naive-approach"&gt;The more naive approach&lt;/h1&gt;
&lt;p&gt;Okay! This is the approach I want to show you. Think about the problem this way: no matter how sophisticated the website is designed, the end result is still a list of tweets loaded on your browser. So my so-called more naive approach is to focus on the end result only. if we could manipulate the browser to load those tweets for me, just as what we see normally, we could use the same the knowledge to parse the HTML file and get the tweets. To automate the browser for us, I’ll show you how I used Selenium.&lt;/p&gt;
&lt;p&gt;“Selenium automates browsers.” That’s what the official website says. Selenium Python bindings will help us to use Selenium using Python. Follow the installation page to install it. The code below tells Selenium to use Chrome to open up the Twitter search page and then move down the page for 5 times. Since the browser object provides the handy API to locate the tweets, we don’t need to use the BeautifulSoup again to parse the HTML file. You may run the script now:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()
base_url = u&amp;#39;https://twitter.com/search?q=&amp;#39;
query = u&amp;#39;%40dawranliou&amp;#39;
url = base_url + query

browser.get(url)
time.sleep(1)

body = browser.find_element_by_tag_name(&amp;#39;body&amp;#39;)

for _ in range(5):
    body.send_keys(Keys.PAGE_DOWN)
    time.sleep(0.2)

tweets = browser.find_elements_by_class_name(&amp;#39;tweet-text&amp;#39;)

for tweet in tweets:
    print(tweet.text)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you see the following error:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Don’t panic. Read the error message (don’t just google it blindly) and what’s wrong is that you are missing the ‘chromedriver’ executable file. It also suggest you to go to the website. How nice it is! Download the executable from the website given and put it under one of your PATH loacation. For me, I put it under my /usr/local/bin/ folder. You should be fine to run the script by now.&lt;/p&gt;
&lt;p&gt;This is the end of this tutorial! Hope you enjoy working with these amazing PyPI packages. Feel free to comment or contact me if you want to learn more. Happy learning! Cheers!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/how-i-built-bex</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>How I built Bex</title>
    <updated>2019-08-08T00:00:00Z</updated>
    <published>2019-08-08T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/how-i-built-bex" type="text/html"/>
    <content type="html">&lt;p&gt;In this article, I’d like to share with you the technologies and services that I use to create &lt;a href="https://bexdesign.io"&gt;Bex&lt;/a&gt;. If you are, and I assume you are, a programmer, Bex is simply a personal online markdown text editor.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h2 id="tldr"&gt;TL;DR&lt;/h2&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Site: &lt;a href="https://gohugo.io/"&gt;Hugo&lt;/a&gt; + vanilla JS, deployed to &lt;a href="https://www.netlify.com/"&gt;Netlify&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;App: &lt;a href="https://clojurescript.org/"&gt;ClojureScript&lt;/a&gt;, &lt;a href="https://cljdoc.org/d/re-frame/re-frame/0.10.8/doc/introduction"&gt;Re-frame&lt;/a&gt;, &lt;a href="https://shadow-cljs.github.io/docs/UsersGuide.html"&gt;Shadow CLJS&lt;/a&gt;, also deployed to &lt;a href="https://www.netlify.com/"&gt;Netlify&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Authentication and database: &lt;a href="https://firebase.google.com/"&gt;Firebase&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Payment: &lt;a href="https://stripe.com/docs/recipes/elements-react"&gt;Stripe&lt;/a&gt; + &lt;a href="https://www.netlify.com/docs/functions/"&gt;Netlify Functions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;(CSS: &lt;a href="https://www.netlify.com/"&gt;Tachyons&lt;/a&gt;!)&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="site-structure"&gt;Site structure&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;# Site:
https://bexdesign.io/
                    /pricing
                    /sign-up
                    /forgot-password
                    /resend-email
                    /blog/...
                    /...

# App:
https://app.bexdesign.io/
                        /log-in
                        /profile
                        /docs/:doc-id
                        /...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Above is the layout of the Site: I want my Site to have the Site part and the App part, separated by the subdomain. The App part is where the fun things are: all the business logic and the user interactions are here. The Site part is essential for SEO/marketing reasons. This part is for the search engine robots to crawl.&lt;/p&gt;
&lt;p&gt;Initially, the two parts are separated by pre-fixing all the App routes with &lt;code&gt;/a/&lt;/code&gt;. However, it didn’t work very well to switch routes between the Site and the App. For simplicity, I broke it down to two apps deployed separately.&lt;/p&gt;
&lt;p&gt;It’s also easier to write the redirect logic for the App:&lt;/p&gt;
&lt;pre class="toml"&gt;&lt;code&gt;# netlify.toml

[[redirects]]
  from = &amp;quot;/*&amp;quot;
  to = &amp;quot;/index.html&amp;quot;
  status = 200&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="the-site---static-site-generator"&gt;The Site - Static Site Generator&lt;/h2&gt;
&lt;p&gt;For the Site, I originally wrote all the HTML markup from scratch, page by page. For some share markups like the navbar and the footer, I copy-and-paste each one of them whenever I make some change.&lt;/p&gt;
&lt;p&gt;It worked well, and I love the simplicity of it, no build tool, just HTML, CSS, and some vanilla JS. After a while, I wanted to start blogging on the Site, and I know I won’t be able to hand-craft all the blog posts. I know a static site generator is a good option for me. What I need is to design the HTML layouts and fragments/partials once and let the tool build the Site for me.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.staticgen.com/"&gt;StaticGen&lt;/a&gt; is very resourceful for comparing static site generators. Most of them can deploy to Netlify.&lt;/p&gt;
&lt;p&gt;There were other static site generators I had used before, like Pelican, Jekyll, and Middleman. They all operate pretty similarly. I chose Hugo for this project mostly because I want to try a different one and see if I like it. Hugo is blazing fast, like instantaneously fast. The one thing I don’t like so far is that it always generates HTML files as index.html and put it under its folder. For example, the page &lt;code&gt;content/pricing.html&lt;/code&gt; will &lt;code&gt;become public/pricing/index.html&lt;/code&gt; after building it. The result is a trailing slash for all the pages like &lt;code&gt;&amp;lt;domain&amp;gt;/pricing/&lt;/code&gt; but I’d rather see &lt;code&gt;&amp;lt;docman&amp;gt;/pricing.html&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="the-app---clojure-clojurescript-and-the-ecosystem"&gt;The App - Clojure, ClojureScript, and the Ecosystem&lt;/h2&gt;
&lt;p&gt;I built the majority of the application with Clojure/Script. Clojure is currently my favorite programming language, so I was very tempted to build something useful with it. ClojureScript is a dialect of Clojure which compiles to JavaScript. Being a functional language, ClojureScript works exceptionally well with React, with the help of a few libraries.&lt;/p&gt;
&lt;p&gt;I use &lt;code&gt;Reagent&lt;/code&gt; to create and render the React components; &lt;code&gt;Re-frame&lt;/code&gt; to manage the application state; &lt;code&gt;Shadow Cljs&lt;/code&gt; to build the application and interop with the npm ecosystem.&lt;/p&gt;
&lt;p&gt;Since most tutorials on the web show you how to build applications with any language and any stack, I won’t get into too many details now for how I develop the App. For people getting into developing ClojureScript applications, I highly recommend &lt;span class="citation" data-cites="JacekSchae"&gt;[@JacekSchae]&lt;/span&gt;(https://twitter.com/JacekSchae)’s &lt;a href="https://www.jacekschae.com/learn-re-frame-pro/s8mby"&gt;Learn re-frame course&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="the-backend---authentication-and-database"&gt;The Backend - Authentication and Database&lt;/h2&gt;
&lt;p&gt;Firebase offers free plans if your App (actually mine) doesn’t have much traffic. Firebase offers pretty much everything I need for the application backend - authentication and a database. You can expect the normal authentication functions like sign up, sign in, and reset password flow to work with the Firebase SDK. It even takes care of the email services as well. The database I choose is a simple key-value store. For my application, I set the user id as the key and all the data associated with the user as the value. That way the database rule can be set this way to ensure only the user can read or write his/her own data:&lt;/p&gt;
&lt;pre class="json"&gt;&lt;code&gt;{
  &amp;quot;rules&amp;quot;: {
    &amp;quot;users&amp;quot;: {
      &amp;quot;$uid&amp;quot;: {
        &amp;quot;.write&amp;quot;: &amp;quot;$uid === auth.uid&amp;quot;,
        &amp;quot;.read&amp;quot;: &amp;quot;$uid === auth.uid&amp;quot;
      }
    }
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One caveat about the Firestore database is that it doesn’t save null as the value. If you assoc null as the value to the key, the database will remove the key. So at one time, I found that I need to serialize the user data into a string, and de-serialize it to retain the null values.&lt;/p&gt;
&lt;h2 id="payment-system"&gt;Payment System&lt;/h2&gt;
&lt;p&gt;Stripe handles my payments. For the SaaS product with a subscription plan, you’ll need to create the product and a subscription plan associated with the product. I did all these on the Stripe dashboard, but you can also do this programmatically.&lt;/p&gt;
&lt;p&gt;Once done, you should have a couple of keys that you need in your application:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Publishable key&lt;/li&gt;
&lt;li&gt;Secret key (KEEP THIS SECRET!)&lt;/li&gt;
&lt;li&gt;Plan id(s)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The subscription flow with all these keys is:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Create a credit-card token with &lt;a href="https://stripe.com/docs/stripe-js/elements/quickstart"&gt;Stripe Element&lt;/a&gt; and the publishable key (pk_*). Send the token to the backend.&lt;/li&gt;
&lt;li&gt;The backend uses the token with the secret key (sk_*) to create a customer.[1]&lt;/li&gt;
&lt;li&gt;The backend uses the customer id, the plan id, and the secret key (sk_*) to create a subscription.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The publishable key is for the frontend, and the secret key is for the backend because frontend can not hide the secret key. Thus, the backend is required here.[2] Here &lt;a href="https://www.netlify.com/products/functions/"&gt;Netlify Functions&lt;/a&gt; is the savior. I published a function that handles all the backend works for me and keeps the secret key in the environment variable.&lt;/p&gt;
&lt;p&gt;With the system in place, I still need to manage the user’s state of the subscription. There might be a better solution, but my strategy is to keep two values in the database:&lt;/p&gt;
&lt;pre class="json"&gt;&lt;code&gt;{
  &amp;quot;subscription-id&amp;quot;: &amp;quot;null|string&amp;quot;,
  &amp;quot;current-period-end&amp;quot;: &amp;quot;null|int&amp;quot;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are four situations/states for &lt;code&gt;["subscription-id", "current-period-end"]&lt;/code&gt; in this model:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;No subscription: &lt;code&gt;[null, null]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Currently subscribed: &lt;code&gt;[not-null, not-null]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Unsubscribed but has time left in current period: &lt;code&gt;[null, not-null]&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Every time the user logs in, if the &lt;code&gt;subscription-id&lt;/code&gt; exists, the backend makes a request to the Stripe and updates the &lt;code&gt;current-period-end&lt;/code&gt;.[3]&lt;/p&gt;
&lt;p&gt;[1] You can potentially reuse credit card information if you had created a customer instance before. However, I feel that way too many use cases to consider, so, to keep things simple, I recollect the credit card information every time the user resubscribes after unsubscribing.&lt;/p&gt;
&lt;p&gt;[2] Unless you are using &lt;a href="https://stripe.com/docs/payments/checkout"&gt;Stripe Checkout&lt;/a&gt;. Personally, I did not try it because I want to create the UI.&lt;/p&gt;
&lt;p&gt;[3] The documentation says it’s better to use a webhook in the backend and let Stripe to update the user’s &lt;code&gt;current-period-end&lt;/code&gt; when the renewal payment is successful. I might change to this strategy, but then I need to change the rules in the database to let my backend change the value without user signed in.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id="next"&gt;Next&lt;/h2&gt;
&lt;p&gt;This post is about the high-level architecture for this SaaS product. I hope this is useful for you. Next, I’d like to get into more detail about the ClojureScript app itself.&lt;/p&gt;
&lt;hr /&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/structural-editing-in-vanilla-emacs</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Structural editing in vanilla Emacs</title>
    <updated>2021-10-23T00:00:00Z</updated>
    <published>2021-10-23T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/structural-editing-in-vanilla-emacs" type="text/html"/>
    <content type="html">&lt;h2 id="strict-structural-editing"&gt;Strict structural editing&lt;/h2&gt;
&lt;p&gt;&lt;a href="/blog/back-to-paredit"&gt;Last time&lt;/a&gt; I switched from the &lt;a href="https://github.com/abo-abo/lispy"&gt;lispy&lt;/a&gt;/&lt;a href="https://github.com/noctuid/lispyville"&gt;lispyville&lt;/a&gt; combo for structural editing s-expressions to &lt;a href="https://www.emacswiki.org/emacs/ParEdit"&gt;paredit&lt;/a&gt; for its simplicity. However, I started to realize that I kept unbinding commands from the &lt;code&gt;paredit-mode-map&lt;/code&gt; such as &lt;code&gt;C-d&lt;/code&gt;, &lt;code&gt;C-k&lt;/code&gt; because they were unnecessarily restraining. Quote from this &lt;a href="https://www.reddit.com/r/emacs/comments/l7khmk/what_key_binding_scheme_do_you_use_to_handle/gl9fcqs?utm_source=share&amp;amp;utm_medium=web2x&amp;amp;context=3"&gt;reddit thread&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;I tend to think that all of the slurping, burping, gurgling, snorting, and barfing, which devotees consider handy, are just contrivances to try to make a virtue out of necessity. From the moment that you’ve automatically, prematurely introduced a closing paren, you naturally find a need to try to find a way to work around it. If you don’t box yourself in, in the first place, then there’s no such need.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I still do premature paren closing with &lt;code&gt;electric-pair-mode&lt;/code&gt; in my current setup. However, this thread really got me thinking. &lt;em&gt;“Do I really want to have balanced parenthesis at all times, at all costs?”&lt;/em&gt; To answer the question, I ask myself: a) What problems does it solves, and b) What are the costs?&lt;/p&gt;
&lt;p&gt;To me, the main cost is the freedom of expressing experimental code as I laid out in the &lt;a href="back-to-paredit"&gt;Back to paredit&lt;/a&gt; post.&lt;/p&gt;
&lt;p&gt;I think the main problem it solves is to &lt;strong&gt;“Avoid uncompilable source files by accident.”&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;However, I don’t care much about this problem nowadays since I don’t often edit the source code line-by-line or character-by-character and unbalanced parens are rarely an issue. Whenever I do accidentally introduce unbalanced parens, I can usually quickly spot the error and fix it&lt;a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;. It isn’t very hard once I learn to navigate and edit S-exps, which I’ll show in the next section.&lt;/p&gt;
&lt;p&gt;From there, it’s a simple decision to ditch paredit and the strict structural editing rules it imposes and revise my workflow with vanilla Emacs commands.&lt;a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2 id="s-expression-workflow-in-vanilla-emacs"&gt;S-expression workflow in vanilla Emacs&lt;/h2&gt;
&lt;p&gt;For the code examples in the following sections, I’ll be using &lt;code&gt;&amp;lt;!&amp;gt;&lt;/code&gt; as the &lt;em&gt;point&lt;/em&gt;, also known as the &lt;em&gt;cursor&lt;/em&gt; or the &lt;em&gt;caret&lt;/em&gt;, and &lt;code&gt;&amp;lt;@&amp;gt;&lt;/code&gt; as the &lt;em&gt;mark&lt;/em&gt;.&lt;/p&gt;
&lt;h3 id="navigate-s-exp"&gt;Navigate S-exp&lt;/h3&gt;
&lt;p&gt;Here are the ones I use most often: - &lt;code&gt;C-M-d&lt;/code&gt; - Go down the S-exp tree - &lt;code&gt;C-M-u&lt;/code&gt; - Go up the S-exp tree - &lt;code&gt;C-M-f&lt;/code&gt; - Go forward to the next S-exp at the same level - &lt;code&gt;C-M-b&lt;/code&gt; - Go backward to the previous S-exp at the same level - &lt;code&gt;C-M-a&lt;/code&gt; - Go to the start of the top-level S-exp (or the previous top-level S-exp) - &lt;code&gt;C-M-e&lt;/code&gt; - Go to the end of the top-level S-exp (or the next top-level S-exp)&lt;/p&gt;
&lt;p&gt;I don’t use these that often because they kinda overlap with &lt;code&gt;C-M-(f|b)&lt;/code&gt; in a way: - &lt;code&gt;C-M-n&lt;/code&gt; - Go to the next S-exp - &lt;code&gt;C-M-p&lt;/code&gt; - Go to the previous S-exp&lt;/p&gt;
&lt;p&gt;I often use the navigation commands to quickly put the point at the beginning of the S-exp or the end of the S-exp. This is quite important because the next few operations require the point to be at the right spot.&lt;/p&gt;
&lt;p&gt;Example (point is &lt;code&gt;&amp;lt;!&amp;gt;&lt;/code&gt;, mark is &lt;code&gt;&amp;lt;|&amp;gt;&lt;/code&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ (+ 1 2&amp;lt;!&amp;gt;) 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After hitting &lt;code&gt;C-M-u&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="mark-s-exp"&gt;Mark S-exp&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;C-M-&amp;lt;SPC&amp;gt;&lt;/code&gt; - &lt;code&gt;mark-sexp&lt;/code&gt; (Mark the S-exp after the point)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hit &lt;code&gt;C-M-&amp;lt;SPC&amp;gt;&lt;/code&gt; the first time will mark the first S-exp following the point, i.e. &lt;code&gt;(+ 1 2)&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2)&amp;lt;@&amp;gt; 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hit &lt;code&gt;C-M-&amp;lt;SPC&amp;gt;&lt;/code&gt; the second time will mark the next two S-exps, i.e. &lt;code&gt;(+ 1 2) 3&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3&amp;lt;@&amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="kill-s-exp"&gt;Kill S-exp&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;C-M-k&lt;/code&gt; - Kill S-exp after the point&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When I’m working on lispy languages, I rarely use &lt;code&gt;C-k&lt;/code&gt; to kill stuff. I use line-based navigation commands + the S-exp navigation commands to locate the opening paren than do &lt;code&gt;C-M-k&lt;/code&gt;. I found this method more precise than using &lt;code&gt;C-k&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After hitting &lt;code&gt;C-M-k&lt;/code&gt;,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt; 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="drag-s-exp"&gt;Drag S-exp&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;C-M-t&lt;/code&gt; - Drag downward&lt;/li&gt;
&lt;li&gt;&lt;code&gt;C-M-- C-M-t&lt;/code&gt; - Drag upward&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Dragging downward is almost equivalent to transposing. The only difference is that transposing requires the point to be after the S-exp to be dragged downward.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ (+ 1 2)&amp;lt;!&amp;gt; 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After hitting &lt;code&gt;C-M-t&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ 3 (+ 1 2)&amp;lt;!&amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the case of dragging upward, I usually kill the S-exp and then yank it to the position I want. Alternatively, using the negative argument with transposing does it too.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ 3 (+ 1 2)&amp;lt;!&amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After hitting &lt;code&gt;C-M-- C-M-t&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ (+ 1 2)&amp;lt;!&amp;gt; 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="wrap-s-exp"&gt;Wrap S-exp&lt;/h3&gt;
&lt;p&gt;This requires the &lt;code&gt;electric-pair-mode&lt;/code&gt;. To do wrapping, I’ll place the point at the beginning of the S-exp(s) that I want to wrap, press &lt;code&gt;C-M-&amp;lt;SPC&amp;gt;&lt;/code&gt; to mark the following few S-exp(s), and then hit the opening paren &lt;code&gt;(&lt;/code&gt; (or &lt;code&gt;"&lt;/code&gt;, &lt;code&gt;[&lt;/code&gt;, &lt;code&gt;{&lt;/code&gt;) to wrap the S-exp.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mark the next two S-exp by hitting &lt;code&gt;C-M-&amp;lt;SPC&amp;gt;&lt;/code&gt; twice&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3&amp;lt;@&amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hit &lt;code&gt;"&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;quot;&amp;lt;!&amp;gt;(+ 1 2) 3&amp;quot; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="raise-s-exp"&gt;Raise S-exp&lt;/h3&gt;
&lt;p&gt;By default, Emacs doesn’t bind the &lt;code&gt;raise-sexp&lt;/code&gt; to any keys. In my current setup, I bind this to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;C-M-r&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After hitting &lt;code&gt;C-M-r&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ 1 2)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="splice-s-exp"&gt;Splice S-exp&lt;/h3&gt;
&lt;p&gt;Splicing is really a special case of raising S-exp - basically, it “raises” all the sibling S-exps. So my workflow is to use &lt;code&gt;C-M-&amp;lt;SPC&amp;gt;&lt;/code&gt; to select all the siblings and then hit &lt;code&gt;C-M-r&lt;/code&gt; to raise all of them.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mark the next three S-exp with three &lt;code&gt;C-M-&amp;lt;SPC&amp;gt;&lt;/code&gt;s.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ &amp;lt;!&amp;gt;(+ 1 2) 3 4&amp;lt;@&amp;gt;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hit &lt;code&gt;C-M-r&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!&amp;gt;(+ 1 2) 3 4&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="slurp-barf"&gt;Slurp &amp;amp; barf&lt;/h3&gt;
&lt;p&gt;There are no equivalent commands out-of-the-box. However, I don’t miss those commands much. In the case of slurping, I can just remove the closing paren, forward one S-exp, and then insert the closing paren back:&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ (+ 1 2)&amp;lt;!&amp;gt; 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;DEL&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ (+ 1 2&amp;lt;!&amp;gt; 3 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;C-M-f&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ (+ 1 2 3&amp;lt;!&amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Insert &lt;code&gt;)&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(+ (+ 1 2 3)&amp;lt;!&amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternatively, kill the next S-exp and yank it before the closing paren.&lt;a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;I think the more I work on lispy languages, the better I become at working with S-exps. Previously, I had to rely on the external packages’ safety nets to edit the source code safely. Nowadays, I think I’m dangerous enough that I feel more productive without those safety nets. &#128520;&lt;/p&gt;
&lt;p&gt;I think my experiment so far has been a success. I’ve been using the revised workflows for my day-to-day work for a while, and vanilla Emacs is all I need to be productive at navigating and editing lispy code.&lt;a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2 id="footnotes"&gt;Footnotes&lt;/h2&gt;
&lt;section class="footnotes" role="doc-endnotes"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn1" role="doc-endnote"&gt;&lt;p&gt;With the help of &lt;code&gt;M-x check-parens&lt;/code&gt; and &lt;code&gt;show-paren-mode&lt;/code&gt;.&lt;a href="#fnref1" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn2" role="doc-endnote"&gt;&lt;p&gt;I also came across the blog &lt;a href="https://andreyorst.gitlab.io/posts/2021-09-30-why-is-paredit-is-so-un-emacsy/"&gt;Why is Paredit is so un-Emacsy?&lt;/a&gt; after the switch. It’s a nice read! It kinda reassured me of my decision.&lt;a href="#fnref2" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn3" role="doc-endnote"&gt;&lt;p&gt;I might be able to write a function to automate slurping and barfing in the future. Stay tuned!&lt;a href="#fnref3" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn4" role="doc-endnote"&gt;&lt;p&gt;I also ditched evil-mode and learned code editing the Emacs way. That’s a story for another time.&lt;a href="#fnref4" class="footnote-back" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/getting-started-python-internals</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Getting Started with Python Internals</title>
    <updated>2017-02-20T00:00:00Z</updated>
    <published>2017-02-20T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/getting-started-python-internals" type="text/html"/>
    <content type="html">&lt;p&gt;This article is a summary of what I learned from &lt;a href="https://twitter.com/pgbovine"&gt;Philip Guo&lt;/a&gt;’s &lt;a href="http://pgbovine.net/cpython-internals.htm"&gt;CPython internals: A ten-hour codewalk through the Python interpreter source code&lt;/a&gt;. I highly recommend you to go through his course. He go through great materials in his videos. You can think of this article as a companion text version of his course, so you can come back for your own references. The only major difference between Philip Guo’s course and this article is the Python version. In his course he was using 2.7.8. This article I’m using the 3.6.0 code. In this article, you’ll know the very basic things about Python internals, and, hopefully, be able to explore the Python internals on your own.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h1 id="what-does-cpython-do-to-my-code"&gt;What does (C)Python do to my code?&lt;/h1&gt;
&lt;p&gt;You might have heard people tell you Python is a interpreted language. You give the Python interpreter your sourcecode, and boom, the interpreter spits out the output.&lt;/p&gt;
&lt;p&gt;However, this might be a little bit confusing, but Python &lt;strong&gt;does compile your code&lt;/strong&gt;. Instead of the one step to get from the sourcecode to the output, Python compiles your sourcecode into an easier format - bytecodes, for the Python virtual machine. Then the interpreter program consumes the bytecode and act on it. We’ll be focusing on the later part where we get from bytecode to the output.&lt;/p&gt;
&lt;p&gt;Here’s a simple diagram:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;source code  |                (C)Python                   |       output
             |                                            |
  test.py   ---&amp;gt;  compiler -&amp;gt; [bytecode] -&amp;gt; interpreter  ---&amp;gt; &amp;#39;Hello World!&amp;#39;
                                   ^                                ^
                                   |                                |
                                   |                                |
                                   ----------------------------------
                                        This is more interesting&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id="how-does-the-cpython-project-look-like"&gt;How does the CPython project look like?&lt;/h1&gt;
&lt;p&gt;Main subdirectories in the CPython project:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;code&gt;Include/&lt;/code&gt; - all the .h (header) files where the interfaces are defined&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Objects/&lt;/code&gt; - the C code that represents Python objects&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Python/&lt;/code&gt; - the main Python runtime&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Other subdirectories:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;code&gt;Modules/&lt;/code&gt; - built-in modules implemented in C&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Libs/&lt;/code&gt; - standard libraries implemented in Python&lt;/li&gt;
&lt;/ol&gt;
&lt;h1 id="python-bytecode-and-the-disassembler"&gt;Python bytecode and the disassembler&lt;/h1&gt;
&lt;p&gt;Let’s define our testing module:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;# test.py
x = 1
y = 2
z = x + y
print(z)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In Python’s interactive interpreter, we can invoke the built-in function: &lt;a href="https://docs.python.org/3/library/functions.html#compile"&gt;&lt;code&gt;compile&lt;/code&gt;&lt;/a&gt;, and get the code object of this module.&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;c = compile(open(&amp;#39;test.py&amp;#39;).read(), &amp;#39;test.py&amp;#39;, &amp;#39;exec&amp;#39;)
# &amp;lt;code object &amp;lt;module&amp;gt; at 0x..., file &amp;quot;test.py&amp;quot;, line 1&amp;gt;

c.co_code
# b&amp;#39;d\x00Z\x00d\x01Z\x01e\x00e\x01\x17\x00Z\x02e\x03e\x02\x83\x01\x01\x00d\x02S\x00&amp;#39;

[byte for byte in c.co_code]
# [100, 0, 90, 0, 100, 1, 90, 1, 101, 0, 101, 1, 23, 0, 90, 2, 101, 3, 101, 2, 131, 1, 1, 0, 100, 2, 83, 0]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The above code is the bytecode representation of our original sourcecode. However, looking at those numbers do not really help unless you are a Python guru. Fortunately, in Python’s standard library there’s a module called &lt;code&gt;dis&lt;/code&gt;, which would translate those byte codes for us.&lt;/p&gt;
&lt;p&gt;To disassemble the Python module, run &lt;code&gt;$ python3 -m dis test.py&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  1           0 LOAD_CONST               0 (1)
              2 STORE_NAME               0 (x)

  2           4 LOAD_CONST               1 (2)
              6 STORE_NAME               1 (y)

  3           8 LOAD_NAME                0 (x)
             10 LOAD_NAME                1 (y)
             12 BINARY_ADD
             14 STORE_NAME               2 (z)

  4          16 LOAD_NAME                3 (print)
             18 LOAD_NAME                2 (z)
             20 CALL_FUNCTION            1
             22 POP_TOP
             24 LOAD_CONST               2 (None)
             26 RETURN_VALUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The format for the disassembled code is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;line_number_in_sourcecode -&amp;gt; byte_offset OP_CODE -&amp;gt; internal_book_keeping_stuff (argument_name)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The byte code is mapped to this disassembled code, somehow, with some optimization. Thus, it’s not very obvious to me how to decode each byte code to which line of the disassembler output. So for now, we’ll be sticking with the more readable disassembler output.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;If you are interested in how the disassembler works, module &lt;code&gt;dis&lt;/code&gt; is located at &lt;code&gt;/Lib/dis.py&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;h1 id="python-is-a-stack-machine"&gt;Python is a Stack Machine&lt;/h1&gt;
&lt;p&gt;&lt;em&gt;If you could quite understand the disassembler output, feel free to skip this section.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Before we jump into the disassembled code above, you need to know - Python virtual machine is a “Stack Machine.” Python internally keeps track of a “Value Stack,” which stores all the values for the upcoming operations to use. If you still don’t have any idea what a value stack is about, imaging Python is a lazy guy who always grabs the top-most T-shirt from his drawer. When he has more clean T-shirts, he simply stacks them on top of the other T-shirts. This guy sometimes may grab an extra T-shirt to go to the gym, sometimes may take several T-shirt for donation, or he may do any action with his T-shirts, but he is very discipline about picking the top-most T-shirt first. This guy is a Stack Machine.&lt;/p&gt;
&lt;p&gt;Let’s look at the disassembled code above. Without knowing the internal, we could sort of guess what’s happening in the Python virtual machine already:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;When a const is loaded by calling &lt;code&gt;LOAD_CONST&lt;/code&gt;, the value is pushed onto the Value Stack.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When &lt;code&gt;STORE_NAME&lt;/code&gt; is called, the last value on the Value Stack is popped and saved in the memory associated with the variable name, &lt;code&gt;x&lt;/code&gt; for example. the &lt;code&gt;0&lt;/code&gt; in line &lt;code&gt;3 STORE_NAME 0 (x)&lt;/code&gt; indicates that name &lt;code&gt;x&lt;/code&gt; is the 0th variable name.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;LOAD_NAME&lt;/code&gt; pushes whatever value the variable name is associated with on top of the Value Stack. (Only the reference of the value is pushed. So now the value has the Reference Counting of 2. One from the variable name, another from the Value Stack.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;BINARY_ADD&lt;/code&gt; pops the two values from the Value Stack and pushes the result on top of the Value Stack again.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;CALL_FUNCTION&lt;/code&gt; calls the &lt;code&gt;print&lt;/code&gt; function and use &lt;code&gt;z&lt;/code&gt; as its argument. (In legacy Python, or Python 2, &lt;code&gt;print&lt;/code&gt; was a primitive operation and has its own opcode.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For completeness, the module returns a &lt;code&gt;None&lt;/code&gt; value.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;TODO add diagrams to help explaining each step&lt;/em&gt;&lt;/p&gt;
&lt;h1 id="python-opcode"&gt;Python opcode&lt;/h1&gt;
&lt;p&gt;We sort of guess our way through the disassembled code. Let’s see how they are formally defined in CPython.&lt;/p&gt;
&lt;p&gt;First look at &lt;code&gt;/Include/opcode.h&lt;/code&gt;. This file defines all the Python opcodes, which Python could act upon. For example, line 78:&lt;/p&gt;
&lt;pre class="c"&gt;&lt;code&gt;#define LOAD_CONST              100&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This defines the opcode for &lt;code&gt;LOAD_CONST&lt;/code&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;#define&lt;/code&gt; is the definition of a macro in C language. For example &lt;code&gt;#define LOAD_CONST 100&lt;/code&gt;. This macro means to replace every occurrence of &lt;code&gt;LOAD_CONST&lt;/code&gt; with &lt;code&gt;100&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;One interesting opcode to notice is in line 68, &lt;code&gt;HAVE_ARGUMENT&lt;/code&gt;. This opcode is just a placeholder. Any opcode include and above 90 takes argument(s).&lt;/p&gt;
&lt;h2 id="main-interpreter-loop"&gt;Main Interpreter Loop&lt;/h2&gt;
&lt;p&gt;Now let’s see file &lt;code&gt;/Python/ceval.c&lt;/code&gt;. Line 721 is the start of the gigantic interpreter main function, which ends at line 3692:&lt;/p&gt;
&lt;pre class="c"&gt;&lt;code&gt;PyObject *
_PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag)
{
...
} // line 3692&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To understand this function:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Return type - Everything in Python is an object, an &lt;code&gt;PyObject&lt;/code&gt; object in CPython code.&lt;/li&gt;
&lt;li&gt;Input argument - A &lt;code&gt;PyFrameObject&lt;/code&gt; is a piece of Python code.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;One object worth noticing in this function is &lt;code&gt;PyObject **stack_pointer&lt;/code&gt; in line 727. This object is a list of pointers pointing to the Value Stack, which we mentioned previously.&lt;/p&gt;
&lt;p&gt;This is it, line 1108, the start of the main interpreter loop! This is the start of the infinite loop to go through the bytecode. This main interpreter loop ends at line 3614:&lt;/p&gt;
&lt;pre class="c"&gt;&lt;code&gt;    for (;;) {
        ...
    } /* main loop */  // Line 3614&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now see line 1220, a GIANT switch case that tells you what C code to operate for each opcode case:&lt;/p&gt;
&lt;pre class="c"&gt;&lt;code&gt;        switch (opcode) {
            ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Line 3528, breaking out of the main interpreter loop:&lt;/p&gt;
&lt;pre class="c"&gt;&lt;code&gt;fast_block_end:
        assert(why != WHY_NOT);
        ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Line 3691, return of the main function:&lt;/p&gt;
&lt;pre class="c"&gt;&lt;code&gt;    return _Py_CheckFunctionResult(NULL, retval, &amp;quot;PyEval_EvalFrameEx&amp;quot;);
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And that is the structure of your CPython runtime! Now you know how to look at the CPython code to figure out what’s happening internally when your code is executing. For example, you can locate the switch case for &lt;code&gt;LOAD_CONST&lt;/code&gt; in line 1244 to see what’s happening when this opcode is used:&lt;/p&gt;
&lt;pre class="c"&gt;&lt;code&gt;        TARGET(LOAD_CONST) {
            PyObject *value = GETITEM(consts, oparg);
            Py_INCREF(value);
            PUSH(value);
            FAST_DISPATCH();
        }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What it does in high level is:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Gets the value&lt;/li&gt;
&lt;li&gt;Increase the reference count of the value by 1&lt;/li&gt;
&lt;li&gt;Push the value on top of the Value Stack&lt;/li&gt;
&lt;/ol&gt;
&lt;h1 id="recap"&gt;Recap&lt;/h1&gt;
&lt;p&gt;Let’s recap some key points in this article:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Python does compile your sourcecode.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;$ python3 -m dis &amp;lt;YOUR_PYTHON_FILE&amp;gt;&lt;/code&gt; to disassemble your code.&lt;/li&gt;
&lt;li&gt;Python is a stack machine.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;/Include/opcode.h&lt;/code&gt; has all the opcodes defined.&lt;/li&gt;
&lt;li&gt;CPython runtime’s main interpreter loop locates in &lt;code&gt;/Python/ceval.c&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The main interpreter loop is a giant switch case in an infinite loop.&lt;/li&gt;
&lt;/ol&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/40-books-in-2016</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>40 Books I Read in 2016</title>
    <updated>2017-01-04T00:00:00Z</updated>
    <published>2017-01-04T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/40-books-in-2016" type="text/html"/>
    <content type="html">&lt;p&gt;I challenged myself to read 10 books this year and I ended up reading 40 of them. Phew. What a great year, 2016! I really picked up this new-found hobbit of reading. Feel free to add me friends on &lt;a href="https://www.goodreads.com/user/show/62701324-daw-ran-liou"&gt;Goodread&lt;/a&gt; to see which book I’m currently reading. Let’s read more! Here’s my top 5 picks in 2016:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Mistborn: The Final Empire (#33)&lt;/li&gt;
&lt;li&gt;Soft Skills - The Software Developer’s Life Manual (#2)&lt;/li&gt;
&lt;li&gt;The 4-hour Work Week (#29)&lt;/li&gt;
&lt;li&gt;The Martian (#14)&lt;/li&gt;
&lt;li&gt;Ready Player One (#15)&lt;/li&gt;
&lt;/ol&gt;
&lt;!-- more --&gt;
&lt;h3 id="the-lean-startup"&gt;1. The Lean Startup&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1333576876m/10127019.jpg" alt="alt the-lean-startup" /&gt;&lt;figcaption aria-hidden="true"&gt;alt the-lean-startup&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I think I’ve been exposed to the “lean” concept a lot from day to day. When I read the book, it wasn’t a big surprise to me.&lt;/p&gt;
&lt;h3 id="soft-skills---the-software-developers-life-manual"&gt;2. Soft Skills - The Software Developer’s Life Manual&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1419180921m/23232941.jpg" alt="alt soft-skills" /&gt;&lt;figcaption aria-hidden="true"&gt;alt soft-skills&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;THE single most influential book to me. This book talks every aspect of life but software development.&lt;/p&gt;
&lt;h3 id="flask-web-development"&gt;3. Flask Web Development&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1390432971m/18774655.jpg" alt="alt flask-web-dev" /&gt;&lt;figcaption aria-hidden="true"&gt;alt flask-web-dev&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This book really gives me a great foundation of developing Flask app. Before I read this book, I was jumping around the online tutorials but they didn’t work out for me.&lt;/p&gt;
&lt;h3 id="how-to-win-friends-influence-people"&gt;4. How to Win Friends &amp;amp; Influence People&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1442726934m/4865.jpg" alt="alt win-firends" /&gt;&lt;figcaption aria-hidden="true"&gt;alt win-firends&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is yet another very influential book. This classic book helps me to improve my social life and my friendships.&lt;/p&gt;
&lt;h3 id="the-millionaire-real-estate-investor"&gt;5. The Millionaire Real Estate Investor&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1417407442m/136205.jpg" alt="alt millionaire-real-estate" /&gt;&lt;figcaption aria-hidden="true"&gt;alt millionaire-real-estate&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is a great investment book. Not only did it change the way I thought about investing in real estate, but also give you a concrete plan for investing. However, the concrete plan part of the book is kind of hard to digest for me.&lt;/p&gt;
&lt;h3 id="the-war-of-art"&gt;6. The War of Art&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1388176109m/1319.jpg" alt="alt war-of-art" /&gt;&lt;figcaption aria-hidden="true"&gt;alt war-of-art&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This classic book helps me to understand one of my worst enemy - procrastination. However, reading the book was like being lectured, which I don’t typically enjoy.&lt;/p&gt;
&lt;h3 id="the-autobiography-of-benjamin-franklin"&gt;7. The Autobiography of Benjamin Franklin&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1428170518m/52309.jpg" alt="alt ben-franklin" /&gt;&lt;figcaption aria-hidden="true"&gt;alt ben-franklin&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Benjamin Franklin is such a fascinating person that I need to read his autobiography to know him.&lt;/p&gt;
&lt;h3 id="rich-dad-poor-dad"&gt;8. Rich Dad Poor Dad&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1388211242m/69571.jpg" alt="alt rick-dad-poor-dad" /&gt;&lt;figcaption aria-hidden="true"&gt;alt rick-dad-poor-dad&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Another very influential book that changed the way I think about money.&lt;/p&gt;
&lt;h3 id="the-power-of-habit"&gt;9. The Power of Habit&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1366758683m/12609433.jpg" alt="alt power-of-habit" /&gt;&lt;figcaption aria-hidden="true"&gt;alt power-of-habit&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Habit is one of the most important that dominates our daily lives without being notice. To understand it and be able to change it is so powerful that benefits all aspects of our lives.&lt;/p&gt;
&lt;h3 id="think-and-grow-rich"&gt;10. Think and Grow Rich&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1463241782m/30186948.jpg" alt="alt think-grow-rich" /&gt;&lt;figcaption aria-hidden="true"&gt;alt think-grow-rich&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;A classic book. It’s amazing how often I heard about this book from various people. The book’s content is too hard for me to digest. Need to read it again.&lt;/p&gt;
&lt;h3 id="you-are-a-badass"&gt;11. You are a Badass&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1351539051m/15843166.jpg" alt="alt badass" /&gt;&lt;figcaption aria-hidden="true"&gt;alt badass&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is a very motivating and fun book. Love yourself and others!&lt;/p&gt;
&lt;h3 id="the-end-of-jobs"&gt;12. The End of Jobs&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1438463792m/25827122.jpg" alt="alt end-of-jobs" /&gt;&lt;figcaption aria-hidden="true"&gt;alt end-of-jobs&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I highly recommend this book! It changed a lot how I think about career. Its target audience it not specific to software engineers (unlike Soft Skills, my bible) so go read it everyone!&lt;/p&gt;
&lt;h3 id="year-of-yes"&gt;13. Year of Yes&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1443552148m/25690958.jpg" alt="alt year-of-yes" /&gt;&lt;figcaption aria-hidden="true"&gt;alt year-of-yes&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Shonda Rhimes told about the amazing story of her Year of Yes.&lt;/p&gt;
&lt;h3 id="the-martian-2nd-time"&gt;14. The Martian (2nd time!)&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1413706054m/18007564.jpg" alt="alt martian" /&gt;&lt;figcaption aria-hidden="true"&gt;alt martian&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is the FIRST EVER book that I read twice in such a short period of time. This book is witty, is fun, and is full of science! If you like the movie you’ll definitely enjoy the book, I promise! Some of the best parts are in the book only. This is definitely one of my all-time favorites.&lt;/p&gt;
&lt;h3 id="ready-player-one-2nd-time"&gt;15. Ready Player One (2nd time!)&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1406383612m/9969571.jpg" alt="alt ready-player-one" /&gt;&lt;figcaption aria-hidden="true"&gt;alt ready-player-one&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is the SECOND EVER book that I read twice in such short period of time. It’s full of imaginations and excitements! I enjoyed every moment reading it. Of course it’s one of my all-time favorites too!&lt;/p&gt;
&lt;h3 id="pitch-anything"&gt;16. Pitch Anything&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1347796457m/10321016.jpg" alt="alt pitch-anything" /&gt;&lt;figcaption aria-hidden="true"&gt;alt pitch-anything&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I have the audio book version of it. It’s always enjoyable listening to the author reading his/her own book. A lot of parts in the book is sort of irrelevant to me, but some of the pitches he made were just so crazily enchanting.&lt;/p&gt;
&lt;h3 id="the-hitchhikers-guide-to-the-galaxy"&gt;17. The Hitchhiker’s Guide to the Galaxy&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1327656754m/11.jpg" alt="alt hitchhikers-guide" /&gt;&lt;figcaption aria-hidden="true"&gt;alt hitchhikers-guide&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Classic sci-fi book. I don’t always get its jokes but it’s a fun read.&lt;/p&gt;
&lt;h3 id="so-good-they-cant-ignore-you"&gt;18. So Good They Can’t Ignore You&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1360564614m/13525945.jpg" alt="alt so-good-they-cant-ignore-you" /&gt;&lt;figcaption aria-hidden="true"&gt;alt so-good-they-cant-ignore-you&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I highly recommend this book even though I haven’t finished it. This book breaks the wide-spread “follow your passion” mindset about our dream jobs. Instead, it focused on the craftsmanship mindset.&lt;/p&gt;
&lt;h3 id="the-7-habits-of-highly-effective-people"&gt;19. The 7 Habits of Highly Effective People&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1421842784m/36072.jpg" alt="alt 7-habits" /&gt;&lt;figcaption aria-hidden="true"&gt;alt 7-habits&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is one of the best self development books I’ve read and the lessons I learned from it really apply to everyone. In stead of thinking in efficiency, this book focuses on the ‘effectiveness’ of the work you do. It’s a subtle mind shift, but it definitely helped making the decisions for where should you put the energies in. Even after fist published 25 years ago, the advices are still so relevant these days. No wonder this is a classic book of its genre. I love this book and bought a hard copy with me for reference.&lt;/p&gt;
&lt;h3 id="how-to-talk-to-anyone"&gt;20. How to Talk to Anyone&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1388184197m/35210.jpg" alt="alt how-to-talk-to-anyone" /&gt;&lt;figcaption aria-hidden="true"&gt;alt how-to-talk-to-anyone&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;It’s a fun read but not so much I could grabbed on after reading it. The book’s goal is to bridge the gap where Dale Carnegie’s How to Win Friends and Influence People, which published 80 years ago, didn’t tell the people living in the 21st century what to do. I love hearing about all the fun stories in the book.&lt;/p&gt;
&lt;h3 id="the-like-switch"&gt;21. The Like Switch&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1421037599m/21412226.jpg" alt="alt like-switch" /&gt;&lt;figcaption aria-hidden="true"&gt;alt like-switch&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I enjoyed this book better than How to Talk to Anyone, even though the feelings I had to this book is somewhat similar to the other. It might be because the author was a former FBI agent and the stories was much more intrigue to me.&lt;/p&gt;
&lt;h3 id="quiet---the-power-of-introverts-in-a-world-that-cant-stop-talking"&gt;22. Quiet - The Power of Introverts in a World That Can’t Stop Talking&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1328562861m/8520610.jpg" alt="alt quiet" /&gt;&lt;figcaption aria-hidden="true"&gt;alt quiet&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I’ve never felt so much connection to a book. This is yet another phenomenal book I’ve read. I learned so much about myself after reading it. I feel so much appreciation for Susan Cain, the author, for putting up the effort researching about the topic that’s so relevant to half of the population in this world. This book has saved me from being doubt about a big part of myself.&lt;/p&gt;
&lt;h3 id="lean-in"&gt;23. Lean in&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1364250803m/16071764.jpg" alt="alt lean-in" /&gt;&lt;figcaption aria-hidden="true"&gt;alt lean-in&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is a great book that I think everyone should read. To me the book is about understanding, and supporting each other. Not only it’s applicable for female, but also the minority groups. Learning from Sheryl Sandburg’s marriage, I am more certain than ever that parents could both be successful in their career and also have a great family.&lt;/p&gt;
&lt;h3 id="hackers-heroes-of-the-computer-revolution"&gt;24. Hackers: Heroes of the Computer Revolution&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1435697935m/56829.jpg" alt="alt hackers" /&gt;&lt;figcaption aria-hidden="true"&gt;alt hackers&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Reading the history of generations of hackers is like THE history of computer. It was the hackers that drove the entire computer revolutions. (&lt;em&gt;Respects&lt;/em&gt;) I’d like to recommend this book to anyone who’s in the software/computer industry.&lt;/p&gt;
&lt;h3 id="the-personal-mba"&gt;25. The Personal MBA&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1348014445m/9512985.jpg" alt="alt personal-mba" /&gt;&lt;figcaption aria-hidden="true"&gt;alt personal-mba&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Having a technical backgraound, I know so little about business side and this book is perfect for peoople like me to start thinking in business. Now I need to turn those knowledges into actions. Recommend to all the tech fellows.&lt;/p&gt;
&lt;h3 id="getting-to-yes"&gt;26. Getting to Yes&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1442289862m/313605.jpg" alt="alt getting-to-yes" /&gt;&lt;figcaption aria-hidden="true"&gt;alt getting-to-yes&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Seek mutual benefits and always aim for win-win.&lt;/p&gt;
&lt;h3 id="the-hard-thing-about-hard-things"&gt;27. The Hard Thing about Hard Things&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1386609333m/18176747.jpg" alt="alt hard-thing" /&gt;&lt;figcaption aria-hidden="true"&gt;alt hard-thing&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The book’s first part tells the CRAZY startup story of Ben Horowitz. Reading his words, I was so terrified and yet amazed by all the things he’d been through. In the rests of the book, Ben explained what the hard things are and what he’d learned from it. I am full of respect to the author and anyone starting a company.&lt;/p&gt;
&lt;h3 id="the-richest-man-in-babylon"&gt;28. The Richest Man in Babylon&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1348336780m/1052.jpg" alt="alt richest-man-in-babylon" /&gt;&lt;figcaption aria-hidden="true"&gt;alt richest-man-in-babylon&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Full of wise thoughts about personal finance. My favorite quote is &lt;em&gt;“A part of what I earned is mine to keep.”&lt;/em&gt; Pay yourself first when you get the paycheck, instead of paying the merchants. Financial education is so important yet totally missed-out in our education. Glad that I start gaining more knowledge about it.&lt;/p&gt;
&lt;h3 id="the-4-hour-work-week"&gt;29. The 4-hour Work Week&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1394578573m/6444424.jpg" alt="alt 4-hour" /&gt;&lt;figcaption aria-hidden="true"&gt;alt 4-hour&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is one of my favorites. I can’t tell you how much my mind was blown by this book. Recommended by my brother, I read this book back-to-back twice and wished every word would be memorized by heart. “The End of Jobs” tells the importance of having one’s own business, and this book tells you exactly how. This is THE book that completely change the course of my life.&lt;/p&gt;
&lt;h3 id="the-willpower-instinct"&gt;30. The Willpower Instinct&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1436737104m/10865206.jpg" alt="alt willpower-instinct" /&gt;&lt;figcaption aria-hidden="true"&gt;alt willpower-instinct&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Understanding what willpower is and how does it work have such an impact to my life. Willpower is like superpower that we all have. Understand it and utilize it properly makes us all superheroes. &lt;em&gt;(Side note: I was reading the Mistborn trilogy on the side while reading The Willpower Instinct. A fun idea came to me. The willpowers are like Mistings’ Allomancy powers. Every time you draw willpower to face challenges, you burn a bit of your willpower reserves away. There’re certain way you can do to recharge willpower, but if you don’t use them wisely, they’ll be burned out very quickly.)&lt;/em&gt;&lt;/p&gt;
&lt;h3 id="trump-the-art-of-the-deal"&gt;31. Trump: The Art of The Deal&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1442705949m/1032.jpg" alt="alt the-art-of-the-deal" /&gt;&lt;figcaption aria-hidden="true"&gt;alt the-art-of-the-deal&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Get’s a sneak peak into Donal Trump’s mind. This person is a great businessman with a great mind. I’m giving him more respect after reading this book.&lt;/p&gt;
&lt;h3 id="the-e-myth-revisited"&gt;32. The E-myth Revisited&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1435673032m/81948.jpg" alt="alt e-myth-revisited" /&gt;&lt;figcaption aria-hidden="true"&gt;alt e-myth-revisited&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is a great companion book for The 4-hour Work Week. This book explained about the “E-myth”, the Entrepreneur Myth, for most technician-changed entrepreneur. The product of a business isn’t the real product of an entrepreneur. It is the business itself that is the real product of an entrepreneur. The product of business is just a bi-product of good business. There’s a distinction between good product and good business. Good product does not necessary lead to good business.&lt;/p&gt;
&lt;h3 id="mistborn-the-final-empire"&gt;33. Mistborn: The Final Empire&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1314601971m/6547258.jpg" alt="alt mistborn-1" /&gt;&lt;figcaption aria-hidden="true"&gt;alt mistborn-1&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;No doubt this is the my favorite novel of the year! OMG I’ve never enjoyed a novel this much, and yet this is my very first book in the high-fantasy genre. I’ll definitely read more fantasy books in the future.&lt;/p&gt;
&lt;p&gt;This book completely blew my mind away! That was the most satisfying reading experience one could get. Brandon Sanderson is a genius. The fantasy world he created was simply amazing - its well-thought magic system was the reason I first start reading the book but it was the characters and the twisted plots that stopped me from putting it down! It’s full of tensions and OMG-that-did-not-just-happened throughout the book. I literary cried at a very emotional moment. I never cried over a book before. That how great it is.&lt;/p&gt;
&lt;p&gt;It’s the longest book I read in ages but I totally enjoyed every minute of 30 hours. I just can’t wait to reading the rest of two books of the trilogy.&lt;/p&gt;
&lt;h3 id="a-brief-history-of-time"&gt;34. A Brief History of Time&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1333578746m/3869.jpg" alt="alt brief-history-of-time" /&gt;&lt;figcaption aria-hidden="true"&gt;alt brief-history-of-time&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I forgot most of the Quantum Mechanics and General Astronomy I learned in College. But this is a very good introductory book for understanding those concepts plus more contemporary science that’s not covered in college curriculum. I was listening to audio version of this book and I just didn’t have time to let the concepts sink in. Still, the book is fun and reminds me of the amazing mother nature. Or the universe.&lt;/p&gt;
&lt;h3 id="redshirts"&gt;35. Redshirts&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1348617890m/13055592.jpg" alt="alt redshirts" /&gt;&lt;figcaption aria-hidden="true"&gt;alt redshirts&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Hugo winner! It was a fun and casual book. It has very interesting prospect of the science fiction world.&lt;/p&gt;
&lt;h3 id="speaker-for-the-dead"&gt;36. Speaker for the Dead&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1295660894m/7967.jpg" alt="alt speaker-for-the-dead" /&gt;&lt;figcaption aria-hidden="true"&gt;alt speaker-for-the-dead&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The second book of The Ender Quintet. This book felt so different from Ender’s Game. It has so much more depth in emotions and morals. I still like Ender’s Game more, but not because this book isn’t great. Speaker for the Dead is just too overwhelming to me to grasp. Likely I’ll revisit this book in the future.&lt;/p&gt;
&lt;h3 id="the-10x-rule"&gt;37. The 10X Rule&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1310779133m/10339170.jpg" alt="alt 10x-rule" /&gt;&lt;figcaption aria-hidden="true"&gt;alt 10x-rule&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Set your goal to incredibly high and take massive action towards it.&lt;/p&gt;
&lt;h3 id="a-monster-calls"&gt;38. A Monster Calls&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1474081871m/28588061.jpg" alt="alt a-monster-calls" /&gt;&lt;figcaption aria-hidden="true"&gt;alt a-monster-calls&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;A very beautiful story about facing death.&lt;/p&gt;
&lt;h3 id="grokking-algorithms-an-illustrated-guide-for-programmers-and-other-curious-people"&gt;39. Grokking Algorithms: An Illustrated Guide for Programmers and Other Curious People&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1458747997m/22847284.jpg" alt="alt grokking-algorithms" /&gt;&lt;figcaption aria-hidden="true"&gt;alt grokking-algorithms&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I love this algorithm book! Especially the part explaining dynamic programming. All the illustrations are beautiful and feels very friendly, which makes an algorithm book much more intriguing.&lt;/p&gt;
&lt;h3 id="台灣不教的中國近代史"&gt;40. 台灣不教的中國近代史&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1426748118m/25173379.jpg" alt="alt modern-history-china" /&gt;&lt;figcaption aria-hidden="true"&gt;alt modern-history-china&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;我最喜歡的部份是蔣中正的故事。蔣中正在中國近代史中是滿爭議的人物，所以我很想多了解這個人。 作者出生在中國大陸、經歷過文化大革命，後來到日本定居。從他的角度說了蔣中正是怎麼崛起、抗日、 敗給中國共產黨。不論他對後世的影響，我很佩服蔣中正做事的決心、打仗的謀略、跟面對高壓環境的 能力。我比較驚訝的是抗日之後，他幾乎像是性情大變，形勢錯估得離譜然後就輸得一塌糊塗。不知道 是我看錯他的個性還是抗日改變了他。書的其他部分還滿有趣的但我沒有很喜歡作者敘事的語氣，滿多 時候帶了太多個人情感。&lt;/p&gt;
&lt;h3 id="code-name-verity-still-reading"&gt;41. Code Name Verity (still reading)&lt;/h3&gt;
&lt;figure&gt;
&lt;img src="https://images.gr-assets.com/books/1373223199m/16250900.jpg" alt="alt code-name-verity" /&gt;&lt;figcaption aria-hidden="true"&gt;alt code-name-verity&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;A beautiful story about friendships. Still reading.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/tachyons-review</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Tachyons CSS Framework / Library Review</title>
    <updated>2019-02-02T00:00:00Z</updated>
    <published>2019-02-02T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/tachyons-review" type="text/html"/>
    <content type="html">&lt;p&gt;I’ve tried to learn many CSS frameworks (Bootstrap, Foundation, and Bulmar) over the years. They never really clicked and styling felt just as painful as ever. But this has changed since I learned about &lt;a href="https://tachyons.io/"&gt;Tachyons&lt;/a&gt;. First introduced by &lt;a href="https://twitter.com/martinklepsch"&gt;Martin Klepsch&lt;/a&gt; (thanks Martin!), I learned and started to use Tachyons since late 2018 for the &lt;a href="https://cljdoc.org/"&gt;Cljdoc.org&lt;/a&gt; project [1]. This is the only CSS framework / library that fit my brain and my workflow. If you are struggling with learning any CSS framework, I hope I could shed some lights by introducing you Tachyons.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h2 id="tachyons"&gt;Tachyons&lt;/h2&gt;
&lt;p&gt;Instead of a CSS framework, I consider Tachyons a CSS library. Here’s the marketing pitch from Tachyons’ &lt;a href="https://github.com/tachyons-css/tachyons/"&gt;Github page&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Functional css for humans. Quickly build and design new UI without writing css.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So what’s functional css? Here I quote the explaination from the article &lt;a href="https://www.mikecr.it/ramblings/functional-css/"&gt;In defense of Functional CSS&lt;/a&gt; by &lt;a href="https://twitter.com/mcrittenden"&gt;Mike Crittenden&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Functional CSS basically means that you have a ton of tiny, single purpose classes that are named based on their visual function.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Here’s the definition from &lt;a href="https://twitter.com/johnpolacek"&gt;John Polacek&lt;/a&gt;’s &lt;a href="https://css-tricks.com/lets-define-exactly-atomic-css/"&gt;Let’s Define Exactly What Atomic CSS is&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Atomic CSS is the approach to CSS architecture that favors small, single-purpose classes with names based on visual function.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There seems to be a theme around “small,” “single-purpose,” and “visual” here. But why are small and single-purpose important for CSS classes? It’s because it makes them highly &lt;strong&gt;composable&lt;/strong&gt;. And the visual aspect makes the composable classes very &lt;strong&gt;readable and maintainable&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In the rest of the post, I’ll explain why composibility and maintainability make Tachyons a great fit for my brain and then why it fits my workflow. You can also find Tachyons’ creator, Adam Morse, talk about his creation if you’d like to learn his point of view[2].&lt;/p&gt;
&lt;h2 id="composability-matters"&gt;Composability matters&lt;/h2&gt;
&lt;p&gt;Coming into CSS with functional programming background, it really troubles me that all the CSS classes are effectively global-mutable-stateful objects. Without a good methodology adopted by the developer, like BEM, all CSS classes have side-effect on the whole document. (See Case 1.) This makes containing and localizing CSS classes a plausible to solve the problem. However, this also elimiates the reusability of the classes. (See Case 2.)&lt;/p&gt;
&lt;pre class="css"&gt;&lt;code&gt;/*
  Case 1
  Globally, any tag with class &amp;quot;link&amp;quot; will have the same style.
  What if some of the link elements want to have a different color, red?
*/
.link {
  color: black;
  text-decoration: none;
}

/*
  Case 2
  To contain the style within the context, one might create
  many duplicate modifier classes like below:
*/
.resulttable--link-hide {
    display: none;
}
.header--item-hide {
  display: none;
}
.article--timestamp-unimportant {
  display: none;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tachyons (and other functional css libraries) addresses the composibility problems by introducing small, single-purpose classes. Consider the examples above with the functional CSS aproach:&lt;/p&gt;
&lt;pre class="css"&gt;&lt;code&gt;/*
  Functional CSS aproach for Case 1
  Now a black link is just a composition of .black and .text-decoration-none;
  a red link is just .red and .text-decoration-none.
*/
.black {
  color: black;
}
.red {
  color: red;
}
.text-decoration-none {
  text-decoration: none;
}

/*
  Functional CSS aproach for Case 2
  Only one universal utility class for all the modifiers.
*/
.display-none {
  display: none;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;“This almost feels like writing inline-css!” and I kind of agree with you. It seems like an common knowledge that inline-css is consider bad (see &lt;a href="https://stackoverflow.com/questions/2612483/whats-so-bad-about-in-line-css"&gt;StackOverflow&lt;/a&gt;.) But this seems to be the only obvious way for me to comprehend CSS. I don’t really understand how to effectively take advantage of the cascading aspect of CSS, and functional CSS frees me from worrying about it anymore. With functional CSS like Tachyons, the classes are very composable and give me very little surprises. That is a powerful thing. I’m able to focus more on the design and less about CSS.&lt;/p&gt;
&lt;h2 id="readability-leads-to-maintainability"&gt;Readability leads to maintainability&lt;/h2&gt;
&lt;p&gt;In the above examples is really not that far away from the actual Tachyons usage. The only difference is the nomenclature (or naming schemes.) In Tachyons, the class names are concise. For example, in the Case 2 above, &lt;code&gt;.display-none&lt;/code&gt; is just &lt;code&gt;.dn&lt;/code&gt;. Padding starts with &lt;code&gt;p&lt;/code&gt;; margin with &lt;code&gt;m&lt;/code&gt;. &lt;code&gt;a&lt;/code&gt; &lt;code&gt;v&lt;/code&gt; &lt;code&gt;h&lt;/code&gt; &lt;code&gt;t&lt;/code&gt; &lt;code&gt;r&lt;/code&gt; &lt;code&gt;b&lt;/code&gt; &lt;code&gt;l&lt;/code&gt; stands for all, vertical, horizontal, top, right, bottom, left separately. Numbers indicate size. Thus, when I look at a div:&lt;/p&gt;
&lt;pre class="html"&gt;&lt;code&gt;&amp;lt;div class=&amp;quot;pa3 mb2&amp;quot;&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I can tell immediately without looking at the CSS code (nor do I need to consult the documentation) that this div is: “padding all with 3, margin at the bottom with 2.” (This almost feels like the vim keybindings!) This is such a breeze for me because when I look at the HTML code, the styles are just right there with it, and very readable. I like the conciseness of Tachyons’ class names and its consistency. It takes a bit of practice to get familiar with them, but the pay-off is that - comprehending the styles has become so easy!&lt;/p&gt;
&lt;p&gt;Take the above div for example. When I look at the rendered result on the browser and I want equal margin on the top and the bottom, I can simply just add &lt;code&gt;.mt2&lt;/code&gt; (because of the composability so this won’t conflict with my &lt;code&gt;.mb2&lt;/code&gt; nor &lt;code&gt;.pa3&lt;/code&gt;), or I can change to &lt;code&gt;.mv2&lt;/code&gt; like:&lt;/p&gt;
&lt;pre class="html"&gt;&lt;code&gt;&amp;lt;div class=&amp;quot;pa3 mv2&amp;quot;&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="workflow"&gt;Workflow&lt;/h2&gt;
&lt;p&gt;I used to think the styling development workflow is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(Feedback)   (Comprehend structure)                                (Comprehend style)                 (Change)
  See UI -&amp;gt; Find element in the HTML -&amp;gt; Figure out the CSS classes in HTML -&amp;gt; Read style in CSS -&amp;gt; Modify CSS
     ^                                                                                                  |
     |__________________________________________________________________________________________________|&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, with Tachyons, the workflow is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(Feedback)  (Comprehend structure)      (Comprehend style)      (Change)
  See UI -&amp;gt; Find element in the HTML -&amp;gt; Read style on HTML -&amp;gt; Modify HTML
     ^                                                             |
     |_____________________________________________________________|&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the high-level, there’s no difference between the two workflow. However, the difference is in the “comprehend style” step. There used to be a gap / disconnection between the CSS class name and the implementation. With Tachyons, you sort of have the entire CSS library memorized because they have very predictable behaviors and names. The result is faster development iterations.&lt;/p&gt;
&lt;p&gt;Lastly, I feel this workflow matches very well with the mindset of REPL-driven development in Clojure. The tight feedback loop enables developer to try things as fast as s/he thinks.&lt;/p&gt;
&lt;h2 id="action"&gt;Action&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;If you ever struggled with CSS, Tachyons is a great tool for you;&lt;/li&gt;
&lt;li&gt;If not, learning Tachyons may give you a fresh point of view.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="appendix"&gt;Appendix&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;[1] Cljdoc is a website building &amp;amp; hosting documentation for Clojure/Script libraries.&lt;/li&gt;
&lt;li&gt;[2] Adam Morse: Tachyons CSS Toolkit – Devshop London June 2016 &lt;a href="https://www.youtube.com/watch?v=r56fRaWth58"&gt;&lt;img src="https://img.youtube.com/vi/r56fRaWth58/0.jpg" alt="Adam Morse: Tachyons CSS Toolkit – Devshop London June 2016" /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/intermediate-dev</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Intermediate Developer</title>
    <updated>2023-08-04T00:00:00Z</updated>
    <published>2023-08-04T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/intermediate-dev" type="text/html"/>
    <content type="html">&lt;p&gt;This is a story of an average intermediate software developer.&lt;/p&gt;
&lt;p&gt;Being an intermediate developer, I cared a lot about my code. I spent a fair share of time weighing the pros and cons of my approaches to solving problems. Is this code too clever to be understood? Are there hidden invariants that weren't being explained? How easy is the code to be changed in the future? How aesthetic is the code, subjectively?&lt;/p&gt;
&lt;p&gt;Being an intermediate developer, I empathize a lot with my PR reviewers. I spent my time in &lt;code class="verbatim"&gt;git rebase --interactive&lt;/code&gt; mode to organize the git history so it tells an appealing story from start to finish. I pick and choose chunks in Magit so commits are focused and avoid accidentally including unnecessary changes. Move up, move down, reword, fixup, and squash commits all came in handy. How easy can reviewers to understand the problem I'm solving when they need more context? Can I give them more visuals like diagrams or GIF animation so I can communicate my work better?&lt;/p&gt;
&lt;p&gt;Being an intermediate developer, I read a lot of code and technical documentation. Libraries code is a great place to learn from the more experienced. Public technical documents like RFCs are resources. When modifying legacy code, always seek to understand before trying to be understood. Digging into git history to know why certain code was written and finding as much documentation as available is necessary. Never dismiss the code too quickly before understanding the history of a piece of code.&lt;/p&gt;
&lt;p&gt;Being an intermediate developer, I document knowledge worth sharing with my colleagues. Not only do I write the technical documentation or submit bug tickets, but I also spend time crafting git commits, doc-strings, or even code comments. Those are good places to document "the why" behind the code. Clean code can communicate "what the code does" well. "Why the code does things" is better communicated in the other forms. Code comments are not code smells when used precisely.&lt;/p&gt;
&lt;p&gt;As an intermediate developer, I don't shy away from learning our full application stack. Application front-end, backend, async job scheduler, and job workers are the obvious ones. When needed, optimizing PostgreSQL query with &lt;code class="verbatim"&gt;EXPLAIN ANALYZE&lt;/code&gt; can be done. Familiar myself with enough DevOps toolings so I can support the team when the Jenkins pipelines break. Occasionally digging into the ClojureScript compiler code so I can troubleshoot obscure advanced compilation bugs. I read a lot and learned a lot.&lt;/p&gt;
&lt;p&gt;Being an intermediate developer, I write tests to improve coverage. "A problem well-stated is half-solved." I don't do very strict TDD, but writing tests beforehand gives me good targets. I can always do interactive rebases to fix the git history by amending the tests. Good tests can tell better stories than other forms of documentation.&lt;/p&gt;
&lt;p&gt;As an intermediate developer, I greatly care about my team's success. I review others' code, give feedback on their work, and offer them help to unblock them. Despite the occasionally non-blocking nick-picks about others' work, my job here is to understand their work, not to be a human compiler to uncover bugs, nor to gate-keep codes that do not follow any superficial code style guides. As a reviewer, I learn from my teammates' code and make sure the knowledge is passed on.&lt;/p&gt;
&lt;p&gt;Being an intermediate developer, I help my team to onboard new people. I share my workflow, REPL development tricks, Emacs lisp code specific to our working environment, documentation, and things not well-documented by the generations of developers that have worked on it.&lt;/p&gt;
&lt;p&gt;Being an intermediate developer, I extend my help to other teams. I work closely with Designers and Quality Engineers to answer questions about features and help them flesh out the UI/UX inconsistencies. I spend hours digging into the DevOps pipelines to familiarize myself with the toolings to help DevOps team to investigate issues that touch both the Clojure domain and the Operations domain.&lt;/p&gt;
&lt;p&gt;As an intermediate developer, I keep an eye on the wider programming community to learn from the thought leaders and the great open-source projects and bring what I know to our code base and technical discussions. &lt;a href="https://lisp-lang.org/"&gt;Common Lisp&lt;/a&gt; is a very vibrant community and has so many great ideas. &lt;a href="https://fennel-lang.org/"&gt;Fennel&lt;/a&gt; is a fun language that helps me to learn &lt;a href="https://www.lua.org/"&gt;Lua&lt;/a&gt; better. &lt;a href="https://janet-lang.org/"&gt;Janet&lt;/a&gt; and &lt;a href="https://wiki.call-cc.org/"&gt;CHICKEN Scheme&lt;/a&gt; have taught me more about C and low level programming.&lt;/p&gt;
&lt;p&gt;This is a story about an average intermediate Clojure developer.&lt;/p&gt;
&lt;p&gt;—&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;strong&gt;Epilogue&lt;/strong&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This year marks my 10th year as a professional software engineer/developer. I've grown a lot over the years. Upon reflecting on my experiences and watching my colleagues, I have many thoughts to write about what seniority means to me. I'm a pretty well-rounded Clojure programmer. However, being an effective software developer is so much more than just programming. "Programs are meant to be read by humans and only incidentally for computers to execute." Communication is the essence of programming. The same is true of the other parts of my day-to-day work as an intermediate developer - reading/writing docs, reviewing PRs, discussing UI/UX with Designers and Quality Engineers, breaking down problems into predictable chunks of work, helping the customer support team to provide customer questions, etc.&lt;/p&gt;
&lt;p&gt;I think this article is 90% the recording of what I've become as an intermediate developer and 10% as my praise for the Clojure language and its community. To this day, I'm still glad that I taught myself Clojure 5 years ago. I attribute a lot of my success today to Clojure because it kept me focused so I could develop the other areas much better. Also, the team I worked with in Kira Systems for the past 3.5 years has been highly supportive, and I've grown a lot since I joined.&lt;/p&gt;
&lt;p&gt;This article is a reminder for my future self of what I've achieved as an intermediate developer. I hope I've grown even more when I look back at this article in the future.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/better-performance-with-java-arrays-in-clojure</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Better performance with Java arrays in Clojure</title>
    <updated>2021-06-14T00:00:00Z</updated>
    <published>2021-06-14T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/better-performance-with-java-arrays-in-clojure" type="text/html"/>
    <content type="html">&lt;p&gt;I was working on re-implementing the &lt;a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent"&gt;Stochastic gradient descent&lt;/a&gt; algorithm in Clojure based on the blog post &lt;a href="https://machinelearningmastery.com/implement-linear-regression-stochastic-gradient-descent-scratch-python/"&gt;How to Implement Linear Regression From Scratch in Python&lt;/a&gt;. Because I wasn’t happy about the performance when the dataset is in the order of thousands rows of thousands features, so I started looking into ways to go lower-level to use the Java arrays and found this amazing article on Clojure Goes Fast: &lt;a href="http://clojure-goes-fast.com/blog/java-arrays-and-unchecked-math/"&gt;Java arrays and unchecked math&lt;/a&gt;. (It’s a great article that goes into details of Clojure type-hinting and other tips. Highly recommended!)&lt;/p&gt;
&lt;p&gt;Following the instructions in the Clojure Goes Fast article, I’m quite amazed by the performance boost. Below is a comparison of the same &lt;code&gt;predict&lt;/code&gt; function: one expects Clojure vector and the other Java arrays. The only thing novel thing that didn’t cover in the Clojure Goes Fast article is the usage of &lt;code&gt;areduce&lt;/code&gt;. Instead of the explicit &lt;code&gt;loop-recur&lt;/code&gt; shown in the article, I stumbled upon this handy &lt;code&gt;clojure.core/areduce&lt;/code&gt; form and used it to better convey the implementation of the &lt;code&gt;predict&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;The results are quite promising.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(require &amp;#39;[criterium.core :as c])

(defn predict-v [xs [bias &amp;amp; coefs]]
  (reduce + bias (map * xs coefs)))

(defn predict-a [^doubles xs ^doubles coefs]
  (areduce xs idx ret (aget coefs 0)
           (+ ret (* (aget xs idx) (aget coefs (inc idx))))))

(let [xs      (range 5000)
      coefs   (range 5001)
      xs-v    (into [] xs)
      coefs-v (into [] coefs)
      xs-a    (into-array Double/TYPE xs)
      coefs-a (into-array Double/TYPE coefs)]
  (c/quick-bench (predict-v xs-v coefs-v))
  (c/quick-bench (predict-a xs-a coefs-a)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;*out*&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Evaluation count : 834 in 6 samples of 139 calls.
             Execution time mean : 736.026481 µs
    Execution time std-deviation : 26.489882 µs
   Execution time lower quantile : 715.074957 µs ( 2.5%)
   Execution time upper quantile : 777.624246 µs (97.5%)
                   Overhead used : 6.224349 ns
Evaluation count : 106956 in 6 samples of 17826 calls.
             Execution time mean : 5.865484 µs
    Execution time std-deviation : 221.419267 ns
   Execution time lower quantile : 5.580842 µs ( 2.5%)
   Execution time upper quantile : 6.125437 µs (97.5%)
                   Overhead used : 6.224349 ns&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It’s about &lt;code&gt;736 µs&lt;/code&gt; versus &lt;code&gt;5.87 µs&lt;/code&gt;. That’s about a 125X speedup by using Java array.&lt;/p&gt;
&lt;p&gt;It’s really nice that I don’t have to sacrifice the functional programming constructs (like &lt;code&gt;map&lt;/code&gt;[^1] and &lt;code&gt;reduce&lt;/code&gt;) because I’m working on a different data structure. Under the hood, &lt;code&gt;areduce&lt;/code&gt; is a macro that does the &lt;code&gt;loop-recur&lt;/code&gt; for you. Here’s the source code of &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L5265"&gt;&lt;code&gt;clojure.core/areduce&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(defmacro areduce
  &amp;quot;Reduces an expression across an array a, using an index named idx,
  and return value named ret, initialized to init, setting ret to the
  evaluation of expr at each step, returning ret.&amp;quot;
  {:added &amp;quot;1.0&amp;quot;}
  [a idx ret init expr]
  `(let [a# ~a l# (alength a#)]
     (loop  [~idx 0 ~ret ~init]
       (if (&amp;lt; ~idx l#)
         (recur (unchecked-inc-int ~idx) ~expr)
         ~ret))))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using this macro has an advantage over using the &lt;code&gt;loop-recur&lt;/code&gt;: you don’t need to explicitly call the &lt;code&gt;unchecked-inc-int&lt;/code&gt; to get the full benefit of speeding up looping on the array &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Reference Links&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://clojure-goes-fast.com/blog/java-arrays-and-unchecked-math/"&gt;Java arrays and unchecked math&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent"&gt;Stochastic gradient descent&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://machinelearningmastery.com/implement-linear-regression-stochastic-gradient-descent-scratch-python/"&gt;How to Implement Linear Regression From Scratch in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L5265"&gt;&lt;code&gt;clojure.core/areduce&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Footnotes&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;[^1] Besides the &lt;code&gt;clojure.core/areduce&lt;/code&gt; shown in this article, there’s also the &lt;code&gt;clojure.core/amap&lt;/code&gt;.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/truth-testing</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Python Truth Value Testing is Awesome</title>
    <updated>2016-02-25T00:00:00Z</updated>
    <published>2016-02-25T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/truth-testing" type="text/html"/>
    <content type="html">&lt;p&gt;I’m constantly amazed by the simplicity and readability Python provides. (See The &lt;a href="https://www.python.org/dev/peps/pep-0020/"&gt;Zen of Python&lt;/a&gt;.) As the industry evolves, more and more codes written each day, how to read code fast is a rising question every developer would face. Imaging the times when you faced a new code base and need to ramp up the knowledge in order to work with it. Lot’s of reading, isn’t it? This is why I think Python is a great modern programming language. Let’s talk about one of the features Python provides — the &lt;a href="https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing"&gt;truth value testing&lt;/a&gt;.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;(Go ahead and read the docs in Python’s official documentation. You cannot avoid reading documentations while developing software.)&lt;/p&gt;
&lt;p&gt;Basically the doc tells you that any object could be used for if-condition, while-condition, or boolean operation. Let’s look at the following code:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;if 1:
    print(&amp;#39;non-zero number is truthy!&amp;#39;)
if [1]:
    print(&amp;#39;non-empty list is truthy!&amp;#39;)
if {&amp;#39;attr&amp;#39;: &amp;#39;value&amp;#39;}:
    print(&amp;#39;non-empty dict is truthy!&amp;#39;)
if &amp;#39;a_string&amp;#39;:
    print(&amp;#39;non-empty string is truthy!&amp;#39;)
if 0:
    # print(&amp;#39;0 is not truthy!&amp;#39;)
if &amp;#39;&amp;#39;:
    # print(&amp;#39;empty string is not truthy!&amp;#39;)
if []:
    # print(&amp;#39;empty list is not truthy!&amp;#39;)
if {}:
    # print(&amp;#39;empty dict is not truthy!&amp;#39;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This feature gives us a very consistent way of writing code. Unlike writing code in Java, I don’t need to remember whether the return type is a null pointer or a boolean false when calling a method. In Python, a simple truth testing would give me the answer I want, because they both gives me a False.&lt;/p&gt;
&lt;p&gt;The truth testing feature also makes a very sweet combo with the Boolean Operators. Consider the code below:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;ENV_VAR = os.environ.get(‘ENV_VAR’) or &amp;lt;default_value&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code reads: get the &lt;code&gt;ENV_VAR&lt;/code&gt; value from the OS’s environment, if can’t find it, just use a default value. It looks pretty neat, isn’t it? Imaging this code written in Java:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;String ENV_VAR;
if (getEnvVar(&amp;quot;ENV_VAR&amp;quot;) != null):
    SECRET_KEY = getEnvVar(&amp;quot;ENV_VAR&amp;quot;);
else:
    SECRET_KEY = &amp;lt;default_value&amp;gt;;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Needless to say, lot’s of noise for my eyes when reading it.&lt;/p&gt;
&lt;p&gt;Why this would work is because the Python or-operator does something slightly difference than what we learn on the truth table. When evaluating the line &lt;code&gt;x or y&lt;/code&gt;, what Python does is to do &lt;code&gt;if x is false, then y, else x&lt;/code&gt;. Again, the ‘if x is false’ statement wouldn’t work without the truth value testing feature in Python.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/first-hackathon</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Completed my first hackathon!</title>
    <updated>2016-03-10T00:00:00Z</updated>
    <published>2016-03-10T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/first-hackathon" type="text/html"/>
    <content type="html">&lt;p&gt;It was such a amazing experience. There’s no such thing that make you, and your teammate pull a all-nighter and still gives you one of the best times of your life, except hackathon. (Hackathon rocks!) I want to share with you what it was like, if you don’t already know, and some thoughts about it.&lt;/p&gt;
&lt;p&gt;My company started its first ever hackathon last Thursday at 8 am. All submission were done on Friday, 12 pm and the whole afternoon is for presentations and demonstrations. The basic idea of hackathon: it is a project competition that’s done during days of marathon-like intensive working/hacking. Participating teams get unlimited supplies of coffee and red bulls. Indeed this sounds very terrifying.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;When I use the word “hack” it is not exactly the same thing we pictured of what computer hackers do. For here it is more generic. Hacking is “to interact with a system in a way that the system don’t want you to.” For example, to gain access to another person’s online credentials without permission. Obviously, in usual use cases, the system wouldn’t want you to. Another example, to write a backdoor in your company’s commercialized software even though your company does not allow you to. Yeah, these are hacking.&lt;/p&gt;
&lt;p&gt;During the hackathon, not only did our team hacked a backdoor in the system, but also did we hacked the system software architecture (a little) in order to get our parasite-like software running on top of it. I believe we had embraced the true spirit of hacking.&lt;/p&gt;
&lt;p&gt;But those did not really matter. &lt;strong&gt;The biggest enemy in hackathon&lt;/strong&gt;, in my opinion, &lt;strong&gt;is perfectionism&lt;/strong&gt;. The 80–20 rules works very well here — &lt;em&gt;if you can make 80% of the things to work with 20% of the efforts, why spending the rest of the 80% of time?&lt;/em&gt; If spending 20 mins hacking the system could get the software to work, why spend the extra hour or so? That’s what we ended up doing a lot through the hackathon.&lt;/p&gt;
&lt;p&gt;Honestly, this isn’t my first ever hackathon I’ve attended. However, this is the first ever hackathon that I finished. The difference is, I didn’t understand my tools well enough the previous time so I ended up spending a lot of time on the web searching for answers I should’ve known by the time. This time was different. I gain much more experience in building Flask web app throughout the course of past few months. Knowing my tools well enough, I’ve built-up the necessary coding muscle memory that I don’t need to consult the documents so often. This gave me the edge to be able to construct my idea into code more quickly.&lt;/p&gt;
&lt;p&gt;A little bit about my hackathon project: the software stack I’m using is Python Flask for backend, and my crappy Bootstrap skills for frontend. The project idea is to build a automated task scheduler web service on top of the existing system. Writing the web service wasn’t the hardest. The most difficult challenge is to integrate the web service into our existing system. OMG, I can’t tell how much relief it felt to see those pieces working together for the first time.&lt;/p&gt;
&lt;p&gt;I’m very proud of what my team had achieved in the hackathon. However, there’s one thing till today I still think that I could have (and should have) done better is the demo. I admit that we didn’t put too much thought into the demo. All I think was that we were going to BLOW EVERYONE’S MIND just by showing it. Turned out it didn’t. Our way of presenting the software wasn’t very engaging to the judges. If I could go back in time to where we started the hackathon, I would’ve punch in my nerdy face and told him to sit down and think about the demo. Think about what you want to present in the demo. And be focused on making that happen. Everything else is the extra 80% burden that drags you along the way.&lt;/p&gt;
&lt;p&gt;It’s amazing how things are so clear afterwards. I got two lessons learned in the end: 1. Know your tools well — go build up the coding muscle memory! 1. Design for demo — keep demo in mind all the time!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/clojure-higher-order-functions-explained-complement</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Clojure higher-order functions explained: complement</title>
    <updated>2021-03-23T00:00:00Z</updated>
    <published>2021-03-23T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/clojure-higher-order-functions-explained-complement" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;Checkout the &lt;a href="/blog/clojure-higher-order-functions-explained-index"&gt;index&lt;/a&gt; for the full series.&lt;/em&gt;&lt;/p&gt;
&lt;h2 id="source-code"&gt;Source code&lt;/h2&gt;
&lt;p&gt;Here’s the &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L1433"&gt;source of complement in clojure 1.10.1&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defn complement
  &amp;quot;Takes a fn f and returns a fn that takes the same arguments as f,
  has the same effects, if any, and returns the opposite truth value.&amp;quot;
  {:added &amp;quot;1.0&amp;quot;
   :static true}
  [f]
  (fn
    ([] (not (f)))
    ([x] (not (f x)))
    ([x y] (not (f x y)))
    ([x y &amp;amp; zs] (not (apply f x y zs)))))&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="usages"&gt;Usages&lt;/h2&gt;
&lt;p&gt;From the doc-string:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Takes a fn f and returns a fn that takes the same arguments as f, has the same effects, if any, and returns the opposite truth value.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Although there’s no restriction on the number of arguments, I found &lt;code&gt;complement&lt;/code&gt; to be most useful to create predicate functions, which take a single argument and return a value that meant to be consumed as a logical value.&lt;/p&gt;
&lt;p&gt;A small caveat when using &lt;code&gt;complement&lt;/code&gt; is that it returns a &lt;strong&gt;Boolean&lt;/strong&gt; instead of the data type from the original function f. This makes it a bit slightly inconvenient to use with &lt;code&gt;keep&lt;/code&gt; or &lt;code&gt;some&lt;/code&gt; if you expect the return value to be the inverse of the original function f:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; some returns the first logical truthy value
(some #{:a :b} [:1 :2 :a :b])
;; =&amp;gt; :a

;; true is a truthy value
(some (complement #{:a :b}) [:1 :2 :a :b])
;; =&amp;gt; true

;; keep removes nil
(keep #{:a :b} [:1 :2 :a :b])
;; =&amp;gt; (:a :b)

;; doesn&amp;#39;t remove the false
(keep (complement #{:a :b}) [:1 :2 :a :b])
;; =&amp;gt; (true true false false)

;; better to use remove instead
(remove #{:a :b} [:1 :2 :a :b])
;; =&amp;gt; (:1 :2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;filter&lt;/code&gt; on the other hand is the most consistent (the least surprising) one with &lt;code&gt;complement&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(filter #{:a :b} [:1 :2 :a :b])
;; =&amp;gt; (:a :b)

(filter (complement #{:a :b}) [:1 :2 :a :b])
;; =&amp;gt; (:1 :2)&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="examples"&gt;Examples&lt;/h2&gt;
&lt;p&gt;There are a couple of great examples by the Clojure community on &lt;a href="https://clojuredocs.org/clojure.core/complement"&gt;clojuredocs.org’s complement page&lt;/a&gt;. Please go check it out for the examples!&lt;/p&gt;
&lt;h2 id="my-use-cases"&gt;My use cases&lt;/h2&gt;
&lt;p&gt;This is my growing list of use cases where I stumble upon and found &lt;code&gt;complement&lt;/code&gt; useful ;)&lt;/p&gt;
&lt;h3 id="not-contains"&gt;Not contains?&lt;/h3&gt;
&lt;p&gt;Already mentioned above, not-contain can be written as:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(filter #(not (contains? #{:a :b} %)) [:1 :2 :a :b])
(filter #(not (#{:a :b} %)) [:1 :2 :a :b])
(filter (complement #{:a :b}) [:1 :2 :a :b])&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="not-key"&gt;Not :key&lt;/h3&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(filter :disabled [{:v 1} {:v 2} {:v 3 :disabled true} {:v 4}])
;; =&amp;gt; ({:v 3, :disabled true})
(filter (complement :disabled) [{:v 1} {:v 2} {:v 3 :disabled true} {:v 4}])
;; =&amp;gt; ({:v 1} {:v 2} {:v 4})&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="links"&gt;Links&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L1433"&gt;Source of complement in clojure 1.10.1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://clojuredocs.org/clojure.core/complement"&gt;Clojuredocs.org’s complement page&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/recap-2018</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Recap 2018</title>
    <updated>2019-01-02T00:00:00Z</updated>
    <published>2019-01-02T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/recap-2018" type="text/html"/>
    <content type="html">&lt;p&gt;After reading Brandon Sanderson’s &lt;a href="https://brandonsanderson.com/state-of-the-sanderson-2018/"&gt;State of the Sanderson 2018&lt;/a&gt; and Fogus’s &lt;a href="http://blog.fogus.me/2019/01/02/the-best-things-and-stuff-of-2018/"&gt;The best things and stuff of 2018&lt;/a&gt;, I feel like to write up a quick summary my year of 2018, a part for myself, and a part for the reason I’ll explain later in the post.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h1 id="some-numbers-in-2018"&gt;Some Numbers in 2018&lt;/h1&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;strong&gt;280&lt;/strong&gt; Open Source Software &lt;a href="https://github.com/dawranliou/"&gt;contributions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;11.9K&lt;/strong&gt; Total viewership over the &lt;strong&gt;5&lt;/strong&gt; articles I published on &lt;a href="https://medium.com/@dawranliou"&gt;Medium&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;40&lt;/strong&gt; &lt;a href="https://www.goodreads.com/user/year_in_books/2018/62701324"&gt;Books&lt;/a&gt; read&lt;/li&gt;
&lt;/ol&gt;
&lt;h1 id="highlights"&gt;Highlights&lt;/h1&gt;
&lt;h2 id="cljdoc.org"&gt;1. Cljdoc.org&lt;/h2&gt;
&lt;p&gt;The thing I’m most proud of in 2018 is that I started contributing to &lt;a href="https://cljdoc.org/"&gt;Cljdoc.org&lt;/a&gt;. My open source contribution started back in 2016 during my first PyCon’s sprint. Since then I occasionally contribute to the open source software that I use but never had I felt that the programming community would be part of my identity. Not until I stumbled upon Clojure and Cljdoc.&lt;/p&gt;
&lt;p&gt;Special thanks to &lt;a href="https://twitter.com/martinklepsch"&gt;Martin Klepsch&lt;/a&gt;, the creator of Cljdoc, who helped me a ton to go through some questions and provide feedbacks all along the way. Through contributing to his project, I gained more confidence and experiences then I would have if I were to learn Clojure all alone. I’m extremely blessed to have someone like Martin to look up to while being so approachable at the same time. Contributing to Cljdoc is easily the highlight of 2018.&lt;/p&gt;
&lt;h2 id="the-cosmere"&gt;2. The Cosmere&lt;/h2&gt;
&lt;p&gt;At 2016, I picked up the first book of Mr. Brandon Sanderson’s Mistborn trilogy and I’m hooked. This year, I stormed through every book in his Cosmere collection and OMG this was &lt;em&gt;phenomenal&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;If you are curious, Cosmere is the fiction Universe that surrounds the worlds (or planetary systems) inside. Though the magic systems varies a lot between the worlds, there are some unified laws or rules that each of them follows, though I believe there’re just fan theories circulating around.&lt;/p&gt;
&lt;p&gt;Brandon’s story telling in each of the book is so fascinating and I just want to recommend his books to all the people I know.&lt;/p&gt;
&lt;h2 id="coolmarkdowneditor.org"&gt;3. CoolMarkdownEditor.org&lt;/h2&gt;
&lt;p&gt;This was quite a surprise. I didn’t set out to do a project as useful as the &lt;a href="https://coolmarkdowneditor.org/"&gt;Cool Markdown Editor&lt;/a&gt; I just wanted to have a toy project to help me learn Clojure/Script and get familiar with the development. Turned out I was wrong, this is actually something useful to me. I used it when I just need an easy place to write up some technical document. Yeah I know you all have opinions on this. My opinions are:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;I want very little distraction.&lt;/li&gt;
&lt;li&gt;I want it launch quickly.&lt;/li&gt;
&lt;li&gt;I want to see preview on the side, always.&lt;/li&gt;
&lt;li&gt;I want to share document.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Though the implementation is quite simple, and probably easier if I chosed to use vanila JavaScript, I really had a blast writing Clojure for this project.&lt;/p&gt;
&lt;h1 id="low-lights"&gt;Low-lights&lt;/h1&gt;
&lt;h2 id="medium-vs-personal-blog"&gt;-1. Medium vs Personal Blog&lt;/h2&gt;
&lt;p&gt;Since this year, I’ve been wanting to move away from Medium but the viewership just kept growing there. I didn’t want to abandon the audience there but my personal blog is just very quiet. Marketing my own blog would be a challenge for the upcoming year.&lt;/p&gt;
&lt;h2 id="no-usta-tennis-tournaments-played-in-2018"&gt;-2. No USTA tennis tournaments played in 2018&lt;/h2&gt;
&lt;p&gt;I broke my left knee at the end of 2017 and came back mid this year. Though I played one NTRP 3.5 singles league and the Bay Area Industrial Tennis League, I did not participate any USTA NTRP singles tournament. Though my skills has improved from NTRP 3.0 to 3.5 this year. I wished that I had some record to support it.&lt;/p&gt;
&lt;h2 id="tennis-vs-body-building"&gt;-3. Tennis vs Body Building&lt;/h2&gt;
&lt;p&gt;I didn’t find the balance between body building and playing competitive tennis. Part of the reason is that my tennis schedule isn’t always fixed and work was more stressful this year.&lt;/p&gt;
&lt;h1 id="favorite-stuffs"&gt;Favorite Stuffs&lt;/h1&gt;
&lt;h2 id="technologies"&gt;Technologies&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://clojure.org/"&gt;Clojure&lt;/a&gt; - Clojure is the best thing that happened to me since Python&lt;/p&gt;
&lt;h2 id="technical-books"&gt;Technical Books&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://www.amazon.com/Living-Clojure-Introduction-Training-Developers/dp/1491909048/ref=sr_1_1?ie=UTF8&amp;amp;qid=1546562606&amp;amp;sr=8-1&amp;amp;keywords=living+clojure"&gt;Living Clojure by Carin Meier&lt;/a&gt; - From my review on Goodread: &amp;gt; This is very practical guide for people coming to Clojure as their second language, just like me.&lt;/p&gt;
&lt;h2 id="non-technical-books"&gt;Non-technical Books&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://www.amazon.com/Words-Radiance-Stormlight-Archive-Book-ebook/dp/B00DA6YEKS/ref=sr_1_1?ie=UTF8&amp;amp;qid=1546562659&amp;amp;sr=8-1&amp;amp;keywords=stormlight+archive+book+2"&gt;Words of Radiance (The Stormlight Archive, Book 2) by Brandon Sanderson&lt;/a&gt; - This is a tough call. I love all the books by Brandon Sanderson and Patrick Rothfuss I read this year. However, there’re some scenes from Words of Radiance that are just too epic. From my review on Goodread: &amp;gt; This book is amazing. I love the character development so much in this book, perhaps more than book 1 in the series. It devastated me how much struggle the characters had to come through. And those heart-wrenching conversations before they came to the realization of their own identities… I learned so much from the characters and I love this book.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.amazon.com/gp/product/0060574216/ref=x_gr_w_bb?ie=UTF8&amp;amp;tag=x_gr_w_bb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=0060574216&amp;amp;SubscriptionId=1MGPYB6YW3HWK55XCGG2"&gt;Men Are from Mars, Women Are from Venus by John Gray&lt;/a&gt; I’ve learned so much about being in a relationship and the differences between men and women. This book has significantly changed the dynamics between me and my girlfriend.&lt;/p&gt;
&lt;h2 id="tv-shows"&gt;TV shows&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://www.rottentomatoes.com/tv/daredevil/"&gt;Daredevil&lt;/a&gt; - No doubt this is my favorite show ever. I love the interpretation of the characters, the struggles, the religious aspects, the philosophy aspects, the screenwriting, the dialogues, and everything about this show. This is just too good. Daredevil is the best super hero since Christopher Nolan’s Batman.&lt;/p&gt;
&lt;h1 id="personal-relationships"&gt;Personal Relationships&lt;/h1&gt;
&lt;p&gt;My girlfriend and I have come through a lot in 2018. We both grew and learned a lot from each other and I couldn’t stress more on how important that is to us. We’ve been sort of long distance (7.5 hours drive away) for the most of our relationship and finally we moved to the same city this October.&lt;/p&gt;
&lt;h1 id="people-who-inspiredinfluenced-me-in-2018-in-no-particular-order"&gt;People who inspired/influenced me in 2018 (in no particular order)&lt;/h1&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;a href="https://twitter.com/martinklepsch"&gt;Martin Klepsch&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/thling"&gt;Sam Ling&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://twitter.com/HendersGame"&gt;Hannah Henderson&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/back-to-paredit</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Back to paredit</title>
    <updated>2021-08-14T00:00:00Z</updated>
    <published>2021-08-14T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/back-to-paredit" type="text/html"/>
    <content type="html">&lt;h2 id="to-simplify-my-s-exp-workflow"&gt;To simplify my s-exp workflow&lt;/h2&gt;
&lt;p&gt;I had been using &lt;a href="https://github.com/abo-abo/lispy"&gt;lispy&lt;/a&gt; and &lt;a href="https://github.com/noctuid/lispyville"&gt;lispyville&lt;/a&gt; for &lt;a href="/blog/my-emacs-clojure-dev-env-overview.md#lispy-lispyville-general-lisp-s-expression-editing"&gt;general s-expression editing and navigation&lt;/a&gt; previously. My setup works pretty well, but I often found the packages are a bit of a feature bloat. Plus, I don’t use most of the transitive dependencies (ace-window, counsel, ivy, swiper, hydra). Over time, I started to realize what I like or want and what I don’t care about for my workflow. I decided to switch to a lighter package to help me to build the workflow. So here we are, back to the good old &lt;a href="https://www.emacswiki.org/emacs/ParEdit"&gt;paredit&lt;/a&gt;, again, for its simplicity.&lt;/p&gt;
&lt;p&gt;Here’s a list of features I &lt;em&gt;actually&lt;/em&gt; want to use:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;S-exp navigation&lt;/li&gt;
&lt;li&gt;Killing s-exp&lt;/li&gt;
&lt;li&gt;Closing parentheses automatically&lt;/li&gt;
&lt;li&gt;Slurping and barfing s-exp&lt;/li&gt;
&lt;li&gt;Wrapping and unwrapping (or splicing) s-exp&lt;/li&gt;
&lt;li&gt;Dragging (or transposing) s-exp&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Surprisingly, vanilla Emacs already supports half of the list! By default, &lt;code&gt;C-M-(f|b|u|d|n|p)&lt;/code&gt; bounds to the s-exp navigation commands; &lt;code&gt;C-M-k&lt;/code&gt; kills s-exp; &lt;code&gt;C-M-t&lt;/code&gt; transposes s-exp that acts sort of like dragging s-exps. So I only need paredit to fill in the rest of the list.&lt;/p&gt;
&lt;h2 id="to-not-handle-parentheses"&gt;To not-handle parentheses&lt;/h2&gt;
&lt;p&gt;I recently came across this &lt;a href="https://www.reddit.com/r/emacs/comments/l7khmk/what_key_binding_scheme_do_you_use_to_handle/gl9fcqs?utm_source=share&amp;amp;utm_medium=web2x&amp;amp;context=3"&gt;reddit thread&lt;/a&gt;, which gave me a new perspective about handling parentheses for lispy languages. Actually, it’s about how &lt;strong&gt;not&lt;/strong&gt; handling parentheses. The constraint of keeping parentheses balanced all the time is surprisingly unnecessary and restrictive. Without this constraint, I started finding myself enjoying a lot more freedom in my REPL workflow. For example, when I have the Clojure code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(-&amp;gt; data
    transform-1
    transform-2
    transform-3
    transform-4)

(let [a 1
      b 1
      c (+ a b)
      d (+ b c)
      e (+ c d)]
  ;; some more computation
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To inspect the transformation, I can temporarily insert unbalanced closing parentheses and code and then evaluate the code by putting the point at &lt;code&gt;-!-&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(-&amp;gt; data
    transform-1
    transform-2)-!-  ; eval this s-exp
    transform-3
    transform-4)

(let [a 1
      b 1
      c (+ a b)] c)-!-  ; eval this s-exp
      d (+ b c)
      e (+ c d)]
  ;; some more computation
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once I got the results, removing the temporary code is all it takes to have perfectly balanced parentheses again.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This is more or less the same as using &lt;code&gt;cider-eval-sexp-up-to-point&lt;/code&gt;, but I don’t want to memorize too many lesser-used keybindings. Plus, I prefer workflows that are more generic to other lispy languages.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;To do this, I unbound a couple of commands from the &lt;code&gt;paredit-mode-map&lt;/code&gt;, such as &lt;code&gt;C-d&lt;/code&gt; and &lt;code&gt;DEL&lt;/code&gt;. &lt;code&gt;C-k&lt;/code&gt; is sometimes useful to delete code in bulk, so I still keep it bind to the &lt;code&gt;paredit-kill&lt;/code&gt; command.&lt;/p&gt;
&lt;p&gt;However, unlike what the reddit thread mentioned, I still find automatically inserting paren pairs helpful. This is probably because I work a lot in Clojure, which considers square brackets &lt;code&gt;[]&lt;/code&gt; and curly braces &lt;code&gt;{}&lt;/code&gt; as valid s-exp as well as parentheses &lt;code&gt;()&lt;/code&gt;, so there are multiple ways to close an s-exp. Also, it’s one less keystroke to type &#128539;.&lt;/p&gt;
&lt;!--  LocalWords:  paredit lispy lispyville swiper exps
 --&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/generator-the-basics</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Generator - The Basics</title>
    <updated>2017-01-07T00:00:00Z</updated>
    <published>2017-01-07T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/generator-the-basics" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;I’ve been wanting to write articles about generators for quite some time. Generator is definitely one of my favorite features in Python. Ever since I stopped treating Python like other programming languages, e.g. Java or C++, I start having so much fun writing codes. Unlike other very powerful features (decorators, context managers, or classes) that I sometimes abused a lot, Generators don’t ever seemed to be too much in my code. They have strong purpose in the code, and are very beautiful in the codes. In this article, I’ll explain the basics things about generators. At the end, I’ll show you how to use it to solve some problems.&lt;/em&gt;&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h1 id="why-do-i-need-to-know-generators"&gt;1. Why do I need to know generators?&lt;/h1&gt;
&lt;p&gt;There’re two categories of use cases:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;To generate a series of data&lt;/li&gt;
&lt;li&gt;To pause code execution&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For category #1, you might think &lt;em&gt;“why we need another tool while we already know how to write lists to store a series of data?”&lt;/em&gt; There are three reasons: 1) list can’t solve all problems, 2) performance, and 3) code style.&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;List can’t solve all problems. In the cases that we have a infinite series of data (e.g. generating prime numbers,) or the series of data that we can’t tell when it’ll stop (e.g. parsing log files that still are adding more entries,) there’s no easy way to extract this part of code into a function that returns a list. On the other hand, generators are perfectly fine for these jobs.&lt;/li&gt;
&lt;li&gt;Performance. Space-wise, if the data series consumer just need one data point at a time, why waste the memory to hold the entire copy of the data series? Time-wise, if the data consumer does not require all the data to be present to do the next thing, why waste time to wait till all data are at hand while you can pass on the data to do work at the same time? Generators are good for both cases.&lt;/li&gt;
&lt;li&gt;Code style. This is a bit opinionative. I feel coding with generators is usually cleaner and easier to understand then functions without them. Also opinionative, usually a generator code is a hint of outputting a series of data. Therefore, I have some idea of what the code is doing even without looking at the code line-by-line.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For category #2, this is something very powerful. Normal functions, or called subroutines, execute line by line till they &lt;code&gt;return&lt;/code&gt; control to the caller. Generators, or a coroutine, execute till they &lt;code&gt;yield&lt;/code&gt; a value to the caller and pause the current state until their caller invoke them again to resume the execution. My favorite examples for this case is the &lt;code&gt;@contextlib.contextmanager&lt;/code&gt; decorator in &lt;a href="https://www.oreilly.com/learning/20-python-libraries-you-arent-using-but-should#contextlib-ZKsPtpTX"&gt;20 Python libraries you aren’t using (but should)&lt;/a&gt; and also David Beazley’s incredible live demo in PyCon 2015 -&lt;a href="https://www.youtube.com/watch?v=MCs5OvhV9S4"&gt;Python Concurrency From the Ground Up: LIVE!&lt;/a&gt;.&lt;/p&gt;
&lt;h1 id="what-are-generators"&gt;2. What are generators?&lt;/h1&gt;
&lt;p&gt;Python’s generator is a special case of &lt;a href="https://en.wikipedia.org/wiki/Coroutine"&gt;coroutine&lt;/a&gt;. If looking at the proper definition gives you an headache, my way of understanding it is - &lt;em&gt;generators are functions that don’t return&lt;/em&gt;. I admit there are many flaws in my definition, but this definition helps me to understand some key concepts. Ask yourself a question, &lt;em&gt;what does &lt;code&gt;return&lt;/code&gt; mean?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;return&lt;/code&gt; means to return control to the caller. Python virtual machine is a stack machine. When a function is called, a frame object is PUSH onto the execution stack. This frame object is a mini environment for the function. Having this enclosing mini environment, the function could have its own variables without worrying about variable names colliding with the outer environment. When the function returns, the frame object is POPPED from the stack. All the variables sitting inside the mini environment are gone. The caller regains full control and continues.&lt;/p&gt;
&lt;p&gt;Generators, however, do not return full control to the caller. Instead, they pause (or yield.) Thus, the mini environment of the generators, are still sitting somewhere in the memory, waiting to be invoked.&lt;/p&gt;
&lt;p&gt;Before I bored you to death with all the descriptions, let’s see some code example.&lt;/p&gt;
&lt;p&gt;Just like functions are objects in Python, generators are also objects. They are special objects that looks very similar to regular function definitions but behaves very differently:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def a_function():
    return True

def a_generator():
    yield True

&amp;gt;&amp;gt;&amp;gt; a_function()
True

&amp;gt;&amp;gt;&amp;gt; a_generator()
&amp;lt;generator object a_generator at 0x...&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When generator objects are created, they don’t start executing immediately. Generator objects, like &lt;code&gt;a_generator()&lt;/code&gt;, follow the Iterator Protocol. So to invoke them, you can use the builtin function &lt;code&gt;next()&lt;/code&gt;&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; g = a_generator()
&amp;gt;&amp;gt;&amp;gt; next(g)
True
&amp;gt;&amp;gt;&amp;gt; next(g)
Traceback (most recent call last):
  File &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 1, in &amp;lt;module&amp;gt;
StopIteration&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Not only do generators are iterators, they are also iterables! (You can know more about the distinction between iterables and iterators from &lt;a href="https://www.youtube.com/watch?v=EnSu9hHGq5o"&gt;Ned Batchelder - Loop like a native: while, for, iterators, generators&lt;/a&gt;.) The builtin &lt;code&gt;iter&lt;/code&gt; function call simply returns the generator itself, which is a iterator:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; iter(g) is g
True&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thus, all the builtin functions and external APIs that takes iterables as input, works for generators! &lt;em&gt;(This is one of the most exciting realization I had while learning Python.)&lt;/em&gt; Keep this in mind. We’re counting on it for the next section.&lt;/p&gt;
&lt;h1 id="how-do-i-use-generators"&gt;3. How do I use generators?&lt;/h1&gt;
&lt;p&gt;Recall that I said generators are good to generate a series of data. Thus, using generators with loops is a good idea:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def best_burger_generator():
    yield &amp;#39;bun&amp;#39;
    yield &amp;#39;veggies&amp;#39;
    for i in range(2):
        yield &amp;#39;patty&amp;#39;
        yield &amp;#39;cheese&amp;#39;
    yield &amp;#39;sause&amp;#39;
    yield &amp;#39;onion&amp;#39;
    yield &amp;#39;bun&amp;#39;

&amp;gt;&amp;gt;&amp;gt; doubledouble_recipe = best_burger_generator()
&amp;gt;&amp;gt;&amp;gt; list(doubledouble_recipe)
[&amp;#39;bun&amp;#39;, &amp;#39;veggies&amp;#39;, &amp;#39;patty&amp;#39;, &amp;#39;cheese&amp;#39;, &amp;#39;patty&amp;#39;, &amp;#39;cheese&amp;#39;, &amp;#39;sause&amp;#39;, &amp;#39;onion&amp;#39;, &amp;#39;bun&amp;#39;]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or to generate an infinite series of data:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def perfect_24_7_drive_thru():
    while True:
        yield &amp;#39;doubledouble and animal fries&amp;#39;

&amp;gt;&amp;gt;&amp;gt; drive_thru = perfect_24_7_drive_thru()
&amp;gt;&amp;gt;&amp;gt; next(drive_thru)
&amp;#39;doubledouble and animal fries&amp;#39;
&amp;gt;&amp;gt;&amp;gt; next(drive_thru)
&amp;#39;doubledouble and animal fries&amp;#39;
&amp;gt;&amp;gt;&amp;gt; # forever and ever satisfaction&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Recall what I said, generators are iterables. Thus, be confident to iterate through them or plug them into functions that takes iterables:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;# loop through the generator with a for-loop
&amp;gt;&amp;gt;&amp;gt; for ingredient in best_burger_generator():
...     print(ingredient)
...
bun
veggies
patty
# rests

# use API that take an iterable
&amp;gt;&amp;gt;&amp;gt; from collections import Counter
&amp;gt;&amp;gt;&amp;gt; ingredients = Counter(best_burger_generator())
&amp;gt;&amp;gt;&amp;gt; ingredients
Counter({&amp;#39;bun&amp;#39;: 2, &amp;#39;patty&amp;#39;: 2, &amp;#39;cheese&amp;#39;: 2, &amp;#39;veggies&amp;#39;: 1, &amp;#39;sause&amp;#39;: 1, &amp;#39;onion&amp;#39;: 1})&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id="generator-in-action"&gt;4. Generator in action&lt;/h1&gt;
&lt;p&gt;To demonstrate some examples using generators, I’m going to show you how to solve problems without them, and then with them, so we could compare the different flavors.&lt;/p&gt;
&lt;h3 id="fibonacci-number-series"&gt;Fibonacci number series&lt;/h3&gt;
&lt;p&gt;Assuming we have a function to calculate the incredible series of data - the first n fibonacci numbers. This is the recursive solution most of us learned (with caching to get some performance):&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;# Recursive solution to get the first 10 fibonacci numbers
import functools

@functools.lru_cache()
def fibonacci(nth):
    &amp;quot;Calculate the nth fibonacci number.&amp;quot;
    if nth &amp;lt; 2:
        return 1
    return fibonacci(nth-2) + fibonacci(nth-1)

def fibonacci_series(n):
    result = []
    for i in range(n):
        result.append(fibonacci(i))
    return result

&amp;gt;&amp;gt;&amp;gt; fibonacci_series(10)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And here’s an iterative solution with generator:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;# Iterative solution to get the first 10 fibonacci numbers using generator
def fibonacci_generator(nth):
    &amp;quot;Yield the first nth fibonacci number.&amp;quot;
    n, m = 0, 1
    for _ in range(nth):
        yield m
        n, m = m, n+m

&amp;gt;&amp;gt;&amp;gt; f = fibonacci_generator(10)
&amp;gt;&amp;gt;&amp;gt; list(f)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I love recursion. I think they are elegant and beautiful. However, I do find the generator version of the solution much easier for my brain. If you only compare the &lt;code&gt;fibonacci&lt;/code&gt; function and the &lt;code&gt;fibonacci_generator&lt;/code&gt; function, the difference may not be significant, and the coding style really depends on personal preferences. So I say it’s a draw. Let’s look at other examples.&lt;/p&gt;
&lt;h3 id="sliding-window"&gt;Sliding window&lt;/h3&gt;
&lt;p&gt;Given a sequence and the window size, an example of sliding window function’s input-output pair is: &amp;gt; &lt;code&gt;'ABCDEF', size=2 -&amp;gt; 'AB', 'BC', 'CD', 'DE', 'EF'&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;A naive iterative solution is:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def sliding_window(sequence, size):
    result = []
    for i in range(len(sequence)-size+1):
        result.append(sequence[i:i+size])
    return result

&amp;gt;&amp;gt;&amp;gt; sliding_window(&amp;#39;ABCDEF&amp;#39;, 2)
[&amp;#39;AB&amp;#39;, &amp;#39;BC&amp;#39;, &amp;#39;CD&amp;#39;, &amp;#39;DE&amp;#39;, &amp;#39;EF&amp;#39;]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A generator approach is:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def sliding_window(sequence, size):
    for i in range(len(sequence)-size+1):
        yield sequence[i:i+size]

&amp;gt;&amp;gt;&amp;gt; list(sliding_window(&amp;#39;ABCDEF&amp;#39;, 2))
[&amp;#39;AB&amp;#39;, &amp;#39;BC&amp;#39;, &amp;#39;CD&amp;#39;, &amp;#39;DE&amp;#39;, &amp;#39;EF&amp;#39;]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This example I think the generator approach is significantly better than the other. First off, the code is much cleaner. Second, the purpose of the sliding window function is to be consumed by another function, one-at-a-time. Why keep duplicates hanging around in memory?&lt;/p&gt;
&lt;p&gt;Say, you have a large data set for a machine learning model. The sliding window is used to segment the data for training and cross validation. Data &lt;code&gt;A&lt;/code&gt; for training while &lt;code&gt;B&lt;/code&gt; for cross validation; then, &lt;code&gt;B&lt;/code&gt; for training, &lt;code&gt;C&lt;/code&gt; for cross validation. In this case, you really don’t need all the other data while working on the current one.&lt;/p&gt;
&lt;h1 id="conclusion"&gt;5. Conclusion&lt;/h1&gt;
&lt;p&gt;Being fluent in using generators is one of the things that took my Python to the next level. They are expressive, cleaner, and for most of the time, more efficient.&lt;/p&gt;
&lt;h1 id="action"&gt;6. Action&lt;/h1&gt;
&lt;p&gt;Next time when you’re writing some Python code, if there’s a function that need to return a sequence of data, think if it make sense to refactor it as a generator function.&lt;/p&gt;
&lt;p&gt;And for your own study, take a look at the Python official document page &lt;a href="https://docs.python.org/3/library/itertools.html"&gt;10.1 itertools&lt;/a&gt;. There are lots of examples of using the &lt;code&gt;yield&lt;/code&gt; expression.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/decode-phone-number</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Decode your phone number with Clojure</title>
    <updated>2018-04-30T00:00:00Z</updated>
    <published>2018-04-30T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/decode-phone-number" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;The original article was shared on my &lt;a href="https://medium.com/@dawranliou/decode-your-phone-number-with-clojure-373ccbd11bb9"&gt;Medium&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The inspiration of this article came from the Cousera course, Functional Programming in Scala. I basically translate the Scala program in section 6 into the Clojure version you’re about to see. Kudos to Martin Odersky.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You might have seen ads with interesting phone numbers like: 1–800-FLOWER, 1–800-FREE-411, or 1–800-GOT-JUNK. Those are called phonewords, or mnemonic phone numbers. It’d be awesome to have a memorable phone number like 1–RANDY-DA-MAN. However, maybe your phone number already has a meaning. How cool is it to figure it out, well, using Clojure?&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;Let’s clarify the problem. What we want is to: find all the combination of words where the concatenation of words could be encoded to the given numbers. For example, given 5299626, we want to find “jazz man,” “lazy man,” or all other words.&lt;/p&gt;
&lt;p&gt;This problem is quite daunting at first glance. Mostly because of the recursive nature of it. For example, given the numbers 23456789, we want to know by splitting the first digit and the rest, we not only want to ask if 2 and 3456789 are both words, but also want to ask the ??&lt;/p&gt;
&lt;p&gt;We could break down the problem in the following steps:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Get a list of all English words.&lt;/li&gt;
&lt;li&gt;Get a map from English characters to numbers.&lt;/li&gt;
&lt;li&gt;Define a function that encode a English word to numbers.&lt;/li&gt;
&lt;li&gt;Reverse the map (from #2) by grouping all English words with the same word numbers.&lt;/li&gt;
&lt;li&gt;Define a (recursive) function to convert numbers to a set of possible word list.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let’s start from the beginning. To get a list of English words, thanks to Cousera course, Functional Programming in Scala, we’ll get it from the Internet:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(def words
  (clojure.string/split-lines
    (slurp &amp;quot;https://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/linuxwords.txt&amp;quot;)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We then defined the map from character to number. We get this by reversing the map mnem:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(def mnem
  {\2 &amp;quot;ABC&amp;quot;
   \3 &amp;quot;DEF&amp;quot;
   \4 &amp;quot;GHI&amp;quot;
   \5 &amp;quot;JKL&amp;quot;
   \6 &amp;quot;MNO&amp;quot;
   \7 &amp;quot;PQRS&amp;quot;
   \8 &amp;quot;TUV&amp;quot;
   \9 &amp;quot;WXYZ&amp;quot;})

(def char-code
  (into {} (for [[k vs] mnem
                 v vs]
             [v k])))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s write a function to encode a English word to numbers. This can be done by mapping all the letters to the corresponding number:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defn word-code
  [word]
  (apply str (map char-code (.toUpperCase word))))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step is to group all English words by their code. This is a one-liner to use the high level function group-by in Clojure:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(def words-for-num
  (group-by word-code words))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now this is the hardest part. We want to define a function to decode the number. The recursive part is in bold. This function looks like:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defn decode
  [number]
  (if (empty? number)                                      ;; #1
    #{()}
    (into #{} (for [split (range 1 (inc (.length number))) ;; #2
                    word (get words-for-num                ;; #3
                              (subs number 0 split)) 
                    rest (decode (subs number split))]     ;; #4
                (cons word rest)))))                       ;; #5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We use list comprehension to bind the symbols from multiple collections. The split symbol binds to the index number of which we want to split the number. (#2) If first part of the split can be found as a word (#3), we will combine (#5) the the word with the recursive solution (#4) from the rest of the split. The base case of the recursive function is a set of empty list. (#1)&lt;/p&gt;
&lt;p&gt;All together, the entire program is 30 lines of code:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(def words
  (clojure.string/split-lines (slurp &amp;quot;https://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/linuxwords.txt&amp;quot;)))

(def mnem
  {\2 &amp;quot;ABC&amp;quot; \3 &amp;quot;DEF&amp;quot; \4 &amp;quot;GHI&amp;quot; \5 &amp;quot;JKL&amp;quot; \6 &amp;quot;MNO&amp;quot; \7 &amp;quot;PQRS&amp;quot; \8 &amp;quot;TUV&amp;quot; \9 &amp;quot;WXYZ&amp;quot;})

(def char-code
  (into {} (for [[k vs] mnem
                 v vs]
             [v k])))

(defn word-code
  [word]
  (apply str (map char-code (.toUpperCase word))))

(def words-for-num
  (group-by word-code words))

(defn decode
  [number]
  (if (empty? number)
    #{()}
    (into #{} (for [split (range 1 (inc (.length number)))
                    word (get words-for-num (subs number 0 split))
                    rest (decode (subs number split))]
                (cons word rest)))))

(defn translate
  [number]
  (map (partial clojure.string/join &amp;quot; &amp;quot;) (decode number)))

(translate &amp;quot;5299626&amp;quot;)
;; (&amp;quot;lazy Nan&amp;quot; &amp;quot;jazz man&amp;quot; &amp;quot;lazy Mao&amp;quot; &amp;quot;jazz Nan&amp;quot; &amp;quot;lazy man&amp;quot; &amp;quot;jazz Mao&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thoughts&lt;/p&gt;
&lt;p&gt;Discovering Clojure has been the best thing to me as a programmer since Python. It was very challenging initially and it totally changed the way I view programming languages. I’m still pretty new to this language, but I love it because it is beautiful and powerful. Let me know what you think of Clojure!&lt;/p&gt;
&lt;p&gt;Also, please share and clap this post if you think this is interesting/helpful to you!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/event-driven-clojurescript-front-end-with-core-async</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Implementing an Event-Driven ClojureScript mini-framework with core.async</title>
    <updated>2021-07-18T00:00:00Z</updated>
    <published>2021-07-18T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/event-driven-clojurescript-front-end-with-core-async" type="text/html"/>
    <content type="html">&lt;p&gt;This was my experiment of re-implementing a lighter version of the popular ClojureScript front-end framework, &lt;a href="http://day8.github.io/re-frame/"&gt;&lt;code&gt;re-frame&lt;/code&gt;&lt;/a&gt;, for the purpose of studying.[^1] A demo project of the result can be found here - &lt;a href="https://github.com/dawranliou/mini-reframe"&gt;&lt;code&gt;mini-reframe&lt;/code&gt;&lt;/a&gt;. In the project README, you can see the section &lt;a href="https://github.com/dawranliou/mini-reframe#self-guided-source-code-tour"&gt;“Self-guided source code tour”&lt;/a&gt; if you like to read the code. In this post, I’d walk you through the steps of implementing it from scratch.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Disclaimer:&lt;/strong&gt; It is not my goal to convince you to implement your own &lt;code&gt;re-frame&lt;/code&gt; from scratch for your apps. I merely wanted to share what I learned from &lt;code&gt;re-frame&lt;/code&gt; by replicating what I deem to be its most essential concepts in this tutorial-like article.&lt;/p&gt;
&lt;p&gt;If you come to this article wondering whether to use &lt;code&gt;re-frame&lt;/code&gt; or just roll your own framework, please use &lt;code&gt;re-frame&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If you are pretty familiar with using &lt;code&gt;re-frame&lt;/code&gt;, never looked at its source code, and wondering what’s happening under the cover, this article is for you.&lt;/p&gt;
&lt;h2 id="prerequisite"&gt;Prerequisite&lt;/h2&gt;
&lt;p&gt;To get started, you need a ClojureScript project and preferably any live-reloading tool like &lt;a href="https://figwheel.org/"&gt;&lt;code&gt;figwheel-main&lt;/code&gt;&lt;/a&gt; or &lt;a href="https://github.com/thheller/shadow-cljs"&gt;&lt;code&gt;shadow-cljs&lt;/code&gt;&lt;/a&gt;. If you are starting from scratch, using &lt;a href="https://rigsomelight.com/figwheel-main-template/"&gt;&lt;code&gt;figwheel-main&lt;/code&gt;&lt;/a&gt; is a good option.&lt;/p&gt;
&lt;p&gt;Once your project is ready, add the following dependencies if you haven’t done so already:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;a href="https://github.com/clojure/core.async"&gt;&lt;code&gt;core.async&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/reagent-project/reagent/"&gt;&lt;code&gt;reagent&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="why-event-driven"&gt;Why event-driven?&lt;/h2&gt;
&lt;p&gt;The way I see it, an event-driven architecture is modeling after systems that need to handle concurrent events by separating the &lt;strong&gt;when (it happens)&lt;/strong&gt; from the &lt;strong&gt;what (to do about it)&lt;/strong&gt;. Take web UIs for example. Browser JavaScript uses this model to handle mouse events, keyboard events, focus events, etc., internally in the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop"&gt;event loop&lt;/a&gt;. We can define what to do on receiving certain events and let the browser figure out when those events happen.&lt;/p&gt;
&lt;p&gt;Nowadays, apps can be complex. Sometimes the mouse and keyboard events might not be the right level of abstraction for an app. You might want the events to be more abstract such as a “user-agrees-to-terms-of-service” event or a “server-cannot-validate-user-credentials” event. In this case, an application level event-driven framework, such as &lt;code&gt;re-frame&lt;/code&gt;, would be helpful.&lt;/p&gt;
&lt;p&gt;We are going to build one for ourselves today.&lt;/p&gt;
&lt;h2 id="core-event-loop"&gt;Core event loop&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;re-frame&lt;/code&gt; at its core runs the &lt;code&gt;EventQueue&lt;/code&gt; that is implemented as a finite state machine (FSM for short). You can find the source &lt;a href="https://github.com/day8/re-frame/blob/master/src/re_frame/router.cljc#L71"&gt;here&lt;/a&gt; if you are interested. The finite states of the &lt;code&gt;EventQueue&lt;/code&gt; are: &lt;code&gt;:idle&lt;/code&gt;, &lt;code&gt;:scheduled&lt;/code&gt;, &lt;code&gt;:running&lt;/code&gt;, or &lt;code&gt;:paused&lt;/code&gt;. it maintains a queue of events and &lt;a href="https://github.com/day8/re-frame/blob/master/src/re_frame/router.cljc#L179"&gt;&lt;code&gt;handle&lt;/code&gt;&lt;/a&gt;s the events one at a time.&lt;/p&gt;
&lt;p&gt;Instead of implementing our own FSM from scratch, we’ll be using &lt;code&gt;core.async&lt;/code&gt;, &lt;em&gt;“a Clojure library providing facilities for async programming and communication.”&lt;/em&gt; Interestingly enough, under the covers core.async creates a &lt;strong&gt;state machine&lt;/strong&gt; to turn synchronous / blocking looking code into asynchronous / non-blocking code. [^2] Using the state machine provided by &lt;code&gt;core.async&lt;/code&gt; to implement our event queue FSM seems to me that we are on the right track.&lt;/p&gt;
&lt;p&gt;A naive implementation is to run an infinite &lt;code&gt;go-loop&lt;/code&gt; that will park (pause) the execution at the input event channel:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(require &amp;#39;[clojure.core.async :as a])

(def events-ch (a/chan))  ; The input event channel

(a/go-loop []
  (let [event (a/&amp;lt;! events-ch)]  ; Park the execution till receiving an event
    ;; Do something ...
    (js/console.log event)
    )
  (recur))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The Inversion-of-Control (IoC) happens at the async take function (&lt;code&gt;a/&amp;lt;!&lt;/code&gt;). Only when an event is put onto the channel will the &lt;code&gt;go-loop&lt;/code&gt; continue executing the rest of its body until it is parked again.&lt;/p&gt;
&lt;p&gt;Next, we’ll be re-implementing some of the &lt;code&gt;re-frame.core&lt;/code&gt; functions, following &lt;code&gt;re-frame&lt;/code&gt;’s data loop [^3] concept.&lt;/p&gt;
&lt;h2 id="event-dispatching"&gt;Event dispatching&lt;/h2&gt;
&lt;p&gt;For event dispatching, all we need is to put events onto the shared &lt;code&gt;events-ch&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(defn dispatch!
  [event]
  (a/put! events-ch event))

(comment
  (dispatch! [:event-name :event-data]))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I dig the re-frame’s convention that every event is a vector of &lt;code&gt;[EVENT_TYPE EVENT_DATA...]&lt;/code&gt; so from the rest of the article, an &lt;code&gt;event&lt;/code&gt; is a vector.&lt;/p&gt;
&lt;h2 id="event-handling"&gt;Event handling&lt;/h2&gt;
&lt;p&gt;Once the core event loop received an &lt;code&gt;event&lt;/code&gt;, we’ll need to decide what to do with it. &lt;code&gt;re-frame&lt;/code&gt; has a great way to push the side effects to the application boundary by adding an extra layer of indirection between events and their effects. Side effects only happen in a very controlled manner, and effect handlers can be entirely descriptive pure functions. This is what we are going to do too!&lt;/p&gt;
&lt;p&gt;Event handlers receive two arguments, the snapshot of the current app-state, the &lt;code&gt;db&lt;/code&gt;, and the &lt;code&gt;event&lt;/code&gt; vector. Depending on your tastes, there are many ways to handle events. You need a mechanism to dispatch the functionalities based on the &lt;code&gt;event&lt;/code&gt; type, which is the first element in the &lt;code&gt;event&lt;/code&gt;. Here are a couple of options for you:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;;; 1. Implemented as a case form
(defn handle-event
  [db [event-type &amp;amp; event-data :as event]]
  (case event-type
    :event-1 (fn [db event] ...)
    :event-2 (fn [db event] ...)))

;; 2. Implemented as a multimethod
(defmulti handle-event (fn [_db event] (first event)))
(defmethod handle-event :event-1
  [db event]
  ...)

;; 3. Implemented as a map
(def event-handlers
  {:event-1 (fn [db event] ...)
   :event-2 (fn [db event] ...)})

(defn handle-event
  [db event-handlers [event-type &amp;amp; _event-params :as event]]
  ((event-handlers event-type) db event))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I prefer to implement the handlers using the 3rd option because that feels more portable to me.&lt;/p&gt;
&lt;h2 id="effect-fx-handling"&gt;Effect (&lt;code&gt;fx&lt;/code&gt;) handling&lt;/h2&gt;
&lt;p&gt;In the section above, we haven’t defined what the event handler functions return. Again, learning from our beloved project &lt;code&gt;re-frame&lt;/code&gt;, it’s a good idea that our event handlers return a descriptive map of effects, such as:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;code&gt;:db&lt;/code&gt; effect to mutate the app-state ratom,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;:dispatch&lt;/code&gt; effect to dispatch another event&lt;/li&gt;
&lt;li&gt;&lt;code&gt;:http&lt;/code&gt; effect to handle AJAX,&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Unlike event handlers, which are pure functions, the effect handlers are messier that it receives the app-state ratom as an argument and can cause side effects. Although they are side-effect-y, their implementations are pretty predictable. Out-of-the-box &lt;code&gt;re-frame&lt;/code&gt; provides several of the standard effect handlers like &lt;code&gt;:db&lt;/code&gt; and &lt;code&gt;:dispatch&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Below is an example of using a plain map to implement our &lt;code&gt;fx-handlers&lt;/code&gt;. Again, there are many ways to write the effect handling logic as we did for event handling.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(defn do-db!
  [page-state _effect-key new-db]
  (when-not (identical? new-db @page-state)
    (reset! page-state new-db)))

(defn do-dispatch!
  [_page-state _effect-key event-v]
  (dispatch! event-v))

(def fx-handlers
  {:db       do-db!
   :dispatch do-dispatch!})

(defn handle-fx!
  [state fx-handlers {:keys [db] :as effects-map}]
  ;; Do the :db effect before any other effects
  (when db
    ((fx-handler :db) state :db db))
  (doseq [[effect-key effect-value] (dissoc effects-map :db)]
    ((fx-handler effect-key) state effect-key effect-value)))&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="revisit-the-core-event-loop"&gt;Revisit the core event loop&lt;/h2&gt;
&lt;p&gt;Previously, we conveniently hide the details in the core event loop. Let’s get back to it now since we (sort of) implemented the &lt;code&gt;handle-event&lt;/code&gt; and &lt;code&gt;handle-fx!&lt;/code&gt; functions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(require &amp;#39;[reagent.core :as r])
(defonce app-state (r/atom {}))

(a/go-loop []
  (let [event (a/&amp;lt;! events-ch)
        fxs   (handle-event @app-state event-handlers event)]
    (handle-fx! app-state fx-handlers fxs)
  (recur)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We finally declared our app state ratom to use it in the event handlers and the effect handlers. Interestingly, we ended up with a very straightforward transducer that transduces an &lt;code&gt;event&lt;/code&gt; to &lt;code&gt;fxs&lt;/code&gt;, then to side effects, and finally discards the return value. If you are interested in the transducer implementation you can find it &lt;a href="https://github.com/dawranliou/mini-reframe/blob/main/src/mini_reframe/event_loop.cljs#L21-L25"&gt;here in the repo&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="query-subscription"&gt;Query subscription&lt;/h2&gt;
&lt;p&gt;Since we don’t want to re-render the whole app when we only touched a particular part of the app-state, we need to be more specific. &lt;code&gt;re-frame.core/subscribe&lt;/code&gt; is a nice API to do such a thing. Under the hood, the API returns a &lt;code&gt;reagent.ratom/Reaction&lt;/code&gt; for you and handles caching so you don’t run the same subscription handler twice. &lt;code&gt;Reaction&lt;/code&gt; is how we avoid re-rendering the whole app because it only signals a re-rendering when its body updates. Although &lt;code&gt;Reaction&lt;/code&gt;s are a powerful tool, we should not use them directly inside a form-1 component.[^3]&lt;/p&gt;
&lt;p&gt;For simplicity, we’ll pre-calculate every subscription in a subscription map. Although we cannot create subscriptions lazily since every subscription is bound at compile time, we also don’t have to worry about caching and the problem with component life-cycle. Here’s an example of subscriptions in the demo project:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(def subscribe
  {:h    (reagent.ratom/make-reaction
           #(str &amp;quot;H - &amp;quot; (or (get-in @page-state [:h]) 0)))
   :j    (reagent.ratom/make-reaction
           #(str &amp;quot;j - &amp;quot; (or (get-in @page-state [:j]) 0)))
   :k    (reagent.ratom/make-reaction
           #(str &amp;quot;k - &amp;quot; (or (get-in @page-state [:k]) 0)))
   :l    (reagent.ratom/make-reaction
           #(str &amp;quot;L - &amp;quot; (or (get-in @page-state [:l]) 0)))
   :http (reagent.ratom/make-reaction
           #(str &amp;quot;Server status - &amp;quot;
                 (name (or (get-in @page-state [:http]) :unknown))))})&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="view-and-dom"&gt;View and DOM&lt;/h2&gt;
&lt;p&gt;With the functions we’ve built so far, the app page can now look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(defn main []
  [:&amp;lt;&amp;gt;
   [:h1 &amp;quot;App&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :h}])} &amp;quot;H&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :j}])} &amp;quot;J&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :k}])} &amp;quot;K&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :l}])} &amp;quot;L&amp;quot;]
   [:button {:on-click #(dispatch! [:reset])} &amp;quot;Reset&amp;quot;]
   [:ul
    [:li @(subscribe :h)]
    [:li @(subscribe :j)]
    [:li @(subscribe :k)]
    [:li @(subscribe :l)]]
   [:p @(subscribe :http)]])&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="putting-it-all-together"&gt;Putting it all together&lt;/h2&gt;
&lt;p&gt;Our app can now look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(ns ^:figwheel-hooks mini-reframe.app
  (:require
   [clojure.core.async :as a]
   [goog.dom :as gdom]
   [reagent.core :as r]
   [reagent.dom :as rdom]
   [reagent.ratom]))

(def events-ch (a/chan))

(defn dispatch! [event]
  (a/put! events-ch event))

(defonce app-state (r/atom {}))

(def subscribe
  {:h    (reagent.ratom/make-reaction
           #(str &amp;quot;H - &amp;quot; (or (get-in @app-state [:h]) 0)))
   :j    (reagent.ratom/make-reaction
           #(str &amp;quot;j - &amp;quot; (or (get-in @app-state [:j]) 0)))
   :k    (reagent.ratom/make-reaction
           #(str &amp;quot;k - &amp;quot; (or (get-in @app-state [:k]) 0)))
   :l    (reagent.ratom/make-reaction
           #(str &amp;quot;L - &amp;quot; (or (get-in @app-state [:l]) 0)))
   :http (reagent.ratom/make-reaction
           #(str &amp;quot;Server status - &amp;quot;
                 (name (or (get-in @app-state [:http]) :unknown))))})

(defn handle-init
  [_db _event]
  {:http {:method     :get
          :url        &amp;quot;http://localhost:1111&amp;quot;
          :on-success [:good-http-result]
          :on-failure [:bad-http-result]}})

(defn handle-good-http-result
  [db [_event-type data]]
  {:db (assoc db :http (:body data))})

(defn handle-bad-http-result
  [db [_event-type data]]
  {:db (assoc db :http (:body data))})

(defn handle-clicked
  [db [_event-type {:keys [element] :as _data}]]
  {:db (update db element inc)})

(defn handle-reset
  [db _event]
  {:db (dissoc db :h :j :k :l)})

(def event-handlers
  {:init             handle-init
   :good-http-result handle-good-http-result
   :bad-http-result  handle-bad-http-result
   :clicked          handle-clicked
   :reset            handle-reset})

(defn handle-event
  [db event-handlers [event-type &amp;amp; _event-params :as event]]
  ((event-handlers event-type) db event))

(defn do-db!
  [page-state _effect-key new-db]
  (when-not (identical? new-db @page-state)
    (reset! page-state new-db)))

(defn do-http!
  [_page-state _effect-key {:keys [_method _url on-success on-failure]}]
  (if (zero? (rand-int 3))
    ;; Simulate HTTP failures once out of every 3 tries
    (js/setTimeout
      #(dispatch! (conj on-failure {:body :bad}))
      (+ 2000 (rand-int 1000)))
    (js/setTimeout
      #(dispatch! (conj on-success {:body :good}))
      (+ 2000 (rand-int 1000)))))

(defn do-dispatch!
  [_page-state _effect-key event-v]
  (dispatch! event-v))

(def fx-handlers
  {:db       do-db!
   :http     do-http!
   :dispatch do-dispatch!})

(defn handle-fx!
  [state fx-handlers {:keys [db] :as effects-map}]
  ;; Do the :db effect before any other effects
  (when db
    ((fx-handlers :db) state :db db))
  (doseq [[effect-key effect-value] (dissoc effects-map :db)]
    ((fx-handlers effect-key) state effect-key effect-value)))

(a/go-loop []
  (let [event (a/&amp;lt;! events-ch)
        fxs   (handle-event @app-state event-handlers event)]
    (handle-fx! app-state fx-handlers fxs)
  (recur)))

(defn main []
  [:&amp;lt;&amp;gt;
   [:h1 &amp;quot;App&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :h}])} &amp;quot;H&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :j}])} &amp;quot;J&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :k}])} &amp;quot;K&amp;quot;]
   [:button {:on-click #(dispatch! [:clicked {:element :l}])} &amp;quot;L&amp;quot;]
   [:button {:on-click #(dispatch! [:reset])} &amp;quot;Reset&amp;quot;]
   [:ul
    [:li @(subscribe :h)]
    [:li @(subscribe :j)]
    [:li @(subscribe :k)]
    [:li @(subscribe :l)]]
   [:p @(subscribe :http)]])

(defn get-app-element []
  (gdom/getElement &amp;quot;app&amp;quot;))

(defn mount [el]
  (rdom/render [main] el))

(defn mount-app-element []
  (when-let [el (get-app-element)]
    (mount el)))

(defn init! []
  ;; conditionally start your application based on the presence of an &amp;quot;app&amp;quot;
  ;; element this is particularly helpful for testing this ns without launching
  ;; the app
  (dispatch! [:init])
  (mount-app-element))

(init!)

;; specify reload hook with ^;after-load metadata
(defn ^:after-load on-reload []
  (mount-app-element))&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;There you go! That’s our event-driven framework in &lt;code&gt;core.async&lt;/code&gt;. Although it is quite possible to implement our own poor man’s &lt;code&gt;re-frame&lt;/code&gt;, I wouldn’t recommend doing it for serious work. In this article, we cut a lot of corners to get the happy codepath working. Honestly, there might be some serious bugs, or it might break your reloading workflow in some profound ways.&lt;/p&gt;
&lt;p&gt;There is a large community behind &lt;code&gt;re-frame&lt;/code&gt; developing toolings and libraries around it. It’s also quite beneficial to do things the &lt;code&gt;re-frame&lt;/code&gt; way [^5]. If you are looking for a way to model your &lt;code&gt;reagent&lt;/code&gt; app using an event-driven approach, I’d recommend &lt;code&gt;re-frame&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I had a lot of fun studying &lt;code&gt;re-frame&lt;/code&gt; source code. In doing so, I got a lot more confident to use it as a dependency for my projects. Hopefully, this article will give you some ideas of what &lt;code&gt;re-frame&lt;/code&gt; does for you under the cover.&lt;/p&gt;
&lt;h2 id="footnotes"&gt;Footnotes&lt;/h2&gt;
&lt;p&gt;[^1] To be honest, I wasn’t a big fan of &lt;code&gt;re-frame&lt;/code&gt; before because I didn’t see the value of using a framework for managing my states while being fully capable of managing them myself. I also didn’t like having a big dependency unless I have to. After studying quite a significant bit of &lt;code&gt;re-frame&lt;/code&gt;’s source code (which doesn’t seem so big of a dependency anymore), I am now convinced that the cost of having it as a dependency is pretty well justified.&lt;/p&gt;
&lt;p&gt;[^2] From [“The State Machines of core.async”]&lt;/p&gt;
&lt;p&gt;[^3] The Six Dominoes of &lt;code&gt;re-frame&lt;/code&gt;’s data loop are:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Event dispatch&lt;/li&gt;
&lt;li&gt;Event handling&lt;/li&gt;
&lt;li&gt;Effect handling&lt;/li&gt;
&lt;li&gt;Query&lt;/li&gt;
&lt;li&gt;View&lt;/li&gt;
&lt;li&gt;DOM&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;[^4] From the &lt;code&gt;reagent.core/reaction&lt;/code&gt; doc:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;New Reaction is created everytime reaction is called, so caller needs to take care that new reaction isn’t created e.g. every component render, by using with-let, form-2 or form-3 components or other solutions. Consider using reagent.core/track, for function that caches the derafable value, and can thus be safely used in e.g. render function safely.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;[^5] See &lt;a href="https://purelyfunctional.tv/article/react-vs-re-frame/"&gt;“6 things Reacters do that Re-framers avoid” by PurelyFunctional.tv&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Links&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/dawranliou/mini-reframe"&gt;&lt;code&gt;mini-reframe&lt;/code&gt; Github page&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://day8.github.io/re-frame/"&gt;re-frame&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/reagent-project/reagent/"&gt;reagent&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/clojure/core.async"&gt;core.async&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/clojure-inspect</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Inspect Java Objects with Clojure</title>
    <updated>2019-02-09T00:00:00Z</updated>
    <published>2019-02-09T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/clojure-inspect" type="text/html"/>
    <content type="html">&lt;p&gt;The more I work with Clojure, the more frustration I found to work with Java objects. Mostly, it feels an unnecessary process to go through the class definition to find the getter methods to access the data I want, especially when the data is buried under multiple layers of classes deep.&lt;/p&gt;
&lt;p&gt;In this article, I’ll explain a recipe to create a graphical inspector UI to explore Java objects, frustration free! The key is to use the &lt;code&gt;clojure.inspector&lt;/code&gt; for the visualization and &lt;code&gt;clojure.org/java.data&lt;/code&gt; for recursively converting Java beans to Clojure data structure.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;&lt;em&gt;Note: Thanks to reddit user &lt;span class="citation" data-cites="vvvvalvalval"&gt;@vvvvalvalval&lt;/span&gt; to point out &lt;a href="https://clojure.org/guides/repl/data_visualization_at_the_repl#_dealing_with_mysterious_values_advanced"&gt;Programming at the REPL: Data Visualization&lt;/a&gt; is also a great place to learn more about inspecting values in the REPL. I was inspired by it to write this article. If you are just starting to learn Clojure REPL, definitely check out the link first!&lt;/em&gt;&lt;/p&gt;
&lt;h2 id="tools---clojure.inspector-and-clojure.java.data"&gt;Tools - &lt;code&gt;clojure.inspector&lt;/code&gt; and &lt;code&gt;clojure.java.data&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;On the official website, &lt;a href="https://clojure.github.io/clojure/clojure.inspector-api.html"&gt;&lt;code&gt;clojure.inspector&lt;/code&gt;&lt;/a&gt; is:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Graphical object inspector for Clojure data structures.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It provides three APIs: &lt;code&gt;inspect&lt;/code&gt;, &lt;code&gt;inspect-table&lt;/code&gt;, and &lt;code&gt;inspect-tree&lt;/code&gt;. To differentiate them, the first thing to notice is that &lt;code&gt;inspect&lt;/code&gt; and &lt;code&gt;inspect-tree&lt;/code&gt; doesn’t have any assumption on the shape of the input data, while &lt;code&gt;inspect-table&lt;/code&gt; assumes the data is sequential and its elements all have the same length. Secondly, &lt;code&gt;inspect-tree&lt;/code&gt; creates a expendable tree to explore data if the data is hierarchical. Here are some examples below. We’ll be focusing more on &lt;code&gt;inspect-tree&lt;/code&gt; in the rest of the article.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; try this in your repl

(require &amp;#39;[clojure.inspector :as insp])
(def d [{:a &amp;quot;a1&amp;quot; :b &amp;quot;b1&amp;quot;} {:a &amp;quot;a2&amp;quot; :b &amp;quot;b2&amp;quot;} {:a &amp;quot;a3&amp;quot; :b &amp;quot;b3&amp;quot;}])
(insp/inspect d)
(insp/inspect-table d)
(insp/inspect-tree d)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The built-in &lt;code&gt;clojure.inspctor&lt;/code&gt; namespace is very useful for exploring data and the interactive development for Clojure. Instead of printing everything down in the repl, using a graphical tool like this is a much superior experience, in my opinion.&lt;/p&gt;
&lt;p&gt;Next question is, when we do interop with Java, Java objects doesn’t automatically become Clojure data types like &lt;code&gt;clojure.lang.IPersistentMap&lt;/code&gt;. The built-in function &lt;a href="https://clojuredocs.org/clojure.core/bean"&gt;&lt;code&gt;bean&lt;/code&gt;&lt;/a&gt; is helpful. However, the time that I really need to inspect a Java object is usually when the object has too many layers of classes nested. In this case, I found the &lt;code&gt;clojure.org/java.data&lt;/code&gt; library is the right tool.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/clojure/java.data"&gt;&lt;code&gt;clojure.org/java.data&lt;/code&gt;&lt;/a&gt; is:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Functions for recursively converting Java beans to Clojure and vice versa. Future home of Java beans and properties support from the old clojure-contrib&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id="demo"&gt;Demo&lt;/h2&gt;
&lt;p&gt;To demonstrate, let’s setup a Java &amp;amp; Clojure polyglot project with Leiningen like this:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defproject inspector &amp;quot;0.1.0-SNAPSHOT&amp;quot;
  ;; ...
  :dependencies [[org.clojure/clojure &amp;quot;1.10.0&amp;quot;]
                 [org.clojure/java.data &amp;quot;0.1.1&amp;quot;]]
  :source-paths      [&amp;quot;src/clojure&amp;quot;]
  :java-source-paths [&amp;quot;src/java&amp;quot;])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In order to make this work, we need to implement our Java class as a &lt;a href="https://www.geeksforgeeks.org/javabean-class-java/"&gt;JavaBean&lt;/a&gt;. Here’s the Java class to inspect:&lt;/p&gt;
&lt;pre class="java"&gt;&lt;code&gt;package inspector;

public class MyClass implements java.io.Serializable {
    private String name;
    private InnerClassA a;

    public MyClass() {
        this.name = &amp;quot;MyClass&amp;quot;;
        this.a = new InnerClassA();
    }

    public String getName() {return this.name;}
    public void setName(String name) {this.name = name;}
    public InnerClassA getA() {return this.a;}
    public void setA(InnerClassA a) {this.a = a;}

    public static class InnerClassA implements java.io.Serializable {
        private String name;
        public InnerClassA() {this.name = &amp;quot;InnerClassA&amp;quot;;}
        public String getName() {return this.name;}
        public void setName(String name) {this.name = name;}
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now you can connect to the REPL and do:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;;; Transform java object to clojure map
(-&amp;gt; (inspector.MyClass.)
    java/from-java)
;; {:a {:name &amp;quot;InnerClassA&amp;quot;}, :name &amp;quot;MyClass&amp;quot;}

;; The inverse works too if the JavaBean is implemented correctly
(-&amp;gt;&amp;gt; {:name &amp;quot;hi&amp;quot; :a {:name &amp;quot;hey&amp;quot;}}
     (java/to-java inspector.MyClass))

;; Now you can use inpsect-tree to visualize the map
(-&amp;gt; (inspector.MyClass.)
    java/from-java
    insp/inspect-tree)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here’s the inspector GUI you’ll see: &lt;img src="images/clojure-inspector.png" alt="alt clojure inspector" /&gt;&lt;/p&gt;
&lt;p&gt;Though, there’re some limitations, for one:&lt;/p&gt;
&lt;pre class="java"&gt;&lt;code&gt;public class MyClass implements java.io.Serializable {
    // ...
    public MyClass getSelf() {return this;}
    // ...
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case, you’ll find an StackOverflowError when calling &lt;code&gt;java/from-java&lt;/code&gt; function. This is because all the &lt;code&gt;get*&lt;/code&gt; methods are consider getter methods to access class member and were invoked recursively. In the example above, you just need to rename &lt;code&gt;getSelf&lt;/code&gt; to &lt;code&gt;returnSelf&lt;/code&gt; or any name without the “get” prefix to avoid the error.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Clojure is really great for:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Transforming data (e.g. &lt;code&gt;clojure.java.data&lt;/code&gt;), and&lt;/li&gt;
&lt;li&gt;Exploring data (e.g. &lt;code&gt;clojure.inspector&lt;/code&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Using the simple recipe explained in the article, I found it more and more pleasant to do interop with Java in the Clojure world.&lt;/p&gt;
&lt;p&gt;If you find this article helpful, please help me to share it!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/my-emacs-clojure-dev-env-overview</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>My Emacs Clojure Development Environment Overview</title>
    <updated>2020-11-12T00:00:00Z</updated>
    <published>2020-11-12T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/my-emacs-clojure-dev-env-overview" type="text/html"/>
    <content type="html">&lt;h1 id="preface"&gt;Preface&lt;/h1&gt;
&lt;p&gt;To me, Emacs isn’t a text editor but rather an extremely flexible development environment that allows anyone to optimize their workflow. I used to be a Vim user and did everything inside the terminal: Vim for code editing, bash commands for running/testing code, and git cli for all other git operations. I wasn’t in any sense a Vim superuser. However, I felt pretty comfortable to do most of my day-to-day work inside the terminal.&lt;/p&gt;
&lt;p&gt;For the past two years, I got into the Clojure programming community and made a very audacious move to learn Emacs at the same time. To me, learning Emacs was just as hard, if not harder, as learning Clojure itself. However, learning either subjects has paid off far more than I had expected. In this post, I will share an overview of my current development environment setup and explain my rationale of some of the key bindings that I use.&lt;/p&gt;
&lt;h1 id="magit---git-porcelain"&gt;Magit - git porcelain&lt;/h1&gt;
&lt;p&gt;&lt;a href="https://magit.vc/"&gt;Magit&lt;/a&gt; is one of the most powerful powerful packages available on Emacs. It is also the package that made me rethink my entire workflow. If you don’t known, Magit is a git porcelain that makes all the fancy git operations within Emacs. I used to enjoy doing all git operations inside terminal. I rarely do it lately because of how great Magit is. If I were to stop using Emacs for writing code, I’d definitely continue using Magit until I find another comparable tool.&lt;/p&gt;
&lt;p&gt;I bind &lt;code&gt;magit-status&lt;/code&gt; to &lt;code&gt;command+g&lt;/code&gt; (also &lt;code&gt;&amp;lt;SPC&amp;gt; g g&lt;/code&gt; because of old habit using Doom Emacs.)&lt;/p&gt;
&lt;h1 id="cider---advanced-clojure-integrated-environment"&gt;Cider - advanced Clojure integrated environment&lt;/h1&gt;
&lt;p&gt;I use &lt;a href="https://cider.mx/"&gt;Cider&lt;/a&gt; to manage the nrepl sessions and to evaluate code. I used to rely on Cider for more things like looking up code definition but lately I’ve been experimenting that with &lt;code&gt;clojure-lsp&lt;/code&gt; which I’ll describe in the next section.&lt;/p&gt;
&lt;p&gt;I bind the Cider keys under a local leader key &lt;code&gt;&amp;lt;,&amp;gt;&lt;/code&gt;, which is only available in the clojure(script)-mode. This is a habit I developed during the time using Spacemacs and Doom Emacs though their keymaps are slightly different. Currently I only use it to evaluate code in three levels - to evaluate buffer, evaluate top-level vars, and evaluate s-expression. They are currently bound to &lt;code&gt;&amp;lt;,&amp;gt; e b&lt;/code&gt;, &lt;code&gt;&amp;lt;,&amp;gt; e f&lt;/code&gt;, and &lt;code&gt;&amp;lt;,&amp;gt; e e&lt;/code&gt;, which I’ll probably simplify by removing the middle &lt;code&gt;e&lt;/code&gt; later.&lt;/p&gt;
&lt;h1 id="lsp---code-jumping"&gt;LSP - code jumping&lt;/h1&gt;
&lt;p&gt;LSP is the text editor-agnostic protocol for IDE-like operations. It separates the concerns of those IDE-like capabilities and the actual implementation. For example, the LSP defines the capability of &lt;code&gt;textDocument/definition&lt;/code&gt; and the &lt;a href="https://github.com/snoe/clojure-lsp"&gt;clojure-lsp&lt;/a&gt; implements how to find the definition of a particular Clojure symbol. In Emacs, AFAIK there are two packages to support LSP interactions, &lt;a href="https://emacs-lsp.github.io/lsp-mode/"&gt;lsp-mode&lt;/a&gt; and &lt;a href="https://github.com/joaotavora/eglot"&gt;eglot&lt;/a&gt;. I’ve tried both in the past but I’m sticking with &lt;code&gt;lsp-mode&lt;/code&gt; at the moment.&lt;/p&gt;
&lt;p&gt;I bind &lt;code&gt;command+l&lt;/code&gt; to the lsp-keymap-prefix while I’m still learning it. So far I only need two functions: &lt;code&gt;lsp-find-definition&lt;/code&gt; and &lt;code&gt;lsp-find-references&lt;/code&gt; which are bound to &lt;code&gt;command+l g g&lt;/code&gt; and &lt;code&gt;command+l g r&lt;/code&gt; respectively. I’ll definitely re-bind those keys for easier access.&lt;/p&gt;
&lt;h1 id="lispy-lispyville---general-lisp-s-expression-editing"&gt;Lispy + Lispyville - general lisp s-expression editing&lt;/h1&gt;
&lt;p&gt;I use &lt;a href="https://github.com/abo-abo/lispy"&gt;Lispy&lt;/a&gt; and &lt;a href="https://github.com/noctuid/lispyville"&gt;Lispyville&lt;/a&gt; for most of the e-expression editing in Clojure mode instead of using smartparens or paredit or parinfer. I like the safe evil operations that are remapped by Lispyville so I don’t need to worry about unbalanced parens. However, I don’t use a lot of the keys other than slurping, barfing, and dragging s-expressions.&lt;/p&gt;
&lt;h1 id="dired---file-management"&gt;Dired - file management&lt;/h1&gt;
&lt;p&gt;I bind dired to &lt;code&gt;&amp;lt;SPC&amp;gt; d&lt;/code&gt; with just two key strokes for easier access. Dired mode was a powerful package that I overlooked for so long. It finally came into my radar thanks to the amazing &lt;a href="https://youtu.be/PMWwM8QJAtU"&gt;video&lt;/a&gt; by &lt;a href="https://twitter.com/daviwil"&gt;David Wilson&lt;/a&gt;. Dired was truly a missing piece in my workflow centered around Emacs. Having the ability to browse the filesystem naturally inside the Emacs buffer was absolutely a joy.&lt;/p&gt;
&lt;h1 id="eshell---direct-shell-access"&gt;Eshell - direct shell access&lt;/h1&gt;
&lt;p&gt;This is bound to &lt;code&gt;&amp;lt;SPC&amp;gt; e&lt;/code&gt; also for easier access. With all the packages above, there are rarely things I need to do directly in shell. For those things that has to be done inside shell, I usually do it in Eshell. However, there are times I do need something closer to the native terminal app on OSX, something I can start a long running process and bury it in the background. In these cases I’ll launch vterm instead. However, for some those off tasks like compiling code or start a docker container in the background, I prefer Eshell.&lt;/p&gt;
&lt;p&gt;Links: - &lt;a href="https://github.com/dawranliou/emacs.d"&gt;My current Emacs Config&lt;/a&gt; - &lt;a href="https://magit.vc/"&gt;Magit&lt;/a&gt; - &lt;a href="https://cider.mx/"&gt;Cider&lt;/a&gt; - &lt;a href="https://github.com/snoe/clojure-lsp"&gt;clojure-lsp&lt;/a&gt; - &lt;a href="https://emacs-lsp.github.io/lsp-mode/"&gt;lsp-mode&lt;/a&gt; - &lt;a href="https://github.com/joaotavora/eglot"&gt;eglot&lt;/a&gt; - &lt;a href="https://github.com/abo-abo/lispy"&gt;Lispy&lt;/a&gt; - &lt;a href="https://github.com/noctuid/lispyville"&gt;Lispyville&lt;/a&gt; - &lt;a href="https://twitter.com/daviwil"&gt;David Wilson&lt;/a&gt; - &lt;a href="https://www.youtube.com/c/SystemCrafters/videos"&gt;System Crafters&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/just-write-the-code</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Don’t think. Just write the code!</title>
    <updated>2018-04-02T00:00:00Z</updated>
    <published>2018-04-02T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/just-write-the-code" type="text/html"/>
    <content type="html">&lt;p&gt;Imaging you are given a brand new web project, some vague requirements, and a ton of freedom to choose the technical stacks, will you take it? My answer while a couple of months back was… “Hell yeah!” Even though I had never really worked on a real-world project except the blog app that was taught a thousand times from online tutorials.&lt;/p&gt;
&lt;p&gt;It had been a wonderful journey, with struggles, of course. I would love to share what I learned. Hope it sheds some lights on your coding journey too. To set the expectation right, let me give you some idea of my experience level before I started the project.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h1 id="before-i-started"&gt;Before I started&lt;/h1&gt;
&lt;p&gt;Okay, quick inventory check in my developer tool box before I started. In the fluent scale of 1 to 10, I had:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Python: 8. (I use list comprehension here and there, duh.)&lt;/li&gt;
&lt;li&gt;Flask: 5&lt;/li&gt;
&lt;li&gt;SQL: 2 (but I can use SQLAlchemy as the ORM: 5)&lt;/li&gt;
&lt;li&gt;JavaScript ES6: 2 (mostly because the syntax is similar to Python even though I had never learned it.)&lt;/li&gt;
&lt;li&gt;HTML: 5?&lt;/li&gt;
&lt;li&gt;CSS with Bootstrap: 5&lt;/li&gt;
&lt;li&gt;Git: 7 (still need to google how to git squash from time to time)&lt;/li&gt;
&lt;li&gt;REST architecture: 4? I know GET, POST, PUT, DELETE and 1 point for each.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Hell yeah, I could do this! What could go wrong?&lt;/p&gt;
&lt;h1 id="the-task"&gt;The Task&lt;/h1&gt;
&lt;p&gt;The task was to build an internal analytics application that touches several different other internal services inside the company. Due to intellectual property issue I cannot show the end product. However, imaging it’s like a dashboard that gathers several information into charts and tables. The user can also modify and download the data from the app.&lt;/p&gt;
&lt;h1 id="the-stack"&gt;The Stack&lt;/h1&gt;
&lt;p&gt;I wanted to build a single page app (SPA) because everybody was doing it. (The worst reason or the best reason to choose a technology. Your pick!) Python Flask backend was a natural choice for me because I didn’t have experience with the other popular frameworks. I did a blog app using Flask by following Miguel Grinberg’s Flask book before. Thus, I’ll use Flask to build a REST API service and leaves all the UI part to the frontend.&lt;/p&gt;
&lt;p&gt;I chose React to be my frontend framework because I had heard how good it was (and it still is today.) Angular was popular too but I had a bad experience with it several years back. Vuejs was a great choice but I was so excited to learn React so WTH.&lt;/p&gt;
&lt;h1 id="struggles"&gt;Struggles&lt;/h1&gt;
&lt;p&gt;There. Were. A. Lot. This part I just want to rant on the things I was struggling. If you don’t like it feel free to skip it to the lessons sections.&lt;/p&gt;
&lt;p&gt;I want to skip the struggles with understanding the user story since those weren’t technical. However, this might be time I struggled the most because I didn’t feel comfortable discussing out of thin air. I like to discuss on more concrete thing.&lt;/p&gt;
&lt;p&gt;In my opinion, Flask is great for building simple, small project, and stay simple and small. Don’t be mislead by the term “simple.” A simple problem does not guarantee a simple solution. As my favorite quote by Leonardo da Vinci:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Simplicity is the ultimate sophistication.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It takes a lot of thinking to build something that’s truly simple. And that was not what I was building from the beginning.&lt;/p&gt;
&lt;p&gt;Setting up the server and running my application was another struggle. It was especially hard if the IT policy blocks the external connections. This forced me to start resolving the dependencies from source code. Gotta say that I felt like a Linux guru when I compiled Python, Redis, SQLite, and other software from the source.&lt;/p&gt;
&lt;p&gt;Writing ugly React code was another struggle. In the back of my mind I knew there must be a better way. I was too afraid to refactor it because of the lack of any test. God I wish I knew how to write React tests.&lt;/p&gt;
&lt;h1 id="lesson-1---the-architect-vs-the-gardener"&gt;Lesson 1 - The Architect vs the Gardener&lt;/h1&gt;
&lt;p&gt;I like this analogy from one of my favorite author Brandon Sanderson. He said there are two types of writers — the architect and the gardener. The architect designs all the nitty-gritty details on the blueprints before building the house, whereas the gardener improvises while fixing the garden.&lt;/p&gt;
&lt;p&gt;To be honest, I would love to be the architect and receive praises like “he solved the problem by thinking!” I wanted to just think for a while, sit down, write code, and boom! Done! But the truth was, I was more towards to the gardener when I wrote the code. I thought only a bit, wrote a lot of code, deleted a lot of code, and rewrote a lot of code.&lt;/p&gt;
&lt;p&gt;Overtime, I found my gardening process actually very beneficial. When I was making a lot of trial-and-errors, I also learned many ways why things didn’t work. Those errors surely built up my understanding to the technologies I was using. Also the more comfortable I dealt with errors, the more experiences I gained. So, my philosophy is to be the gardener — write as much code as you can — when you don’t have much experience, and you’ll learn from it!&lt;/p&gt;
&lt;h1 id="lesson-2---trust-me-write-tests"&gt;Lesson 2 - Trust me, write tests&lt;/h1&gt;
&lt;p&gt;I’m not a very strict TDD (Test Driven Development) person, but I enjoy writing tests. Trust me, writing tests is very beneficial if you are making a lot of changes in the code base. I had written code that was worse than spaghetti or lasagna. It’d be almost impossible to safely untangled my spaghetti code without tests.&lt;/p&gt;
&lt;p&gt;Writing tests also takes experience. It’s fine to write lots of ad-hoc tests and remove them later on when broken. The point is to make a conscious choice when the test breaks. Also, the more bad tests you wrote, the more experienced you are to write good ones.&lt;/p&gt;
&lt;p&gt;One benefit about TDD-ing your REST APIs is that it forces you to think through the API design before you started. Or, at least, forces you to design an early version of the API to start with.&lt;/p&gt;
&lt;h1 id="lesson-3---dont-be-afraid-to-go-internal"&gt;Lesson 3 - Don’t be afraid to go internal&lt;/h1&gt;
&lt;p&gt;This is one very valuable skill I learned. As I wrote lots of codes, I constantly saw errors. Seeing errors are horrible, but whenever I saw an error, I stopped the urge to google the error message immediately. Instead, I looked at the stack trace (not just the stack trace from your code,) and try to reason the error from the trace only. If needed, go into the library/framework code and set a breakpoint there to see the error in action.&lt;/p&gt;
&lt;p&gt;Libraries are great resources of learning. Not only are they readable, but also they are written by many smart people. In my opinion, this is the best resource to push yourself to the next level when there are no senior developers around.&lt;/p&gt;
&lt;h1 id="lesson-4-watch-out-for-the-perfectionist"&gt;Lesson 4— Watch out for the perfectionist&lt;/h1&gt;
&lt;p&gt;Sometimes I found myself struggle because I didn’t like the solution at hand. Somehow I knew there must be a better way… This was when I caught myself being the perfectionist, again. And my solution was pretty much always — practicality wins.&lt;/p&gt;
&lt;p&gt;I would write down the practical but ugly solution first, and told myself: “I would come back for you when I knew the answer.” Sometimes I did come up with a better solution and spent extra efforts refactoring the code; sometime I didn’t and the code stuck. If the former happened, I learned to accomplish the task in two different way; if the latter happened, I still have some code that worked. There wasn’t anything to lose to write down the ugly but practical code first, except for your programmer ego.&lt;/p&gt;
&lt;h1 id="bonus-lesson-contribute-back"&gt;Bonus Lesson — Contribute back&lt;/h1&gt;
&lt;p&gt;I wouldn’t have accomplished my task without the help of the open source community. Luckily, contributing back to the community not only satisfied my needs of giving back, but also helped me to gain experiences.&lt;/p&gt;
&lt;p&gt;For less experienced developers, there are several ways to contribute back to the community, from the least amount of efforts to the most in my opinion:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;. Star the Github repo &lt;/em&gt;. Answer questions on Stackoverflow or Github issues &lt;em&gt;. Post Github issues (To me, it’s not easy to post a well-defined problem.) &lt;/em&gt;. Improve documentations&lt;/p&gt;
&lt;p&gt;Improving documentations takes the most efforts because it really stretches my understanding of a library. For example, while working on the PyTest documentation, I learned a cool pattern with the &lt;span class="citation" data-cites="pytest.mark"&gt;@pytest.mark&lt;/span&gt; decorator to make any mark such as &lt;span class="citation" data-cites="pytest.mark.hello"&gt;@pytest.mark.hello&lt;/span&gt; or &lt;span class="citation" data-cites="pytest.mark.obsolete"&gt;@pytest.mark.obsolete&lt;/span&gt;.&lt;/p&gt;
&lt;h1 id="conclusion"&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Talk is cheap, so does thinking. Until I wrote down the code and ran it did I know if it worked. So stop thinking and just write the code! My conclusion really is just one point — write more code! This was crucial for me when I had very little experience. I don’t think there was a better way to gain experience other than writing more code.&lt;/p&gt;
&lt;p&gt;If you like this post, please help me to share it. I also maintain a personal blog at https://dawranliou.com/ . Cheers!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/Re-frame-effects-vs-coeffects</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Re-frame Effects VS Coeffects</title>
    <updated>2019-08-13T00:00:00Z</updated>
    <published>2019-08-13T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/Re-frame-effects-vs-coeffects" type="text/html"/>
    <content type="html">&lt;p&gt;When I first started using &lt;code&gt;re-frame&lt;/code&gt;, I was a bit confused about what effects and coeffects are, or, what &lt;code&gt;fx&lt;/code&gt;s and &lt;code&gt;cofx&lt;/code&gt;s are. They both seemed to relate to the “Side Effects” (or “Effects”) functional programmers dislike. It was hard for me to distinguish them.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;Before you read on, if you’ve never came across re-frame’s &lt;a href="https://github.com/Day8/re-frame/blob/master/docs/README.md"&gt;official documentation&lt;/a&gt; or the &lt;a href="https://cljdoc.org/d/re-frame/re-frame/0.10.8/doc/introduction"&gt;cljdoc page&lt;/a&gt;, please start there. They are fantastic resources. However, if you find yourself need some more examples or direct comparisons to help you understand them, please read on.&lt;/p&gt;
&lt;h2 id="two-types-of-side-effects"&gt;Two types of side effects&lt;/h2&gt;
&lt;figure&gt;
&lt;img src="side-effects-everywhere.jpg" alt="side effects everywhere meme" /&gt;&lt;figcaption aria-hidden="true"&gt;side effects everywhere meme&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Out of the box, &lt;code&gt;re-frame&lt;/code&gt; comes with the mechanisms to update the application state. When your application needs to cause a side effect on the application state, you only need to write &lt;code&gt;reg-event-db&lt;/code&gt;, to register your event handlers. The side effects that operate on the application state is well-managed. There’s very little confusion about them, so this article will not focus on those side effects.&lt;/p&gt;
&lt;p&gt;The two types of side effects we are focusing on are the &lt;code&gt;effects&lt;/code&gt; and the &lt;code&gt;coeffects&lt;/code&gt;, or &lt;code&gt;fx&lt;/code&gt;s and the &lt;code&gt;cofx&lt;/code&gt;s. These two types represent things that are not a part of the application state, such as:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Database&lt;/li&gt;
&lt;li&gt;LocalStore&lt;/li&gt;
&lt;li&gt;Third-Party APIs&lt;/li&gt;
&lt;li&gt;(Other external resources that are not deterministic)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The differences are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;fx&lt;/code&gt;s are &lt;strong&gt;&lt;em&gt;pushed&lt;/em&gt;&lt;/strong&gt; by an event, whereas,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;cofx&lt;/code&gt;s are &lt;strong&gt;&lt;em&gt;pulled&lt;/em&gt;&lt;/strong&gt; by an event.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="examples-of-fx"&gt;Examples of &lt;code&gt;fx&lt;/code&gt;&lt;/h2&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Push data to a database&lt;/li&gt;
&lt;li&gt;Push data to localStore/cookie&lt;/li&gt;
&lt;li&gt;Push data to a third party service&lt;/li&gt;
&lt;li&gt;Push message to &lt;code&gt;js/alert&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Push a function to JavaScript event queue, e.g. &lt;code&gt;js/setInterval&lt;/code&gt;, &lt;code&gt;js/setTimeout&lt;/code&gt;, &lt;code&gt;js/Promise&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="example-of-cofx"&gt;Example of &lt;code&gt;cofx&lt;/code&gt;&lt;/h2&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Pull data from a database&lt;/li&gt;
&lt;li&gt;Pull data from localStore/cookie&lt;/li&gt;
&lt;li&gt;Pull data from a third party service&lt;/li&gt;
&lt;li&gt;Pull current datetime from browser&lt;/li&gt;
&lt;li&gt;Pull a random number&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="what-about-jspromises-that-fetch-data"&gt;What about &lt;code&gt;js/Promise&lt;/code&gt;s that fetch data?&lt;/h2&gt;
&lt;p&gt;This situation is a bit mind-boggling at first. A more concrete example is when doing interop with a JavaScript library in an event handler to fetch data, and it returns a promise immediately. Thinking sequentially, what I wanted is to wait until the data fetched, then run the event handler. However, promises don’t work that way.&lt;/p&gt;
&lt;p&gt;The solution is to think of this as a push side effect, or &lt;code&gt;fx&lt;/code&gt;. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dispatch [:fetch-data] -&amp;gt; do-fx [:promise-fetch-data] -&amp;gt; dispatch [:data-fetched %]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This ends up with two event handlers, one effect handler, and no coeffect handler. I doubt this is the best way because I wish I can just have one &lt;code&gt;:fetch-data&lt;/code&gt; coeffect handler.&lt;/p&gt;
&lt;h2 id="summary"&gt;Summary&lt;/h2&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Effects push,&lt;/li&gt;
&lt;li&gt;Coeffects pull,&lt;/li&gt;
&lt;li&gt;(Please let me know if you have a better way to handle javascript promises.)&lt;/li&gt;
&lt;/ol&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/clojure-nil-busting</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Clojure nil busting one-liners</title>
    <updated>2021-03-10T00:00:00Z</updated>
    <published>2021-03-10T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/clojure-nil-busting" type="text/html"/>
    <content type="html">&lt;h2 id="tldr"&gt;TL;DR&lt;/h2&gt;
&lt;p&gt;To remove all &lt;code&gt;nil&lt;/code&gt;s from a seq:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(remove nil? xs)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To transform a seq and remove &lt;code&gt;nil&lt;/code&gt;s from its result:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(keep a-transform xs)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To replace all &lt;code&gt;nil&lt;/code&gt;s with a fallback value from a seq:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(map (fnil identity a-fallback) xs)&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="preface"&gt;Preface&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;nil&lt;/code&gt; is a value in Clojure that represents “the absence of a value”. Working with &lt;code&gt;nil&lt;/code&gt;s is quite common in Clojure. Most of the core library functions deal with &lt;code&gt;nil&lt;/code&gt;s elegantly, and very consistent. Overtime, it’s quite easy to develop the intuitions that tell you how &lt;code&gt;nil&lt;/code&gt;s will flow through the functions. However, in some cases, which I’ll explain in the later sections below, I do need to take some actions to deal with &lt;code&gt;nil&lt;/code&gt;s. Fortunately, we are in a great position with all the tools in the &lt;code&gt;clojure.core&lt;/code&gt; library.&lt;/p&gt;
&lt;h2 id="most-of-the-time-just-do-nothing"&gt;Most of the time, just do nothing&lt;/h2&gt;
&lt;p&gt;In most cases, we simply don’t need to do anything since so many core functions work with &lt;code&gt;nil&lt;/code&gt;s already:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(:k nil) ;; =&amp;gt; nil
(:k {}) ;; =&amp;gt; nil
({:k :v} nil) ;; =&amp;gt; nil
(#{:a :b} nil) ;; =&amp;gt; nil
(&amp;#39;symbol nil) ;; =&amp;gt; nil
(conj nil :a) ;; =&amp;gt; (:a)
(assoc nil :k :v) ;; =&amp;gt; {:k :v}
(str nil) ;; =&amp;gt; &amp;quot;&amp;quot;
(-&amp;gt; nil :k1 :k2 :k3) ;; =&amp;gt; nil
(map :k nil) ;; =&amp;gt; ()
(filter pos? nil) ;; =&amp;gt; ()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because of this behavior, functions using the seq abstraction (&lt;code&gt;map&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt;, &lt;code&gt;reduce&lt;/code&gt;, etc.) works out of the box even when the seq contains &lt;code&gt;nil&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(map #{:a :b} [:a nil :b nil :c])
;; =&amp;gt; (:a nil :b nil nil)

(filter keyword? [:a nil :b nil :c])
;; =&amp;gt; (:a :b :c)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, when functions do give up on &lt;code&gt;nil&lt;/code&gt;s, we need other strategies.&lt;/p&gt;
&lt;h2 id="early-termination"&gt;Early termination&lt;/h2&gt;
&lt;p&gt;When piping a value through a series of transformations, if one transformation turns the value into &lt;code&gt;nil&lt;/code&gt;, the rest of the transformations might fail. For example:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(-&amp;gt; x
    transform-1  ; yields nil
    transform-2) ; throws NPE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case we can simply swap the threading macros &lt;code&gt;-&amp;gt;&lt;/code&gt; and &lt;code&gt;-&amp;gt;&amp;gt;&lt;/code&gt; with their early-termination variants: &lt;code&gt;some-&amp;gt;&lt;/code&gt; and &lt;code&gt;some-&amp;gt;&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(some-&amp;gt; x
        transform-1  ; return nil
        transform-2) ; execution never reach this step&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, this only works if the step yields &lt;code&gt;nil&lt;/code&gt;. What if we get something like this:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(-&amp;gt;&amp;gt; xs
     (map transform-1)  ; yield a list containing some nils
     (map transform-2)) ; throws NPE on (transform-2 nil)

(some-&amp;gt;&amp;gt; xs
         (map transform-1)  ; yield a list containing some nils
         (map transform-2)) ; throws NPE on (transform-2 nil)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case, we’ll need to bust those &lt;code&gt;nil&lt;/code&gt;s from the seq.&lt;/p&gt;
&lt;h2 id="remove-nils"&gt;Remove &lt;code&gt;nil&lt;/code&gt;s&lt;/h2&gt;
&lt;p&gt;When there’s no need to preserve those &lt;code&gt;nil&lt;/code&gt;s, simply &lt;code&gt;remove&lt;/code&gt; them from the seq.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(remove nil? [:a nil :b nil :c])
;; =&amp;gt; (:a :b :c)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Furthermore, &lt;code&gt;map&lt;/code&gt; + &lt;code&gt;remove&lt;/code&gt; is equivalent to &lt;code&gt;keep&lt;/code&gt; when we want to remove the &lt;code&gt;nil&lt;/code&gt;s from a series of transformations:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(-&amp;gt;&amp;gt; xs
     (map transform-1)
     (remove nil?)
     (map transform-2)
     (remove nil?))

(-&amp;gt;&amp;gt; xs
     (keep transform-1)
     (keep transform-2))&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="replace-nils"&gt;Replace &lt;code&gt;nil&lt;/code&gt;s&lt;/h2&gt;
&lt;p&gt;In some case, we do want to preserve the &lt;code&gt;nil&lt;/code&gt;s (perhaps because we need the correct count of the seq, or the &lt;code&gt;nil&lt;/code&gt;s are something meaningful later down the pipe.)&lt;/p&gt;
&lt;p&gt;My first thought was using the &lt;code&gt;or&lt;/code&gt; form to replace each &lt;code&gt;nil&lt;/code&gt; with a fallback value. However, creating a partial function doesn’t work because:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;code&gt;partial&lt;/code&gt; cannot take macros like &lt;code&gt;or&lt;/code&gt; as arguments, and&lt;/li&gt;
&lt;li&gt;the order of the arguments doesn’t work out for us, i.e. &lt;code&gt;(partial or    a-fallback)&lt;/code&gt; is not what we want.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To make &lt;code&gt;or&lt;/code&gt; work, we need to create a function: &lt;code&gt;#(or % a-fallback)&lt;/code&gt;. However, creating an anonymous function seems an overkill to me. I prefer function compositions whenever possible, especially for a conceptually simple functions like this. Here’s solution I came up with using &lt;code&gt;fnil&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(-&amp;gt;&amp;gt; xs
     (map transform-1)
     ;; replaces nils with a-fallback
     (map (fnil identity a-fallback))
     (map transform-2))


;; This might help the readability

(defn self-or [other]
  (fnil identity other))

(-&amp;gt;&amp;gt; xs
     (map transform-1)
     (map (self-or a-fallback))
     (map transform-2))&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="epilogue"&gt;Epilogue&lt;/h2&gt;
&lt;p&gt;I never did find any real use case for &lt;code&gt;fnil&lt;/code&gt; until this &lt;a href="https://twitter.com/dawranliou/status/1369266420572319744"&gt;tweet&lt;/a&gt;. This whole article is actually just an excuse for sharing the usage of &lt;code&gt;fnil&lt;/code&gt; shown in the last code snippet, which I’m pretty excited about! I did find &lt;a href="https://twitter.com/dawranliou/status/1369273509768097794"&gt;another cool usage&lt;/a&gt; of &lt;code&gt;fnil&lt;/code&gt; soon after. I’ll write more about &lt;code&gt;fnil&lt;/code&gt; and other cool thing you can do with higher-order function in the future. Thanks for reading!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/composing-namedtuple</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Composing namedtuple from namedtuples</title>
    <updated>2017-11-02T00:00:00Z</updated>
    <published>2017-11-02T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/composing-namedtuple" type="text/html"/>
    <content type="html">&lt;p&gt;The problem:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;One namedtuples is great, two better. But how do I combine the two namedtuples to get the best nametuple of all?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;For example, how to combine the Square class with Color class?&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;Square = namedtuple(&amp;#39;Square&amp;#39;, &amp;#39;x0 y0 x1 y1&amp;#39;)
Color = namedtuple(&amp;#39;Color&amp;#39;, &amp;#39;r g b&amp;#39;)
# The opposite of DRY principle - WET (we enjoy typing) principle
ColoredSquare = namedtupe(&amp;#39;ColoredSquare&amp;#39;, &amp;#39;x0 y0 x1 y1 r g b&amp;#39;)&lt;/code&gt;&lt;/pre&gt;
&lt;!-- more --&gt;
&lt;p&gt;I don’t like this solution, because there are clearly something to reuse in Square and Color , and also, it isn’t fun to call ColoredSquare ‘s &lt;strong&gt;init&lt;/strong&gt; function that has 7 arguments. The alternative might be writing a custom class that takes Square and Color as arguments of the &lt;strong&gt;init&lt;/strong&gt; function, but then we lost all the benefits from using namedtuples. (TODO add a link of something to support this statement.)&lt;/p&gt;
&lt;p&gt;So, here’s the recipe:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;class ColoredSquare(namedtuple(&amp;#39;ColoredSquare&amp;#39;,
                               Square._fields + Color._fields)):
    @classmethod
    def from_(cls, square: Square, color: Color):
        return cls(*square, *color)

my_square = ColoredSquare.from_(
        square=Square(0, 0, 1, 1), 
        color=Color(100, 100, 100))

&amp;gt;&amp;gt;&amp;gt; my_square
ColoredSquare(x0=0, y0=0, x1=1, y1=1, r=100, g=100, b=100)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let me know what you think! Please share or like this post if you think it’s helpful!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/learning-clojure-and-emacs</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>My personal experience to learn Clojure and Emacs together</title>
    <updated>2021-07-19T00:00:00Z</updated>
    <published>2021-07-19T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/learning-clojure-and-emacs" type="text/html"/>
    <content type="html">&lt;p&gt;I recently made a bit lengthy response in the Clojureverse discussion on the topic &lt;a href="https://clojureverse.org/t/gnu-emacs-cider-vs-vs-code-calva/7829"&gt;“GNU Emacs + Cider vs VS Code + Calva”&lt;/a&gt;. To summarize:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I recommend learning Emacs.&lt;/li&gt;
&lt;li&gt;I recommend learning Emacs and Clojure at the same time. It’s going to be very challenging and fun and rewarding.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Quote:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Hi, I just want to provide another data point here. I started learning Clojure using my own free time back in 2018Q3 while having a full-time software engineering job in Java + Python. I picked up Emacs (Spacemacs at the time) around 2018Q4 for no particular reason other than I always gravitate toward ancient technologies. There’s just something about the aesthetics that I love about old technologies. I watched a few Clojure talks using Emacs on YouTube at the time and thought Emacs was pretty cool, and thought I wanted to be like those Clojure Emacs people. I was fairly fluent in Vim keybindings before that, so Spacemacs made the transition a bit easier.&lt;/p&gt;
&lt;p&gt;There were lots of challenges to overcome to learn Clojure and Emacs at the same time. And oh boy, that was a lot of fun! I think both learning Clojure and learning Emacs are very rewarding experiences to me. The more time I spent on it, the more knowledge I gained, the more powerful I felt. I really think Clojure and Emacs are the two best things ever happen to my developer career so far.&lt;/p&gt;
&lt;p&gt;I’d say that I got pretty fluent in Clojure by 2019Q4 when I got my first and current Clojure full-time position but was still a beginner Emacs. Today, I feel pretty comfortable rocking my own Emacs configuration without using any off-the-shelve Emacs distribution. I can read and write ELisp code (but not so fluently) and know a couple of tricks to debug/troubleshoot issues with 3rd party packages.&lt;/p&gt;
&lt;p&gt;One benefit I found from learning Clojure and Emacs(Lisp) at the same time is that many of the concepts are transferable to one another. For example, the REPL driven development I love doing in Clojure is right there for you in Emacs, a highly moldable and inspectable Lisp machine like your Clojure REPL. Also, I couldn’t grasp the idea of dynamic vars in Clojure until I learned it from Emacs Lisp.&lt;/p&gt;
&lt;p&gt;I know that the general sentiment towards Emacs is that it is too hard, and I get that. But I mean, what’s fun in learning it if it’s just easy? After using Emacs as my daily driver for almost 3 years, I am still having fun learning bits and bits about Emacs.&lt;/p&gt;
&lt;/blockquote&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/my-core-values</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>My Core Values</title>
    <updated>2019-10-24T00:00:00Z</updated>
    <published>2019-10-24T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/my-core-values" type="text/html"/>
    <content type="html">&lt;p&gt;I’ve never tried to verbalize my core values before, though it feels right to do so for the first time in 30 years of my life. I hope this post serves the right place for the future me to reflect on. This post is an open letter to my future self.&lt;/p&gt;
&lt;p&gt;You might find many ancient Chinese wisdom influences below, which says a lot about my origin.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h2 id="balance"&gt;Balance&lt;/h2&gt;
&lt;p&gt;The Chinese idiom, “物極必反,” means “Things will develop in the opposite direction when they become extreme.” Also, in classical Chinese philosophy, Confucianism (儒家), the core is about the Golden Mean (中庸之道). This is true for many situations: carbohydrates/sugar gives us energies, but too much of it causes diseases; sunlights are essential to our biology, but too much of it damages our skins.&lt;/p&gt;
&lt;p&gt;This is also my opinion on many subjects, e.g., politics, finance, technologies, social media, etc. Generally, anything that generates too much hypes are dangerous.&lt;/p&gt;
&lt;p&gt;I also believe striving for balance is a key to peace and happiness.&lt;/p&gt;
&lt;h2 id="compassion"&gt;Compassion&lt;/h2&gt;
&lt;p&gt;“己所不欲，勿施於人,” translated to “Do not impose on others what you do not desire,” is undoubtedly the words I live by. This means to put others’ desires before yourself. Understand bad days could happen to anyone just like ourselves. And always give back to the communities because you owe them.&lt;/p&gt;
&lt;p&gt;Self-compassion is equally crucial as the compassion to others. Don’t beat yourself up every time you make a mistake.&lt;/p&gt;
&lt;h2 id="autonomy"&gt;Autonomy&lt;/h2&gt;
&lt;p&gt;Autonomy is not about being independent. Instead, it’s about being dependable and become interdependent as a community. Autonomy is to taking initiatives, taking responsibilities, and willing to adapt. For example, don’t start eating out everyday because your employer pays you a lot. Don’t invest in those highest grossing stocks or whatever coin people are hyping about. Don’t let everyone’s opinion become your opinion by default.&lt;/p&gt;
&lt;p&gt;Autonomy is the key to freedom - freedom of finance, freedom of mind.&lt;/p&gt;
&lt;h2 id="curiosity"&gt;Curiosity&lt;/h2&gt;
&lt;p&gt;Curiosity is a primal human drive to survive and grow. However, it’s easy to forget about it once we feel comfortable.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“Only the paranoid survives.” - Andrew Grove&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Always challenge yourself to do difficult things. Do not be satisfied with your current status quo. Always take the road not taken.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“The limits of my language mean the limits of my world.” - Ludwig Wittgenstein&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id="simplicity"&gt;Simplicity&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“Simplicity is the ultimate sophistication.” - Leonardo Da Vinci&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Simplicity keeps our lives focused, and fulfilled. Yet, simplicity is hard work, value to strive for. Especially in the era of information explosion, social media constantly fighting for your attention, new gadgets showing up every other day, it’s easy to lost simplicity.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Balance&lt;/li&gt;
&lt;li&gt;Compassion&lt;/li&gt;
&lt;li&gt;Autonomy&lt;/li&gt;
&lt;li&gt;Curiosity&lt;/li&gt;
&lt;li&gt;Simplicity&lt;/li&gt;
&lt;/ol&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/pyglet-game-under-30-mins</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>First Game Programming Experience with Python and Pyglet under 30 Minutes</title>
    <updated>2016-01-27T00:00:00Z</updated>
    <published>2016-01-27T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/pyglet-game-under-30-mins" type="text/html"/>
    <content type="html">&lt;p&gt;This is my first experience with game programming, and also my first time working with the Python &lt;a href="https://bitbucket.org/pyglet/pyglet/wiki/Home"&gt;Pyglet&lt;/a&gt; package. I got to say I feel so much accomplishment even though it’s just a dumb, simple, ghetto game that could be done within 100 lines of codes. It really amazes me how things could get done so easily these days.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;I was in the &lt;a href="http://www.meetup.com/sfpython/"&gt;San Francisco Python Meetup Group&lt;/a&gt; and joined &lt;a href="http://simeonfranklin.com/talk/pyglet/slides.html"&gt;Simeon’s Pyglet tutorial session&lt;/a&gt;, which really gave me a blast. In his tutorial, he showed some fundamental building blocks for Pyglet game programming like showing images on window, how to do animation, listening to keyboard or mouse event, and so on. After half an hour diving into the tutorial, suddenly he said, “&lt;em&gt;are you ready to make a game now?&lt;/em&gt;”&lt;/p&gt;
&lt;p&gt;That was a shock. I don’t even know where to start! However, the goal was simple, to create a simple game with 50 to 100 lines of code within the next hour. So I start with the simplest game idea that I could think of — to dodge whatever falls from the sky. The more you dodge, the more score you have, till you got hit and the game’s over. Simple enough, eh? Now I’m going to find a nice 8-bit character for my game. Guess what I found? Mega Man!&lt;/p&gt;
&lt;p&gt;&lt;em&gt;It’s time to get hands dirty!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Surprisingly, the coding process wasn’t as hard as expected. I don’t have a really good code design for my game so I simply make incremental progress along the way. The result might have been chaotic but it turned out good enough for my little game. This is what I did in order:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Make a window&lt;/li&gt;
&lt;li&gt;Show a still picture of Mega Man at the bottom of the window&lt;/li&gt;
&lt;li&gt;Show a still picture of the ball at the top of the window&lt;/li&gt;
&lt;li&gt;Make Pyglet listen to the left and right arrow keys and shifts the Mega Man accordingly&lt;/li&gt;
&lt;li&gt;Let Pyglet update the ball position every time the clock ticks&lt;/li&gt;
&lt;li&gt;Add a Game class that saves the “state of the game”. I’ll explain this later. OOP rocks!&lt;/li&gt;
&lt;li&gt;Refactor the code to use a Game object for updating the Mega Man position and the ball position&lt;/li&gt;
&lt;li&gt;Add the logic to detect and handle collision between Mega Man and the ball&lt;/li&gt;
&lt;li&gt;Add the score label and the score logic&lt;/li&gt;
&lt;li&gt;Done!&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;My git repo is here: https://github.com/dawranliou/pyglet-tutorial/blob/master/megaman.py. The code is less than 100 lines so it shouldn’t be hard to follow even though I didn’t put too much thought on the structure. Like the famous quote says: “&lt;strong&gt;&lt;em&gt;if your first product does not embarrass you, you are shipping it too late.&lt;/em&gt;&lt;/strong&gt;” Leave me comments or tweet me &lt;span class="citation" data-cites="randydliou"&gt;@randydliou&lt;/span&gt; if you have any thought want to share.&lt;/p&gt;
&lt;p&gt;Come back to the step number 6 above. There’re some good reasons to have a game state class defined in the code:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;You don’t need to declare global variable everywhere.&lt;/strong&gt; I don’t like global variables. They make my code harder to maintain.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Games are full of states that need to be tracked and it’s a good idea to wrap those together for clarity.&lt;/strong&gt; In my case, the states I am tracking is the position of Mega Man, the position of the ball, the score, and if the game is terminated. If the game gets bigger with more objects on the window, this list could increase a lot.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That’s it! It was a very entertaining and accomplishing experience. I had a lot of fun trying out something new. I think Pyglet did a pretty decent job maintain their documentation. It wasn’t hard for me to find the information that I needed. Highly recommend to give it a try if you’ve never done game programming before!&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/domain-exploring-with-spec</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Domain Exploring with Clojure Spec</title>
    <updated>2019-10-17T00:00:00Z</updated>
    <published>2019-10-17T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/domain-exploring-with-spec" type="text/html"/>
    <content type="html">&lt;p&gt;I read a great article “&lt;a href="https://adambard.com/blog/domain-modeling-with-clojure-spec/"&gt;Domain modelling with clojure.spec&lt;/a&gt;” by &lt;a href="https://twitter.com/adambard"&gt;Adam Bard&lt;/a&gt; and started to use more &lt;code&gt;clojure.spec&lt;/code&gt; for domain modeling. Here I want to share my process, which I called “Domain Exploring.” It really is just a combination of REPL-driven development with domain modeling in it’s essence.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h2 id="domain-modeling-vs-exploring"&gt;Domain Modeling vs Exploring&lt;/h2&gt;
&lt;p&gt;From &lt;a href="https://en.wikipedia.org/wiki/Domain_model"&gt;Wikipedia - Domain Model&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;In software engineering, a domain model is a conceptual model of the domain that incorporates both behaviour and data.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Before we reach the complete domain model, it’s typical to start by drawing some borders of our domain. Note those borders are not just typical database constraints like &lt;code&gt;NOT NULL&lt;/code&gt; or types like &lt;code&gt;INTEGER&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="example-blog-domain"&gt;Example: Blog Domain&lt;/h2&gt;
&lt;p&gt;In this example, I’ll describe my exploration process to build the domain model for blog.&lt;/p&gt;
&lt;p&gt;First, create a ns:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(ns dawranliou.blog
  (:require [clojure.spec.alpha :as s]))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The blog domain model start with just a map:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(s/def ::blog map?)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And in the comment, try to generate a few samples of the &lt;code&gt;::blog&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(require &amp;#39;[clojure.spec.gen.alpha :as gen])
(gen/sample (s/gen ::blog))

;; =&amp;gt;
({}
 {}
 {}
 {\3 29N, 0 :-}
 #:M*6{:c+ true}
 {}
 {J 1/3,
  2 -41204876568N,
  f -1.0,
  &amp;quot;&amp;#39;&amp;quot; #uuid &amp;quot;0c7e7887-627f-4f6f-b6d3-05a8197c4d5a&amp;quot;,
  2.5 -1.296875,
  &amp;quot;j&amp;amp;3?M&amp;quot; Ez}
  ;; ...
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It’s obvious that this isn’t the data we’re expecting. What we need is called an &lt;a href="https://clojure.org/guides/spec#_entity_maps"&gt;Entity Map&lt;/a&gt;. Update the &lt;code&gt;::blog&lt;/code&gt; spec to:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(s/def ::blog (s/keys))
(gen/sample (s/gen ::blog))
;; =&amp;gt; ({} {} {} {} {} {} {} {} {} {})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We got empty map because we didn’t define the entities in the map. Let’s start by adding the &lt;code&gt;title&lt;/code&gt; string:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(s/def ::title string?)
(s/def ::blog (s/keys :req [::title]))

;; =&amp;gt;
(#:dawranliou.blog{:title &amp;quot;&amp;quot;}
 #:dawranliou.blog{:title &amp;quot;&amp;quot;}
 #:dawranliou.blog{:title &amp;quot;E5&amp;quot;}
 ;; ...
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A good thing is that the keywords in the maps are namespace qualified. When this blog map is merged with another map, we can be pretty confident that the data won’t be overwritten.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(s/def ::body string?)
(s/def ::author string?)
(s/def ::date-publish int?)
(s/def ::blog (s/keys :req [::title ::body ::author ::date-published]))

(gen/sample (s/gen ::blog))
;; =&amp;gt;
(#:dawranliou.blog{:title &amp;quot;&amp;quot;, :body &amp;quot;&amp;quot;, :author &amp;quot;&amp;quot;, :date-publish -1}
 #:dawranliou.blog{:title &amp;quot;&amp;quot;, :body &amp;quot;O&amp;quot;, :author &amp;quot;&amp;quot;, :date-publish -1}
 #:dawranliou.blog{:title &amp;quot;6&amp;quot;, :body &amp;quot;&amp;quot;, :author &amp;quot;2g&amp;quot;, :date-publish 1}
 ;; ...
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One thing to notice is that the timestamps are sometimes negative. We can use &lt;code&gt;pos-int?&lt;/code&gt; here instead of &lt;code&gt;int?&lt;/code&gt;.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(s/def ::date-publish pos-int?)

(gen/sample (s/gen ::blog))
;; =&amp;gt;
(#:dawranliou.blog{:title &amp;quot;&amp;quot;, :body &amp;quot;&amp;quot;, :author &amp;quot;&amp;quot;, :date-publish 1}
 #:dawranliou.blog{:title &amp;quot;Q&amp;quot;, :body &amp;quot;&amp;quot;, :author &amp;quot;&amp;quot;, :date-publish 1}
 #:dawranliou.blog{:title &amp;quot;S&amp;quot;, :body &amp;quot;&amp;quot;, :author &amp;quot;f4&amp;quot;, :date-publish 1}
 ;; ...
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To define a behavior under the blog domain, simply write a function under the same namespace:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defn blog [title body author]
  {::title title ::body body ::author author ::date-publish nil})

(s/fdef blog
  :args (s/cat :title string? :body string? :author string?)
  :ret ::blog)

(blog &amp;quot;title&amp;quot; &amp;quot;body&amp;quot; &amp;quot;author&amp;quot;)
;; =&amp;gt;
#:dawranliou.blog{:title &amp;quot;title&amp;quot;,
                  :body &amp;quot;body&amp;quot;,
                  :author &amp;quot;author&amp;quot;,
                  :date-publish nil}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;s/fdef&lt;/code&gt; does not automatically check the function arguments. To do it, we need to instrument the test to do so. However, instrumentation isn’t suitable for production due to performance. It should only be used in development and testing.&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(require &amp;#39;[clojure.spec.test.alpha :as stest])
(stest/instrument)

(blog &amp;quot;title&amp;quot; &amp;quot;body&amp;quot; 123)
;; Execution error - invalid arguments to dawranliou.blog/blog at (REPL:24).
;; 123 - failed: string? at: [:author]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At last, we can exercise the function to check if there are any mistake:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(s/exercise-fn `blog)
;; =&amp;gt;
([(&amp;quot;&amp;quot; &amp;quot;&amp;quot; &amp;quot;&amp;quot;)
  #:dawranliou.blog{:title &amp;quot;&amp;quot;, :body &amp;quot;&amp;quot;, :author &amp;quot;&amp;quot;, :date-publish nil}]
 [(&amp;quot;&amp;quot; &amp;quot;0&amp;quot; &amp;quot;&amp;quot;)
  #:dawranliou.blog{:title &amp;quot;&amp;quot;, :body &amp;quot;0&amp;quot;, :author &amp;quot;&amp;quot;, :date-publish nil}]
 [(&amp;quot;M&amp;quot; &amp;quot;TO&amp;quot; &amp;quot;f8&amp;quot;)
  #:dawranliou.blog{:title &amp;quot;M&amp;quot;, :body &amp;quot;TO&amp;quot;, :author &amp;quot;f8&amp;quot;, :date-publish nil}]
 ;; ...
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The return value isn’t validated so we need to do it ourselves:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(for [[args ret] (s/exercise-fn `blog)]
  (s/valid? ::blog ret))
;; =&amp;gt; (false false ...)

;; Check the console for what&amp;#39;s wrong
(for [[args ret] (s/exercise-fn `blog)]
  (s/explain ::blog ret))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Turned out the &lt;code&gt;::date-publish&lt;/code&gt; key cannot be &lt;code&gt;nil&lt;/code&gt;. Thus,&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(s/def ::date-publish (s/or :published pos-int?
                            :not-published nil?))

(for [[args ret] (s/exercise-fn `blog)]
  (s/valid? ::blog ret))
;; =&amp;gt; (true true ...)&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="summary"&gt;Summary&lt;/h2&gt;
&lt;p&gt;The Domain Exploring process is:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Define/refine a spec&lt;/li&gt;
&lt;li&gt;Generate some data&lt;/li&gt;
&lt;li&gt;Test data against the spec&lt;/li&gt;
&lt;li&gt;Repeat&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="appendix"&gt;Appendix&lt;/h2&gt;
&lt;p&gt;Complete example&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(ns dawranliou.blog
  (:require [clojure.spec.alpha :as s]))

(s/def ::title string?)
(s/def ::body string?)
(s/def ::author string?)
(s/def ::date-publish (s/or :published pos-int?
                            :not-published nil?))
(s/def ::blog (s/keys :req [::title ::body ::author ::date-publish]))

(s/fdef blog
  :args (s/cat :title string? :body string? :author string?)
  :ret ::blog)

(defn blog [title body author]
  {::title title ::body body ::author author ::date-publish nil})

(comment
  (require &amp;#39;[clojure.spec.gen.alpha :as gen])

  (gen/sample (s/gen ::blog))

  (require &amp;#39;[clojure.spec.test.alpha :as stest])
  (stest/instrument)

  (for [[args ret] (s/exercise-fn `blog)]
    (s/valid? ::blog ret)))&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/xref-with-eglot-and-project</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Don't kill my xref buffers</title>
    <updated>2023-02-12T00:00:00Z</updated>
    <published>2023-02-12T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/xref-with-eglot-and-project" type="text/html"/>
    <content type="html">&lt;p&gt;I like buffers.&lt;/p&gt;
&lt;p&gt;When I first started using Emacs, I used to feel paranoid about keeping too many buffers. Nowadays, I don't even notice the hundreds or thousands of buffers buried in Emacs.&lt;/p&gt;
&lt;p&gt;I like &lt;code class="verbatim"&gt;xref&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The built-in package, &lt;code class="verbatim"&gt;xref&lt;/code&gt;, is an essential part of my workflow at Kira Systems (now acquired by Litera). We use a monorepo setup for our flagship Machine Learning contract analysis SaaS product written in Clojure and Go. It's crucial for my day-to-day work to be able to do project-wide searches for references. I use the &lt;code&gt;project-find-regexp&lt;/code&gt; (a command from the built-in package, &lt;code class="verbatim"&gt;project.el&lt;/code&gt;, bound to &lt;code class="verbatim"&gt;C-x p g&lt;/code&gt;) to find matches for references in both Clojure and Go code. If I'm only interested in the Clojure source code, I can use &lt;code&gt;xref-find-references&lt;/code&gt; (bound to &lt;code class="verbatim"&gt;M-?&lt;/code&gt;) to find all references with &lt;code class="verbatim"&gt;eglot&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;There's one problem. &lt;code class="verbatim"&gt;xref&lt;/code&gt; doesn't like buffers.&lt;/p&gt;
&lt;p&gt;Or every time the commands invokes &lt;code class="verbatim"&gt;xref&lt;/code&gt;, they reuse the &lt;code class="verbatim"&gt;*xref*&lt;/code&gt; buffer and effectively destroyed the results of the previous reference search.&lt;/p&gt;
&lt;p&gt;Of course, this is Emacs. We can configure it ourselves. All it requires is a little gentle advice:&lt;/p&gt;
&lt;pre class="commonlisp" data-org-language="emacs-lisp"&gt;&lt;code&gt;(with-eval-after-load &amp;#39;project
  (defun project-find-regexp-with-unique-buffer (orig-fun &amp;amp;rest args)
    &amp;quot;An advice function that gives project-find-regexp a unique buffer name&amp;quot;
    (require &amp;#39;xref)
    (let ((xref-buffer-name (format &amp;quot;%s %s&amp;quot; xref-buffer-name (car args))))
      (apply orig-fun args)))

  (advice-add &amp;#39;project-find-regexp :around
              #&amp;#39;project-find-regexp-with-unique-buffer))
&lt;/code&gt;&lt;/pre&gt;
&lt;pre class="commonlisp" data-org-language="emacs-lisp"&gt;&lt;code&gt;(with-eval-after-load &amp;#39;eglot
  (defun xref-find-references-with-eglot (orig-fun &amp;amp;rest args)
    &amp;quot;An advice function that gives xref-find-definitions a unique
buffer name when eglot is enabled.&amp;quot;
    (if (bound-and-true-p eglot--managed-mode)
        (let ((xref-buffer-name (format &amp;quot;%s %s&amp;quot;
                                        xref-buffer-name
                                        (symbol-at-point))))
          (apply orig-fun args))
      (apply orig-fun args)))

  (advice-add &amp;#39;xref-find-references :around
              #&amp;#39;xref-find-references-with-eglot))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By leveraging Emacs's advice-function facility and dynamic scoping, the Elisp code above customize the existing &lt;code&gt;project-find-regexp&lt;/code&gt; and &lt;code&gt;xref-find-references&lt;/code&gt; to use a more descriptive buffer name for each invocation. The result is that I get to keep multiple &lt;code class="verbatim"&gt;xref&lt;/code&gt; reference buffers till I finish using those.&lt;/p&gt;
&lt;p&gt;The configurability of Emacs is often brought up as the top reason to use Emacs. Yes, it took some time to traverse the source code of &lt;code class="verbatim"&gt;eglot.el&lt;/code&gt;, &lt;code class="verbatim"&gt;package.el&lt;/code&gt;, and &lt;code class="verbatim"&gt;xref.el&lt;/code&gt;. Still, the customization described in this article can be done without a deep knowledge of the Emacs source code or individual packages.&lt;/p&gt;
&lt;p&gt;To me, this article is a perfect example of how Emacs adapts to the user's workflows instead of forcing the user to adapt to the editor's (or package authors') ideology. I hope this short article inspires you to start customizing your Emacs experience. Cheers! :)&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/from-vim-to-emacs</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>From Vim to Emacs</title>
    <updated>2020-04-06T00:00:00Z</updated>
    <published>2020-04-06T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/from-vim-to-emacs" type="text/html"/>
    <content type="html">&lt;p&gt;I was a Vim user a couple years back. I totally loved (and still love) the philosophy of Vim as well as the &lt;code&gt;hjkl&lt;/code&gt; navigation. In contrast, Emacs didn’t make any sense to me. &lt;code&gt;C-v&lt;/code&gt; for page down and &lt;code&gt;M-v&lt;/code&gt; for page up? Does that even make any sense to anyone?&lt;/p&gt;
&lt;p&gt;Yet here I am, after all those years, writing this article on my Emacs with all the keybinding craziness. I must confess, I enjoy Emacs quite a lot. However, the transition wasn’t easy for me. Here’s my journey so far.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;h2 id="the-start-of-the-cycle"&gt;The start of the cycle&lt;/h2&gt;
&lt;p&gt;&lt;img src="//imgs.xkcd.com/comics/lisp_cycles.png" title="I've just received word that the Emperor has dissolved the MIT computer science program permanently." alt="Lisp Cycles"&gt;&lt;/p&gt;
&lt;p&gt;In the mid 2018 I started teaching myself Clojure, a dialect of the Lisp family. I fell in love with the language but the thing that amazed me the most, was how the Clojure community do all the amazing presentations using Emacs. “Well,” I told myself, “maybe it’s time to finally see the other side of the Vim vs Emacs Editor War.”&lt;/p&gt;
&lt;p&gt;I learned the basics from the &lt;a href="https://www.braveclojure.com/basic-emacs/"&gt;Clojure for the Brave and True&lt;/a&gt; website, It turned out that learning Clojure and Emacs at the same time was too audacious for me at the time. Clojure itself alone already has a pretty steep learning curve. And then there was Emacs… I took a more strategic route and focus on Clojure solely for a while (using both VSCode and IntelliJ.) It was fine at the time (because I didn’t know what I was missing.)&lt;/p&gt;
&lt;p&gt;Only knowing the foundamentals of Clojure, I started working on opensource projects to gain more real world experiences. It was then I was introduced to Spacemacs.&lt;/p&gt;
&lt;h2 id="into-the-space"&gt;Into the Space&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://www.spacemacs.org/"&gt;Spacemacs&lt;/a&gt;, on the website:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Spacemacs is a new way to experience Emacs – a sophisticated and polished set-up focused on ergonomics, mnemonics and consistency.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;To me, the main selling point was the exceptional out-of-box configuration. The layer system makes adding packages almost no-brainers. And plus, I didn’t need to give up my Vim keybindings! Spacemacs truely made me start liking Emacs and wanted to explore more aspects of Emacs.&lt;/p&gt;
&lt;p&gt;After learning a few basics, I was able to get pretty productive using Spacemacs and started understanding the superpower of Clojure, the REPL + Editor integration workflow. The “mnemonics” aspect of Spacemacs also made discovering and memorizing the useful functionalities so much easier.&lt;/p&gt;
&lt;p&gt;I also made a switch to the &lt;code&gt;develop&lt;/code&gt; branch of Spacemacs at the time because of a lot of the features and customizations can only be done there. I was learning quite a bit from both the official documentation and from &lt;a href="https://practicalli.github.io/spacemacs/"&gt;Practicalli’s spacemacs tutorial.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Then, it was the late 2019’s that I started my first professional job as a Clojure/Script developer. During the first week at work I saw my collegue’s minimalistic Emacs &lt;code&gt;init.el&lt;/code&gt; file that also uses evil-mode (which is the configuration that gives you the access to all the Vim keybindings.) I was pretty amazed by it.&lt;/p&gt;
&lt;p&gt;Using Clojure and Spacemacs day in and day out, I wasn’t completely satisfied with the fact that I can only understand Emacs through the lense of Spacemacs. And so, just last week, I started diving into Emacs.&lt;/p&gt;
&lt;h2 id="embracing-the-evil"&gt;Embracing the Evil&lt;/h2&gt;
&lt;p&gt;Aaron Bieber has a great talk on &lt;a href="https://youtu.be/JWD1Fpdd4Pc"&gt;“Evil Mode: Or, How I Learned to Stop Worrying and Love Emacs”&lt;/a&gt;. He helped me to set the right mindset from the start. I don’t really want to ditch all the keybindings, just yet. I also watched a lot of &lt;a href="https://cestlaz.github.io/stories/emacs/"&gt;Mike Zamansky’s Emacs tutorials&lt;/a&gt;. It felt like an achievable goal to recreate the Spacemacs experiences myself.&lt;/p&gt;
&lt;p&gt;Actually, someone has already done it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://youtu.be/6INMXmsCCC8"&gt;Suyash Bire talked about Spin Your Own Spacemacs-lite&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://sam217pa.github.io/2016/09/02/how-to-build-your-own-spacemacs"&gt;Bacterial Finches wrote about How to build your own spacemacs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;And here’s a repo for &lt;a href="https://github.com/balaramadurai/.emacs.d"&gt;Spacemacs-Lite&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Those resources are awesome. They gave me so much hope that I knew my goal of making my own mini Spacemacs was an achievable project.&lt;/p&gt;
&lt;p&gt;I really learned a lot in this stage. One of the most important lessons I learned is:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Emacs is a self-documenting editor&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Instead of needing to go to Google to search for answers, Emacs has all those things built-in for you. Just like Clojure, I was given the tool I need to solve my problems. Learning a few commands and I was very well-suited to troubleshoot my editor. This is very powerful.&lt;/p&gt;
&lt;p&gt;So far I’ve got most of the things I want working. You can check out the code &lt;a href="https://github.com/dawranliou/emacs.d/blob/master/init.el"&gt;here&lt;/a&gt;. Currently it’s about 500 LOC and I wrote every line of the code. I feel very good about it. If something isn’t working right, I know where to fix it (most of the time.)&lt;/p&gt;
&lt;h2 id="to-infinity-and-beyond"&gt;To infinity and beyond&lt;/h2&gt;
&lt;p&gt;Emacs is truely an amazing piece of software that I had so much fun with. The reason it pushed me away in the first place was its out-of-box configuration. It required me to have opinions on almost every aspect of the editor on day one, and this intimidated me.&lt;/p&gt;
&lt;p&gt;Spacesmacs was a godsend for me when I needed it the most. Till today, the way of Spacesmacs influences a lot of my opinion toward my Emacs configurations. I’m not giving up the things I like about Spacesmacs.&lt;/p&gt;
&lt;p&gt;However, will I ever ditch Evil mode and embrace the holly form of Emacs? Maybe.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/clojure-higher-order-functions-explained-fnil</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Clojure higher-order functions explained: fnil</title>
    <updated>2021-03-19T00:00:00Z</updated>
    <published>2021-03-19T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/clojure-higher-order-functions-explained-fnil" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;Checkout the &lt;a href="/blog/clojure-higher-order-functions-explained-index"&gt;index&lt;/a&gt; for the full series.&lt;/em&gt;&lt;/p&gt;
&lt;h2 id="source-code"&gt;Source code&lt;/h2&gt;
&lt;p&gt;It’s better to read the source code first because source code don’t lie. Here’s the &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L6556"&gt;source of fnil in clojure 1.10.1&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defn fnil
  &amp;quot;Takes a function f, and returns a function that calls f, replacing
  a nil first argument to f with the supplied value x. Higher arity
  versions can replace arguments in the second and third
  positions (y, z). Note that the function f can take any number of
  arguments, not just the one(s) being nil-patched.&amp;quot;
  {:added &amp;quot;1.2&amp;quot;
   :static true}
  ([f x]
   (fn
     ([a] (f (if (nil? a) x a)))
     ([a b] (f (if (nil? a) x a) b))
     ([a b c] (f (if (nil? a) x a) b c))
     ([a b c &amp;amp; ds] (apply f (if (nil? a) x a) b c ds))))
  ([f x y]
   (fn
     ([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
     ([a b c] (f (if (nil? a) x a) (if (nil? b) y b) c))
     ([a b c &amp;amp; ds] (apply f (if (nil? a) x a) (if (nil? b) y b) c ds))))
  ([f x y z]
   (fn
     ([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
     ([a b c] (f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c)))
     ([a b c &amp;amp; ds] (apply f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c) ds)))))&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="usages"&gt;Usages&lt;/h2&gt;
&lt;p&gt;Simply put, &lt;strong&gt;fnil patches functions to handle nil arguments&lt;/strong&gt;. Usually this is because you are using functions that you do not maintain and want them to handle &lt;code&gt;nil&lt;/code&gt;s in your particular use cases rather than just barfing out NPEs.&lt;/p&gt;
&lt;p&gt;Personally, &lt;code&gt;fnil&lt;/code&gt; has become increasingly handy ever since I come to be more liberal on passing &lt;code&gt;nil&lt;/code&gt;s as real values in the front-end presentation logic. (See my other &lt;a href="2021-03-10-clojure-nil-busting.md"&gt;article about nil busting here&lt;/a&gt;.)&lt;/p&gt;
&lt;h2 id="examples"&gt;Examples&lt;/h2&gt;
&lt;p&gt;There are a couple of great examples by the Clojure community on &lt;a href="https://clojuredocs.org/clojure.core/fnil"&gt;clojuredocs.org’s fnil page&lt;/a&gt;. Please go check it out for the examples!&lt;/p&gt;
&lt;h2 id="my-use-cases"&gt;My use cases&lt;/h2&gt;
&lt;p&gt;This is my growing list of use cases where I stumble upon and found &lt;code&gt;fnil&lt;/code&gt; useful ;)&lt;/p&gt;
&lt;h3 id="python-defaultdict-in-clojure"&gt;Python defaultdict in Clojure&lt;/h3&gt;
&lt;p&gt;Being a more Object-oriented language than functional, the way Python deal with inserting default value in a hash-table (or &lt;code&gt;dict&lt;/code&gt;) through the object, &lt;a href="https://docs.python.org/3/library/collections.html#defaultdict-objects"&gt;defaultdict&lt;/a&gt;. Example:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import collections
&amp;gt;&amp;gt;&amp;gt; d = collections.defaultdict(list)
&amp;gt;&amp;gt;&amp;gt; d[&amp;#39;yellow&amp;#39;].append(1)
&amp;gt;&amp;gt;&amp;gt; d
defaultdict(&amp;lt;class &amp;#39;list&amp;#39;&amp;gt;, {&amp;#39;yellow&amp;#39;: [1]})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The more functional approach to the problem can be done using &lt;code&gt;fnil&lt;/code&gt; in Clojure. Instead of defining the new behavior of an object, just create a function that knows what to do with &lt;code&gt;nil&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(def conj* (fnil conj []))
(update {} :yellow conj* 1)
;; =&amp;gt; {:yellow [1]}

;; Or, inline the function
(update {} :yellow (fnil conj []) 1)
;; =&amp;gt; {:yellow [1]}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Credits to &lt;a href="https://clojuredocs.org/clojure.core/fnil#example-54d0443ee4b0e2ac61831cf7"&gt;clojuredocs’s user Dimagog’s example&lt;/a&gt;. It was my initial inspiration.&lt;/em&gt;&lt;/p&gt;
&lt;h3 id="identity-fallback"&gt;Identity fallback&lt;/h3&gt;
&lt;p&gt;Again from my previous &lt;a href="2021-03-10-clojure-nil-busting.md"&gt;article about nil busting here&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(defn self-or [other] (fnil identity other))

(-&amp;gt;&amp;gt; [nil nil nil nil nil nil nil nil nil nil nil nil nil &amp;quot;Batman!&amp;quot;]
     (map (self-or &amp;quot;na&amp;quot;))
     (clojure.string/join &amp;quot;, &amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="retrofitting-clojure-string-functions"&gt;Retrofitting clojure string functions&lt;/h3&gt;
&lt;p&gt;Most of the &lt;code&gt;clojure.string&lt;/code&gt; functions don’t like &lt;code&gt;nil&lt;/code&gt;s and will throw NPE at you. &lt;code&gt;fnil&lt;/code&gt; to the rescue!&lt;/p&gt;
&lt;pre class="clj"&gt;&lt;code&gt;(require &amp;#39;[clojure.string :as str])
(sort-by (fnil str/lower-case &amp;quot;&amp;quot;) [&amp;quot;hi&amp;quot; nil &amp;quot;ho&amp;quot;])
;; =&amp;gt; (nil &amp;quot;hi&amp;quot; &amp;quot;ho&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/on-learning-emacs</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>On Learning Emacs</title>
    <updated>2020-11-13T00:00:00Z</updated>
    <published>2020-11-13T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/on-learning-emacs" type="text/html"/>
    <content type="html">&lt;figure&gt;
&lt;img src="/images/emacs_learning_curves.png" alt="Classical learning curves for some common editors" /&gt;&lt;figcaption aria-hidden="true"&gt;Classical learning curves for some common editors&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;&lt;em&gt;Classical learning curves for some common editors&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I once came across a Tweet telling people how to use Emacs like this: step 1, download Emacs; step 2, spend the next 10 years configuring it. At first, this seems pretty silly, yet, there are some truths in it. I, for one, didn’t spend 10 years before becoming comfortable using Emacs as my daily driving horse in software development. However, I could very well imagine that after 10 years I’d still be tinkering my Emacs config with a sense of satisfaction.&lt;/p&gt;
&lt;p&gt;In retrospect, I found it amusing that both of my two favorite tools in software development, i.e. Clojure and Emacs, don’t seem to care much about the friendliness for newcomers. Yes, the community is very welcoming. However, the tools themselves are pretty demanding for the newcomers. Clojure required a huge leap of faith to unlearn most of my previous OOP experiences, whereas Emacs required me to design my own text editor from scratch and to have some understanding of the ELisp programming language. Neither of them promise newcomers to “hit the ground running” or “learn it over the weekend”.&lt;/p&gt;
&lt;p&gt;In my observation, the whole software industry puts too much spotlight on “the latest and the greatest” things. FOMO, the fear of missing out, has fueled a culture of desiring speed. The easiness of learning has become an advertising term for many of the software tools such as libraries and languages. However, &lt;strong&gt;the effectiveness of a tool would eventually outweigh the difficulty to learn it in the long run&lt;/strong&gt;. If I saved myself 15 minutes for using Emacs every day at work, I already saved myself 65 hours last year. That is almost three extra days an year. Even if I initially had spent a full week do nothing but learning Emacs, I would still start seeing the payoffs in the third year, as well as the rest of my life. The math isn’t really important here. To be honest with you, I don’t think I merely saved 15 minutes a day for using Emacs. The important thing is this - the ROI of learning a new tool is a long game. The longer you stick with it, the less significant the initial investment is. What’s more important is the capability of the tool itself.&lt;/p&gt;
&lt;p&gt;That brings me to the next key point: &lt;strong&gt;Emacs isn’t just a text editor.&lt;/strong&gt; Some people think Emacs as their operating system. I like to think &lt;strong&gt;Emacs as an integrated development environment&lt;/strong&gt;. Modern software development usually involves multiple tools: text editor, compiler, interpreter, repl, test runner, version control system, database client, or the browser. Every project is different and there is no one single IDE will meet all needs. We reach different tools for different purposes and inevitably are forced to make context switches. Context switches break our development flow. It’s draining for me to constantly reaching for a different tool with different key bindings or requires me to use the mouse. I really would prefer to stay inside one tool with the same universal key bindings all the time.&lt;/p&gt;
&lt;p&gt;When I started off learning Emacs, I tried to find the best and most conventional way to set it up. I was also feeling wrong for using the Vim key bindings rather than the default Emacs key bindings. This idea seems silly to me now for &lt;strong&gt;there should be no one true way of using Emacs&lt;/strong&gt;. Every one is using Emacs differently, with different background, under different context. I use a different keyboard than most people I know. I have a &lt;a href="https://ergodox-ez.com/pages/planck"&gt;Planck&lt;/a&gt; keyboard that only has 50 keys. A lot of the special characters I cannot type without a modifier key already. I couldn’t afford to hit a key chord that requires hitting multiple modifier keys plus a special character. Something like &lt;code&gt;C-M-$&lt;/code&gt; would be pretty humanly impossible to press with one hand. I’m glad Emacs is flexible enough to fit my needs.&lt;/p&gt;
&lt;p&gt;To recap, here’s my key points: 1. The effectiveness of a tool would eventually outweigh the difficulty to learn it in the long run. 1. Emacs is an integrated development environment rather than a text editor. 1. There’s no one true way of using Emacs.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/default-transducers</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Defaulting to Transducers</title>
    <updated>2023-08-20T00:00:00Z</updated>
    <published>2023-08-20T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/default-transducers" type="text/html"/>
    <content type="html">&lt;p&gt;Transducers are great. I've been defaulting to write transducers as opposed to the lazy-seq operations for the past two years at work. To me, transducers are better building blocks to compose Clojure programs for their many benefits that come with reasonable drawbacks/obstacles. And, you know what, though I don't always like recommending people to do things one way or another: you should default to write transducers, too.&lt;/p&gt;
&lt;p&gt;Here are the reasons:&lt;/p&gt;
&lt;h2 id="reason-1---eagerness-is-almost-always-what-you-want"&gt;Reason 1 - Eagerness is almost always what you want&lt;/h2&gt;
&lt;p&gt;The article &lt;a href="https://clojure-goes-fast.com/blog/clojures-deadly-sin/"&gt;"Clojure's Deadly Sin"&lt;/a&gt; by &lt;a href="https://github.com/alexander-yakushev"&gt;Oleksandr Yakushev&lt;/a&gt; explains the laziness feature in Clojure and, more importantly, the cost of laziness in Clojure. The article is fantastic and of high quality as many other articles on the website, and I highly recommend them all.&lt;/p&gt;
&lt;p&gt;The truth is, when I programmed in Clojure at work for the past 4 years, I rarely relied on laziness (apart from the one time when it made sense for the code organization reason, which I'll come back in &lt;span class="spurious-link" target="*Reason 3 - On-demand laziness"&gt;&lt;em&gt;Reason 3 - On-demand laziness&lt;/em&gt;&lt;/span&gt;.) When I wrote:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(-&amp;gt;&amp;gt; data
     (map some-function)
     (filter some-predicate-fn))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I almost always wanted the data to be mapped and filtered right away. I never intended to return a lazy sequence and let the consumer force its evaluation.&lt;/p&gt;
&lt;p&gt;&lt;code class="verbatim"&gt;lazy-seq&lt;/code&gt; is a pretty nice abstraction for a source of an infinite stream of data, but the usage for laziness pretty much ends there. If a software process can be split into three parts: a) pulling, b) transformation, and c) pushing, then pulling is the only place where laziness makes sense because a process could be pulling from an infinite source of data. I've never seen a place where I need my transformation stage or pushing stage to be lazy.&lt;/p&gt;
&lt;p&gt;Lazy transformation can cause &lt;a href="https://github.com/reagent-project/reagent/issues/18"&gt;the issue with reactive deref in lazy-seqs in Reagent&lt;/a&gt;, which almost all ClojureScript front-end dev I worked with (myself included) had to face at some point in their career. The lesson learned here is that you always want to eagerly evaluate the &lt;code class="verbatim"&gt;lazy-seqs&lt;/code&gt; in the Reagent component's rendering function.&lt;/p&gt;
&lt;p&gt;Lazy pushing isn't ideal, either. Although mapping a side-effect function over a sequence is almost certainly an anti-pattern, sometimes there are use cases for it. However, laziness in such cases might make you scratch your head for hours until you realize why the side effect never happened.&lt;/p&gt;
&lt;h2 id="reason-2---performance"&gt;Reason 2 - Performance&lt;/h2&gt;
&lt;p&gt;Quote the example and numbers from &lt;a href="https://clojure-goes-fast.com/blog/clojures-deadly-sin/#performance-overhead"&gt;the performance overhead numbers from Clojure's Deadly Sin&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;;;;; Lazy map

(time+
 (-&amp;gt;&amp;gt; (repeat 1000 10)
      (map inc)
      (map inc)
      (map #(* % 2))
      (map inc)
      (map inc)
      doall))

;; Time per call: 410.22 us   Alloc per call: 480,296b

;;;; Transducers+into

(time+
 (into []
       (comp (map inc)
             (map inc)
             (map #(* % 2))
             (map inc)
             (map inc))
       (repeat 1000 10)))

;; Time per call: 43.95 us   Alloc per call: 6,264b
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, the transducer version isn't that much different (visually) from the lazy map version (such that you can almost glance over it without realizing it is using transducers.) It's a bit ridiculous that the performance of the transducer version (with &lt;code class="verbatim"&gt;clojure.core/into&lt;/code&gt;) is &lt;strong&gt;almost 10 times faster&lt;/strong&gt; than the lazy map version and produces &lt;strong&gt;almost 80 times less memory usage&lt;/strong&gt; on the heap. Yes, we are getting into the territory of &lt;a href="https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize"&gt;premature optimization&lt;/a&gt;. However, considering how much code we Clojurians write is about functional transformation like this and how little friction it is to use transducers, I think transducers should be the default for most cases for most people instead of the other way around.&lt;/p&gt;
&lt;h2 id="reason-3---on-demand-laziness"&gt;Reason 3 - On-demand laziness&lt;/h2&gt;
&lt;p&gt;This reason number 3 is teased in &lt;span class="spurious-link" target="*Reason 1 - Eagerness is almost always what you want"&gt;&lt;em&gt;Reason 1 - Eagerness is almost always what you want&lt;/em&gt;&lt;/span&gt;: there was one instance at work where I still required some level of laziness because of the code organization like the following:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;;; (ns a)
(defn s [db]
  ,,,)

;; (ns b)
(defn b [db]
  (into []
        ;; transformation: t-b
        (comp (map ,,,)
              (filter ,,,))
        (a/s db)))

;; (ns c)
(defn c [db n]
  (into []
        ;; transformation: t-c
        (comp (map ,,,)
              (filter ,,,)
              (take n))
        (a/s db)))
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;ns &lt;code class="verbatim"&gt;a&lt;/code&gt; defines a data source &lt;code class="verbatim"&gt;s&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;ns &lt;code class="verbatim"&gt;b&lt;/code&gt; depends on &lt;code class="verbatim"&gt;a&lt;/code&gt;'s data source and does some transformation &lt;code class="verbatim"&gt;t-b&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Transformation &lt;code class="verbatim"&gt;t-b&lt;/code&gt; requires the full set of data source &lt;code class="verbatim"&gt;s&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;ns &lt;code class="verbatim"&gt;c&lt;/code&gt; depends on &lt;code class="verbatim"&gt;a&lt;/code&gt;'s data source and does some transformation &lt;code class="verbatim"&gt;t-c&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Transformation &lt;code class="verbatim"&gt;t-c&lt;/code&gt; only requires the first filtered &lt;code class="verbatim"&gt;n&lt;/code&gt; data points from &lt;code class="verbatim"&gt;s&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Now, imagine some common transformation, &lt;code class="verbatim"&gt;t-0&lt;/code&gt;, that both &lt;code class="verbatim"&gt;t-b&lt;/code&gt; and &lt;code class="verbatim"&gt;t-c&lt;/code&gt; depend on, such as some data normalization logic. In this case, &lt;code class="verbatim"&gt;a&lt;/code&gt; would be the ideal place to host this logic. We don't want to transduce the data source &lt;code class="verbatim"&gt;s&lt;/code&gt; with &lt;code class="verbatim"&gt;t-0&lt;/code&gt; in ns &lt;code class="verbatim"&gt;a&lt;/code&gt; because &lt;code class="verbatim"&gt;c&lt;/code&gt; does not need the rest of the data to be transformed after the &lt;code class="verbatim"&gt;n+1&lt;/code&gt; data point. Therefore, the problem is this: how do we bind the transformation &lt;code class="verbatim"&gt;t-0&lt;/code&gt; to the data source &lt;code class="verbatim"&gt;s&lt;/code&gt; early but hold off the evaluation later? If that sounds like laziness to you, congratulations! You are correct that this is laziness again. However, there is a different type of laziness that doesn't cost us performance.&lt;/p&gt;
&lt;p&gt;This is the use case for &lt;code class="verbatim"&gt;clojure.core/eduction&lt;/code&gt;. It gives you a different type of laziness - a pushing type of laziness (whereas the lazy map/filter is the pulling type of laziness.) This allows us to bind the data source with some transformation early. This early-bounded transformation &lt;code class="verbatim"&gt;t-0&lt;/code&gt; would only be invoked until this Eduction object is being transduced.&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;;; (ns a)
(defn s [db]
  ,,,)

(defn s-normalized [db]
  (eduction (map normalize)             ; transformation t-0
            (s db)))

;; (ns b)
(defn b [db]
  (into []
        ;; transformation t-b
        (comp (map ,,,)
              (filter ,,,))
        (a/s-normalized db)))

;; (ns c)
(defn c [db n]
  (into []
        ;; transformation t-c
        (comp (map ,,,)
              (filter ,,,)
              (take n))
        (a/s-normalized db)))
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="things-to-consider"&gt;Things to consider&lt;/h2&gt;
&lt;p&gt;Here are a few things to consider that may or may not be obstacles for you:&lt;/p&gt;
&lt;h3 id="shapes-of-the-program-can-be-a-bit-tricky"&gt;Shapes of the program can be a bit tricky&lt;/h3&gt;
&lt;p&gt;Consider the shape of the code from this example that most Clojure devs are familiar with and how to rewrite it using transducers:&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;;; Variation #1: Lazy map
(-&amp;gt;&amp;gt; (repeat 1000 10)
     (map inc)
     (map inc)
     (map #(* % 2))
     (map inc)
     (map inc)
     doall)

;; Variation #2: Transduer+into
(into []
      (comp (map inc)
            (map inc)
            (map #(* % 2))
            (map inc)
            (map inc))
      (repeat 1000 10))

;; Variation #3: Transducer+into+thread-last
(-&amp;gt;&amp;gt; (repeat 1000 10)
     (into []
           (comp (map inc)
                 (map inc)
                 (map #(* % 2))
                 (map inc)
                 (map inc))))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I personally tend to write variation #3 for its resemblance to the lazy map variation. However, notice that the code is wider, and the indentation level is deeper now. Instead of all vertically aligned at 5 spaces in variation #1, the inner-most transducers (the mappers inside the `comp` form) in variation #3 are now indented with 17 spaces. I like the aesthetics of variation #1 the most, to be honest, but I've convinced myself to write variation #2 or #3 for their benefits.&lt;/p&gt;
&lt;h3 id="imperative-programming-for-fully-customized-transducers"&gt;Imperative programming for fully customized transducers&lt;/h3&gt;
&lt;p&gt;This obstacle will probably throw many die-hard functional programmers off. However, we Clojure programmers are practical, and it's okay to throw in some local states in a controlled manner. At work, I needed a partitioning logic that partitions the data using the running total so each partition has a running total of less than a given limit while maintaining the order of the data.&lt;/p&gt;
&lt;p&gt;This problem fits the use cases for transducers well, even though I don't really care about integrating it with &lt;code class="verbatim"&gt;core.async&lt;/code&gt; at the moment, but I know the option is open to the future. I implemented this with a custom transducer function that accepts the limit number (and a few other key functions) and returns a transducer. The implementation itself isn't that hard to figure out with the help of the &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L7160-L7194"&gt;&lt;code class="verbatim"&gt;clojure.core/partition-by&lt;/code&gt; source code&lt;/a&gt;. Below is the simplified implementation of the &lt;code class="verbatim"&gt;partition-by-running-total&lt;/code&gt; custom transducer (note that this simplified version doesn't handle an initial value that's larger than the limit gracefully, but I want to burry you with too many details):&lt;/p&gt;
&lt;pre class="clojure"&gt;&lt;code&gt;(defn partition-by-running-total [limit]
  (fn [rf]
    (let [a (java.util.ArrayList.)
          total (volatile! 0)]
      (fn
        ([] (rf))
        ([result]
         (let [result (if (.isEmpty a)
                        result
                        (let [v (vec (.toArray a))]
                          (.clear a)
                          (unreduced (rf result v))))]
           (rf result)))
        ([result input]
         (let [total-val @total]
           (if (&amp;lt;= (+ total-val input) limit)
             (do
               (.add a input)
               (vswap! total + input)
               result)
             (let [v (vec (.toArray a))]
               (.clear a)
               (let [ret (rf result v)]
                 (when-not (reduced? ret)
                   (.add a input)
                   (vreset! total input))
                 ret)))))))))

(into [] (partition-by-running-total 10) [2 5 5 5 2 2 2 5])
;; =&amp;gt; [[2 5] [5 5] [2 2 2] [5]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The implementation of this custom transducer undoubtedly requires writing imperative code to keep track of and mutate the internal states. However, this is the only case in the past 4 years where I needed to implement the transducer from the ground up. Chances are that the &lt;code class="verbatim"&gt;clojure.core&lt;/code&gt; already has you covered.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;I think you should default to compose transducers for all the sequence transformations&lt;/strong&gt;. Transducers are more optimized for speed and memory. You can opt-in for laziness when needed. And they are as easy to compose. If you are not already writing transducers as your default, please give them a try.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/closures-bind-late</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Closures bind late</title>
    <updated>2017-02-18T00:00:00Z</updated>
    <published>2017-02-18T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/closures-bind-late" type="text/html"/>
    <content type="html">&lt;p&gt;“Closure is a turtle carrying its shell,” my favorite explanation to closures, quote by &lt;a href="https://twitter.com/raymondh"&gt;Raymond Hettinger&lt;/a&gt;. With closures, lots of great features are possible in Python like higher order functions and decorators.&lt;/p&gt;
&lt;p&gt;I came across this StackOverflow post - &lt;a href="http://stackoverflow.com/questions/42003351/how-can-i-return-a-function-that-uses-the-value-of-a-variable"&gt;How can I return a function that uses the value of a variable?&lt;/a&gt; , which helped me bridging the gap in my knowledge, the gap that I sort-of understood it but couldn’t explain it very well. The bridge is just a simple sentence, “closures bind late.”&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;What does “closures bind late” mean exactly? Consider a function generator that generates a series of multiplication functions starting from 0 to &lt;code&gt;max&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def mult_function_generator(max):
    for i in range(max):
        yield lambda x: x * i

mult_functions = list(mult_function_generator(3))
print([func(3) for func in mult_functions])
# Oh crap, it&amp;#39;s [6, 6, 6], not [0, 3, 6]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Seems like all the &lt;code&gt;i&lt;/code&gt;s in the generated functions are assigned to 2, which is the last value of &lt;code&gt;i&lt;/code&gt; after all functions were being generated. Let’s take a closer look at what’s behind the scene. First of all, how does a closure represent in Python, or, how the turtle shell looks like:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;mult_functions = mult_function_generator(3)
mult_zero = next(mult_functions)
mult_zero
# &amp;lt;function ...&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To look at the closure, there’s a special attribute in each function called &lt;code&gt;__closure__&lt;/code&gt; (quite obvious, huh?)&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;mult_zero.__closure__
# (&amp;lt;cell at 0x..., int object at 0x...&amp;gt;,)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Okay, we are getting closer. The &lt;code&gt;__closure__&lt;/code&gt; attribute is a tuple of &lt;code&gt;cell&lt;/code&gt; objects. Let’s see what’s inside the cell, which has an attribute &lt;code&gt;cell_contents&lt;/code&gt; to help us:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;cell_zero = mult_zero.__closure__[0]
cell_zero.cell_contents
# 0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Bingo! This is the int object &lt;code&gt;i&lt;/code&gt; that trapped inside the function’s closure.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(I haven’t figured out how Python find the reference of &lt;code&gt;i&lt;/code&gt; so I won’t go any further. For more discussion please refer to the Appendix section.)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The interesting thing is, the same cell object is used across our multiplication functions. Thus, when we get the second function:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;mult_one = next(mult_functions)
cell_one = mult_one.__closure__[0]
cell_one.cell_contents
# 1
# So far so good. But...
cell_zero.cell_contents
# 1
# Crap!
cell_zero is cell_one
# True
# Okay fine&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The same cell object means the same reference to &lt;code&gt;i&lt;/code&gt;. This explains what happened in this example. Or, if you like, you could explain all this by saying, “closures bind late.” They are both correct but just with different mental models.&lt;/p&gt;
&lt;p&gt;Now we understand the problem that introduced by late binding. Let’s see how to bind the variable during function declaration. The idea is to have &lt;code&gt;i&lt;/code&gt; also be a argument passed into the lambda function and then we assign the value immediately:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def mult_function_generator(max):
    for i in range(max):
        yield (lambda i: lambda x: x * i)(i)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or if you like partial functions:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def mult_function_generator(max):
    for i in range(max):
        yield functools.partial(lambda x, i: x * i, i=i)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or my favorite one:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def mult_function_generator(max):
    for i in range(max):
        yield lambda x, i=i: x * i&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The last one works because default arguments is assigned when the function is defined.&lt;/p&gt;
&lt;h3 id="bonus"&gt;Bonus&lt;/h3&gt;
&lt;p&gt;My favorite example for taking advantage of the late binding closure is from &lt;a href="https://www.oreilly.com/learning/20-python-libraries-you-arent-using-but-should"&gt;20 Python libraries you aren’t using (but should)&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;from time import perf_counter
from array import array
from contextlib import contextmanager

@contextmanager
def timing(label: str):
    t0 = perf_counter()
    yield lambda: (label, t1 - t0)
    t1 = perf_counter()

with timing(&amp;#39;Array tests&amp;#39;) as total:
    with timing(&amp;#39;Array creation innermul&amp;#39;) as inner:
        x = array(&amp;#39;d&amp;#39;, [0] * 1000000)

    with timing(&amp;#39;Array creation outermul&amp;#39;) as outer:
        x = array(&amp;#39;d&amp;#39;, [0]) * 1000000


print(&amp;#39;Total [%s]: %.6f s&amp;#39; % total())
print(&amp;#39;    Timing [%s]: %.6f s&amp;#39; % inner())
print(&amp;#39;    Timing [%s]: %.6f s&amp;#39; % outer())

# Total [Array tests]: 0.064896 s
#    Timing [Array creation innermul]: 0.064195 s
#    Timing [Array creation outermul]: 0.000659 s&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="appendix---discussion-on-loading-a-dereferenced-variable"&gt;Appendix - discussion on loading a dereferenced variable&lt;/h3&gt;
&lt;p&gt;Take the &lt;code&gt;mult_zero&lt;/code&gt; function for example. The dissembled code looks:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;  3           0 LOAD_FAST                0 (x)
              2 LOAD_DEREF               0 (i)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second line calls the &lt;code&gt;LOAD_DEREF&lt;/code&gt; op code in Python. My guess is that the name &lt;code&gt;i&lt;/code&gt; was never dereferenced because the cell object still holds a reference on it. However, &lt;code&gt;i&lt;/code&gt; must be treated specially since &lt;code&gt;i&lt;/code&gt; isn’t visible to the scope outside the closure functions. My next move will be looking into the CPython code to see how this op code works exactly.&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/you-probably-dont-need-for-loops</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>You probably don't need for loops</title>
    <updated>2016-11-17T00:00:00Z</updated>
    <published>2016-11-17T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/you-probably-dont-need-for-loops" type="text/html"/>
    <content type="html">&lt;p&gt;&lt;em&gt;Originally titled “Never Write For-loops again”&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;This is a challenge. I challenge you to avoid writing for-loops in every scenario. Also, I challenge you to find the scenarios that are so freaking hard to write anything else but a for-loop. Please share your findings. I’d like to hear about them.&lt;/p&gt;
&lt;p&gt;It’s been a while since I started exploring the amazing language features in Python. At the beginning, it’s just a challenge I gave myself to practice using more language features instead of those I learned from other programming language. And things are just getting more fun! Not only the code become shorter and cleaner, but also code looks more structured and disciplined. I’ll get into those benefits more in this article.&lt;/p&gt;
&lt;!-- more --&gt;
&lt;p&gt;But first, let’s take a step back and see what’s the intuition behind writing a for-loop:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;To go through a sequence to extract out some information&lt;/li&gt;
&lt;li&gt;To generate another sequence out of the current sequence&lt;/li&gt;
&lt;li&gt;This is my second nature to write for-loops because I’m a programmer&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Fortunately, there are already great tools that are built into Python to help you accomplish the goals! All you need is to shift your mind and look at the things in a different angle.&lt;/p&gt;
&lt;h1 id="what-you-gain-by-not-writing-for-loops-everywhere"&gt;What you gain by not writing for-loops everywhere&lt;/h1&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Fewer lines of code&lt;/li&gt;
&lt;li&gt;Better code readability&lt;/li&gt;
&lt;li&gt;Leave indentation for managing context only&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let’s see the code skeleton below:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;# 1
with ...:
    for ...:
        if ...:
            try:
            except:
        else:&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, we are dealing with multiple layers of code. THIS IS HARD TO READ. The problem I found in this code is that it is mixing the &lt;strong&gt;administrative&lt;/strong&gt; logic (the &lt;code&gt;with&lt;/code&gt;, &lt;code&gt;try-except&lt;/code&gt;) with the &lt;strong&gt;business logic&lt;/strong&gt; (the &lt;code&gt;for&lt;/code&gt;, &lt;code&gt;if&lt;/code&gt;) by giving them the indentation ubiquitously. If you are disciplined about using indentation only for administrative logic, your core business logic would stand out immediately.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Flat is better than nested” - The Zen of Python&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h1 id="tools-you-can-use-to-avoid-using-for-loops"&gt;Tools you can use to avoid using for-loops&lt;/h1&gt;
&lt;h2 id="list-comprehension-generator-expression"&gt;1. List Comprehension / Generator Expression&lt;/h2&gt;
&lt;p&gt;Let’s see a simple example. Basically you want to compile a sequence based on another existing sequence:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;result = []
for item in item_list:
    new_item = do_something_with(item)
    result.append(item)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can use &lt;code&gt;map&lt;/code&gt; if you love MapReduce, or, Python has List Comprehension:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;result = [do_something_with(item) for item in item_list]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Similarly, if you wish to get a iterator only, you can use Generator Expression with almost the same syntax. (How can you not love the consistency in Python?)&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;result = (do_something_with(item) for item in item_list)&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="functions"&gt;2. Functions&lt;/h2&gt;
&lt;p&gt;Thinking in a higher-order, more functional programming way, if you want to map a sequence to another, simply call the &lt;code&gt;map&lt;/code&gt; function. (Be my guest to use list comprehension here instead.)&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;doubled_list = map(lambda x: x * 2, old_list)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want to reduce a sequence into a single, use &lt;code&gt;reduce&lt;/code&gt;&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Also, lots of Python’s builtin functions consumes iterables:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = list(range(10))
&amp;gt;&amp;gt;&amp;gt; a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
&amp;gt;&amp;gt;&amp;gt; all(a)
False
&amp;gt;&amp;gt;&amp;gt; any(a)
True
&amp;gt;&amp;gt;&amp;gt; max(a)
9
&amp;gt;&amp;gt;&amp;gt; min(a)
0
&amp;gt;&amp;gt;&amp;gt; list(filter(bool, a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
&amp;gt;&amp;gt;&amp;gt; set(a)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
&amp;gt;&amp;gt;&amp;gt; dict(zip(a,a))
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
&amp;gt;&amp;gt;&amp;gt; sorted(a, reverse=True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
&amp;gt;&amp;gt;&amp;gt; str(a)
&amp;#39;[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]&amp;#39;
&amp;gt;&amp;gt;&amp;gt; sum(a)
45&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="extract-functions-or-generators"&gt;3. Extract Functions or Generators&lt;/h2&gt;
&lt;p&gt;The above two methods are great to deal with simpler logic. How about more complex logic? As a programmer, we write functions to abstract out the difficult things. Same idea applies here. If you are writing this:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;results = []
for item in item_list:
    # setups
    # condition
    # processing
    # calculation
    results.append(result)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Apparently you are giving too much responsibility to a single code block. Instead, I propose you do:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def process_item(item):
    # setups
    # condition
    # processing
    # calculation
    return result

results = [process_item(item) for item in item_list]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;How about nested for-loops?&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;results = []
for i in range(10):
    for j in range(i):
        results.append((i, j))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;List Comprehension got your back:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;results = [(i, j)
           for i in range(10)
           for j in range(i)]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;How about if you have some internal state in the code block to keep?&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;# finding the max prior to the current item
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = []
current_max = 0
for i in a:
    current_max = max(i, current_max)
    results.append(current_max)

# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s extract a generator to achieve this:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;def max_generator(numbers):
    current_max = 0
    for i in numbers:
        current_max = max(i, current_max)
        yield current_max

a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = list(max_generator(a))&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;“Oh wait, you just used a for-loop in the generator function. That’s cheating!”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Fine, smart ass, let’s try the following.&lt;/p&gt;
&lt;h2 id="dont-write-it-yourself.-itertools-got-you-covered"&gt;4. Don’t write it yourself. &lt;code&gt;itertools&lt;/code&gt; got you covered&lt;/h2&gt;
&lt;p&gt;This module is simply brilliant. I believe this module covers 80% of the cases that you makes you want to write for-loops. For example, the last example can be rewritten to:&lt;/p&gt;
&lt;pre class="python"&gt;&lt;code&gt;from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Also, if you are iterating on combinatoric sequences, there are &lt;code&gt;product()&lt;/code&gt;, &lt;code&gt;permutations()&lt;/code&gt;, &lt;code&gt;combinations()&lt;/code&gt; to use.&lt;/p&gt;
&lt;h1 id="conclusion"&gt;Conclusion&lt;/h1&gt;
&lt;ol type="1"&gt;
&lt;li&gt;You don’t need to write for-loops in most scenarios&lt;/li&gt;
&lt;li&gt;You should avoid writing for-loops, so you have better code readability&lt;/li&gt;
&lt;/ol&gt;
&lt;h1 id="action"&gt;Action&lt;/h1&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Look at your code again. Spot any places that you wrote a for-loop previously by intuition. Think again and see if it make sense to re-write it without using for-loop.&lt;/li&gt;
&lt;li&gt;Share your cases that are hard to code without using for-loops&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;em&gt;This &lt;a href="https://medium.com/@dawranliou/never-write-for-loops-again-91a5a4c84baf"&gt;article&lt;/a&gt; was originally posted in my &lt;a href="https://medium.com/@dawranliou"&gt;Medium blog&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry xml:lang="en">
    <id>https://dawranliou.com/blog/clojure-higher-order-functions-explained</id>
    <author>
      <name>Daw-Ran Liou</name>
    </author>
    <title>Clojure higher-order functions explained: index</title>
    <updated>2021-03-12T00:00:00Z</updated>
    <published>2021-03-12T00:00:00Z</published>
    <link href="https://dawranliou.com/blog/clojure-higher-order-functions-explained" type="text/html"/>
    <content type="html">&lt;p&gt;Besides all the other amazing things Clojure enables, I just want to take a moment to appreciate Clojure being a functional programming language that offers many higher-order functions out of the box great for daily tasks. Although the usage of higher-order functions could sometimes lead to too much cleverness in the code, and arguably bad for readability (apologies to my colleagues), it’s really fun to express code without creating any one-off anonymous function explicitly.&lt;/p&gt;
&lt;p&gt;This post is the index to all the articles in the series and the future articles in the planning.&lt;/p&gt;
&lt;h2 id="the-index"&gt;The Index&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Updated 2021-03-23&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="/blog/clojure-higher-order-functions-explained-fnil"&gt;fnil&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/blog/clojure-higher-order-functions-explained-complement"&gt;complement&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="the-backlog"&gt;The Backlog&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;comp&lt;/li&gt;
&lt;li&gt;partial&lt;/li&gt;
&lt;li&gt;juxt&lt;/li&gt;
&lt;li&gt;constantly&lt;/li&gt;
&lt;li&gt;every-pred&lt;/li&gt;
&lt;li&gt;some-fn&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>
</feed>
