<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[functional and mathematical]]></title><description><![CDATA[I enjoy combining computer science ,mathematics and machine learning, and reflect on critical thinking]]></description><link>https://blog.functorcoder.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 15:24:31 GMT</lastBuildDate><atom:link href="https://blog.functorcoder.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Complex systems, Chaos and ecosystem part 1: the defiance to  reductionism]]></title><description><![CDATA[Reductionism, a philosophy that seeks to handle complexity by breaking into parts, serves as the corner stone for industrial revolution and contemporary science. This top-down approach is also quite compatible with the social hierarchy that rich peop...]]></description><link>https://blog.functorcoder.com/complex-systems-chaos-and-ecosystem-the-defiance-to-reductionism</link><guid isPermaLink="true">https://blog.functorcoder.com/complex-systems-chaos-and-ecosystem-the-defiance-to-reductionism</guid><category><![CDATA[Mathematics]]></category><category><![CDATA[Complexity]]></category><dc:creator><![CDATA[Eason Du]]></dc:creator><pubDate>Fri, 12 Apr 2024 09:44:09 GMT</pubDate><content:encoded><![CDATA[<p>Reductionism, a philosophy that seeks to handle complexity by breaking into parts, serves as the corner stone for industrial revolution and contemporary science. This top-down approach is also quite compatible with the social hierarchy that rich people have more power and control over the society, as the conerstone of modern neoliberal capitalism.  </p>
<p>However, The whole is often greater than the sum of its parts, and the attempt to understand complex systems through reductionism neglects the interactions, emergent behaviors, and non-linear dynamics within the system.  </p>
<p>In neuroscience and artificial intelligence, attempting to understand consciousness through the examination of individual neurons can't answer how consciousness emerge from those simple parts, as well as trying to create intelligence by connect neurons in a predefined way, whatsoever it's convolutional, hierarchical or recurrent. Similarly, In ecology, reducing an ecosystem to its individual species is unable to explain the stability,resilience and at the same time, the fragility of ecosystem.  </p>
<p>Aside from those complicated systems, simple deterministic system may show unpredictable behaviors. In this article, I will introduce the concept of dynamical systems and show some of those systems described with simple mathematical formula.  </p>
<p>In this part 1 note, basic concepts of dynamical systems like phase space, trajectory, bifurcation, Feigenbaum constant will be introduced, and we mostly focus on examples.<br />Advanced concepts like chaos, renormalization, self-organization will be discussed in the next part, as well as the mathematical tools.</p>
<h2 id="heading-define-chaos">Define Chaos</h2>
<p>For a particular <strong>mathematical formula or computation process</strong>(like calculate the trajectory of three body system, predict weather ,etc), a slightly different <strong>initial condition, or input, would result in very different result</strong>.</p>
<p>What does this sensitivity implies? For an computation process to be useful, we usually expect to get similar result for similar input, otherwise the output is not meaningful since a small rounding error will invalidate the result.</p>
<h2 id="heading-sensitivity-to-initial-condition">sensitivity to initial condition</h2>
<p>To display the essence of chaotic behavior, we start from simple deterministic mathematics formulas.</p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Three-body_problem">Example</a>: a slightly different <a target="_blank" href="https://en.wikipedia.org/wiki/Initial_condition">initial condition would result in</a> a vastly different <a target="_blank" href="https://en.wikipedia.org/wiki/Trajectory">trajectory</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712259710907/ad57dd53-75f4-4074-9178-ffb93e22e0a9.png" alt class="image--center mx-auto" /></p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Three-body_problem">Example</a>: Three 2 node system with slightly different initial condition:</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Demonstrating_Chaos_with_a_Double_Pendulum.gif/220px-Demonstrating_Chaos_with_a_Double_Pendulum.gif" alt /></p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/4/45/Double-compound-pendulum.gif" alt="File:Double-compound-pendulum.gif" /></p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Three-body_problem">Example</a>: logistic map</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712259209275/bac24936-d763-4373-8903-26d334915a53.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712259303803/4c6513eb-ac41-4c8a-ab06-fa56cfdce427.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712259351580/158e910a-6a61-4e69-8d42-7c32b31dd517.png" alt class="image--center mx-auto" /></p>
<p>Example: Three-body problem</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/1/1c/Three-body_Problem_Animation_with_COM.gif" alt /></p>
<p>Example: Biosphere II was a expensive failure to create a self-sustaining replica of Earth ecosystems.</p>
<p>Example</p>
<p>while we are sure about our location in the short run, we can not say precisely where we are at a specific date in the long run, for example in a year.</p>
<h2 id="heading-describe-and-analyze-chaos-dynamical-systems-theory">Describe and analyze Chaos: dynamical systems theory</h2>
<p>Although we can't calculate chaotic system in the usual way, there are some new tools that will shed some light.</p>
<h3 id="heading-bifurcation-diagram">bifurcation diagram</h3>
<p>for the logistic map example we just discussed, this diagram plots the stabilized x value versus the parameter R:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712259390336/03a37aba-c6b8-489b-9643-68dad0cd8f8a.png" alt class="image--center mx-auto" /></p>
<p>As the parameter R increase at 3.0, X have more possible values.</p>
<h3 id="heading-phase-space">phase space</h3>
<p>In dynamical systems theory and control theory, a <strong>phase space</strong> or state space is a space to display all possible "states"(positions), in contrast to the <strong>trajectory</strong>(position at specific time t) of the system.</p>
<p>Example: <a target="_blank" href="https://verzep.github.io/Learning-Lorenz/">https://verzep.github.io/Learning-Lorenz/</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712914723307/80e5097c-7187-416c-93ad-16221073e5f3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712914698411/d495b82d-95c1-4d9b-9c69-bf18b9e58f2a.png" alt class="image--center mx-auto" /></p>
<p>In space (x,y,z) - time</p>
<p><img src="https://skepticalscience.com/images/chaos1.gif" alt="Chaos theory and global warming: can climate be predicted?" /></p>
<p>In phase space (x,y,z):</p>
<p><img src="https://miro.medium.com/v2/resize:fit:1313/1*4zLik4-PUVjdBDAp3BpWSQ.png" alt /></p>
<h3 id="heading-feigenbaum-constant">Feigenbaum constant:</h3>
<p>The constant represents the ratio of the difference in parameter values at which successive bifurcations occur as a system undergoes a period-doubling route to chaos. It has an approximate value of 4.6692.</p>
<p>TBD</p>
<h2 id="heading-ai-and-the-failed-prediction-of-chaos">AI and the failed prediction of Chaos</h2>
<p>TBD<br />Lorenz System <a target="_blank" href="https://verzep.github.io/Learning-Lorenz/">https://verzep.github.io/Learning-Lorenz/</a></p>
<h1 id="heading-reference">Reference:</h1>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Three-body_problem">https://en.wikipedia.org/wiki/Three-body_problem</a></p>
<p>Complexity: A Guided Tour , by Melanie Mitchell</p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Chaos_theory">https://en.wikipedia.org/wiki/Chaos_theory</a></p>
<p>lorenz equation: <a target="_blank" href="https://www.math.fsu.edu/~bertram/lectures/Chaos.pdf">https://www.math.fsu.edu/~bertram/lectures/Chaos.pdf</a></p>
<p><a target="_blank" href="https://verzep.github.io/Learning-Lorenz/">https://verzep.github.io/Learning-Lorenz/</a></p>
<p><a target="_blank" href="https://gereshes.com/2018/11/19/chaos-and-the-double-pendulum/">https://gereshes.com/2018/11/19/chaos-and-the-double-pendulum/</a></p>
<h3 id="heading-qa">QA:</h3>
<p>I presented this in a meeting and got some good questions:</p>
<p>Are chaotic systems calculable?</p>
<p>yes, if you have extremely accuracy of the initial condition. There're two way to address this: 1. we continue to quest for higher precision. 2. we accept this difficulty and give up for precise prediction/computation</p>
<p>In addition, someone mentioned Kolmogorov–Arnold–Moser about the persistence of quasiperiodic motions under small perturbations, which can be seen as a special case when computation is desirable.</p>
]]></content:encoded></item><item><title><![CDATA[The banality of life under capitalism in The Matrix Resurrections (The Matrix 4), part 1]]></title><description><![CDATA[I recently listened to a summary of "Capital in the Twenty-First Century" and feel the Déjà vu to watched "The Matrix Resurrections" again. Piketty's controversial book delves into the historical analysis of wealth inequality and conclude statistical...]]></description><link>https://blog.functorcoder.com/the-banality-of-life-under-capitalism-in-the-matrix-resurrections-the-matrix-4-part-1</link><guid isPermaLink="true">https://blog.functorcoder.com/the-banality-of-life-under-capitalism-in-the-matrix-resurrections-the-matrix-4-part-1</guid><category><![CDATA[Environment]]></category><category><![CDATA[Science ]]></category><category><![CDATA[society]]></category><category><![CDATA[#ecology]]></category><category><![CDATA[Movies]]></category><dc:creator><![CDATA[Eason Du]]></dc:creator><pubDate>Tue, 19 Mar 2024 23:37:03 GMT</pubDate><content:encoded><![CDATA[<p>I recently listened to a summary of "Capital in the Twenty-First Century" and feel the <em>Déjà vu</em> to watched "The Matrix Resurrections" again. Piketty's controversial book delves into the historical analysis of wealth inequality and conclude statistically that the capital increase much faster that the economy or salaries(exclude those hefty CEO pay raise).</p>
<p>Visually, the first half of The Matrix Resurrections presents a dystopia dominated by corporate power and consumerism, raising questions about the nature of reality, identity, and liberation from capitalist systems. Those scenes where Neo work as game designers provoke me deeply and shows directly how capitalism is able to internalize and commodify everything you can think of, like natural resources, holidays and Valentine's day. Free resources like clean water and air are more like luxuries now since PFAS and exhaust from cars are everywhere.</p>
<p>Not unexpectedly, The director Lilly Wachowski Claims The Matrix series was Born Out Of “Rage At Capitalism”. Neo now works as a game designer for a top game company, MetaCortex.<br />It's always hard to get up in the morning everyday:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710712470243/218e1310-4576-46be-a9a5-ccdfd879d5cc.png" alt class="image--center mx-auto" /></p>
<p>Looks like your dream office?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710697643065/7e36cc8f-9483-46aa-8331-2bc9eff129f4.png" alt class="image--center mx-auto" /></p>
<p>Despite his extraordinary capabilities in his professional career, Neo finds himself trapped in mundane routine, making him mentally sick, thus seeking help from the psychology consultant "The Analyst " which we will talk about in the next part.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710697740520/24f3b11b-28b2-459e-a590-622be8375b64.png" alt class="image--center mx-auto" /></p>
<p>The conversations among Neo's colleagues about the latest Matrix game represent the commodification of creativity and the reduction of art to a mere product for consumption. Instead of engaging in meaningful discussions about the philosophical or artistic implications of their work, they focus on market trends, sales figures, and competition, reflecting the prioritization of profit over genuine artistic expression.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710697770617/ee48f2f5-5e9e-40dd-9032-f4cf88131623.png" alt class="image--center mx-auto" /></p>
<p>The scenes where Neo and his colleagues play leisure games in the office highlight the superficial distractions that capitalism offers to workers as a means of pacifying them and preventing deeper introspection or dissatisfaction. These escapism allows employees to momentarily forget the monotony of their work while reinforcing the status quo that you are still working. I still remember those pictures of dream office in Google:</p>
<p><img src="https://media.licdn.com/dms/image/C5622AQFBAea67Dd3PA/feedshare-shrink_800/0/1620132766715?e=1713398400&amp;v=beta&amp;t=8UWeEtxBFhTQ353nRWxwGw1ehqrkGXseRPj0VYuXFK8" alt="No alternative text description for this image" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710697792204/ed3159e6-2898-48cb-b37b-359beedbb312.png" alt class="image--center mx-auto" /></p>
<p>The archaic luxury hand pressed coffee machine depicts the ubiquitous presence of coffee in the workplace, symbolizes the reliance on stimulants and comforts to cope with the demands of productivity. Trying to build an artistic feeling by combining caffeine and red bricks?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710697899761/8dd9bd90-3085-4ab5-be90-3f3458f22047.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710697953696/66638e91-7659-46ef-84ec-5fbdcba55053.png" alt class="image--center mx-auto" /></p>
<p>Coffee breaks, though ostensibly a moment of respite, ultimately serve to perpetuate the cycle of consumption and production, reinforcing the expectation of constant productivity and the normalization of overwork.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1710698735971/4063585f-dddd-40b9-a92c-720cf2d467ae.png" alt class="image--center mx-auto" /></p>
<p>The scenes depicting Neo and his boss enjoying the view from skyscrapers underscore the illusion of success and prosperity perpetuated by capitalism. The impressive skyline and luxurious corporate offices create an illusion of achievement and progress, masking the underlying exploitation and inequality inherent in the system. The view serves as a distraction from the harsh realities of capitalism, perpetuating the myth of upward mobility, meritocracy.</p>
<p>"The Matrix Resurrections" illustrate how capitalism commodifies non tradable experiences, offering pleasures to maintain control and prevent individuals from questioning the underlying structures of power and exploitation. Despite moments of fleeting joy, the characters remain trapped in a cycle of banality, unable to awake from the capitalist system.</p>
<p>For now at least, we can stop buying non stick pans(I prefer ceramic pans), waterproof cloths made with Teflon(due to PFAS), and put priority of environmentalism over consumerism. Maybe also growing some vegetables at home?</p>
]]></content:encoded></item><item><title><![CDATA[An incomplete guide to Scala 3 macros and Multi-stage programming]]></title><description><![CDATA[Macros, a form of metaprogramming,or more precisely Multi-stage programming, is a way to modify code as data during compile time. Thanks to this technique, programmers now have the power close to the compiler (although you can't change the syntax arb...]]></description><link>https://blog.functorcoder.com/an-incomplete-guide-to-scala-3-macros-and-multi-stage-programming</link><guid isPermaLink="true">https://blog.functorcoder.com/an-incomplete-guide-to-scala-3-macros-and-multi-stage-programming</guid><category><![CDATA[Scala]]></category><category><![CDATA[scala3, ]]></category><category><![CDATA[Metaprogramming ]]></category><dc:creator><![CDATA[Eason Du]]></dc:creator><pubDate>Tue, 21 Feb 2023 20:26:14 GMT</pubDate><content:encoded><![CDATA[<p>Macros, a form of metaprogramming,or more precisely Multi-stage programming, is a way to modify code as data during compile time. Thanks to this technique, programmers now have the power close to the compiler (although you can't change the syntax arbitrarily), which just also transforms the AST.</p>
<p>As said in Wikipedia, it can be considered as a form of partial evaluation that performs computations at compile-time.To make more analogies, it's also similar to the scenario for embedded DSL, where full access to the AST is given and any transformations are possible.</p>
<p>Mostly based on the official guide at <a target="_blank" href="https://docs.scala-lang.org/scala3/guides/macros/index.html">https://docs.scala-lang.org/scala3/guides/macros/index.html</a> , I will divide the topic into several parts and focus on theories than giving examples, while also referencing other languages:</p>
<ul>
<li><p>conversion between code and data(AST)</p>
</li>
<li><p>operations on AST (AST for type or terms)</p>
</li>
<li><p>get information from the child node of an AST</p>
</li>
<li><p>organize code and modularity</p>
</li>
</ul>
<h3 id="heading-clarifying-terminologies">Clarifying terminologies</h3>
<ul>
<li><p>code: the runnable code as it is.</p>
</li>
<li><p>data and AST: we treat the code as data structure. It's usually a tree so we call it AST(abstract syntax tree). Quoted code is a shorthand for manually written AST.</p>
</li>
<li><p>conversion between code and data: usually called</p>
<ul>
<li><p>quote : transform code to data</p>
</li>
<li><p>splice (or eval) : evaluate data as code</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-conversion-between-code-and-data">conversion between code and data</h3>
<p>Dynamic languages like Lisp(quoted code) and javascript(tostring,eval) make it easy to toggle code and data. In Scala it's different since macros are also statically typed.</p>
<p>The data is called <strong>quoted</strong> code <code>'{ ... }</code> (like string "") and the process of converting data back to code is called <strong>splice</strong> <code>${ ... }</code>(like ${} inside string). To insert AST(Expr[T]) into <strong>quoted</strong> code <code>'{ ... }</code>, we can use the syntax $expr or ${ expr }</p>
<pre><code class="lang-scala"><span class="hljs-keyword">import</span> scala.quoted.* <span class="hljs-comment">// imports Quotes, Expr</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inspectImpl</span></span>(x: <span class="hljs-type">Expr</span>[<span class="hljs-type">Any</span>])(using <span class="hljs-type">Quotes</span>): <span class="hljs-type">Expr</span>[<span class="hljs-type">Any</span>] =
  println(x.show)
  x
inline <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inspect</span></span>(inline x: <span class="hljs-type">Any</span>): <span class="hljs-type">Any</span> = ${ inspectImpl(<span class="hljs-symbol">'x</span>) }
</code></pre>
<p><strong>inspectImpl</strong> goes from AST to AST as a normal Scala function, while <strong>inline def inspect</strong> has more magic, converting code into AST and invoking inspectImpl.</p>
<p><strong>using Quotes</strong> contains extra info about Expr[_]. Depending on the desired manipulations for AST(called Expr[_] here), other APIs like <strong>using Type[T]</strong> can also be added like below:</p>
<pre><code class="lang-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getTyped</span></span>[<span class="hljs-type">T</span>](x: <span class="hljs-type">Expr</span>[<span class="hljs-type">T</span>])(using <span class="hljs-type">Type</span>[<span class="hljs-type">T</span>], <span class="hljs-type">Quotes</span>): <span class="hljs-type">Expr</span>[<span class="hljs-type">T</span>]
</code></pre>
<p>The Expr.value, Expr.valueOrAbort, and Expr.unapply methods turns the AST Expr to the value(code) if possible.</p>
<p><strong>Idris Elaborator Reflection:</strong></p>
<p>In Idris, a dependently typed language, the directive %runElab takes data and turn it into code. The monadic do block of type <code>Elab a</code> construct the AST:</p>
<pre><code class="lang-haskell">idNat : Nat -&gt; Nat
idNat = %runElab (do intro `{{x}}
                     fill (Var `{{x}})
                     solve)
</code></pre>
<p>for more details visit <a target="_blank" href="https://docs.idris-lang.org/en/latest/elaboratorReflection/elaborator-reflection.html#elaborator-reflection">https://docs.idris-lang.org/en/latest/elaboratorReflection/elaborator-reflection.html#elaborator-reflection</a></p>
<h3 id="heading-operations-on-ast">Operations on AST</h3>
<p><strong>Expr[t] and Term</strong></p>
<p><code>Expr[T]</code> can be seen as wrappers around a <code>Term</code> for expressions, where <code>T</code> is the statically-known type of the term. Below, we use the extension method asTerm to transform an expression into a term</p>
<p><strong>Type and TypeRepr</strong></p>
<p>access type for term : <code>t.Underlying</code></p>
<pre><code class="lang-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">evalAndUse</span></span>[<span class="hljs-type">T</span>](x: <span class="hljs-type">Expr</span>[<span class="hljs-type">T</span>])(using t: <span class="hljs-type">Type</span>[<span class="hljs-type">T</span>])(using <span class="hljs-type">Quotes</span>) = '{
  <span class="hljs-keyword">val</span> x2: t.<span class="hljs-type">Underlying</span> = $x <span class="hljs-comment">// eval AST Expr[T] into x2:T</span>
}
</code></pre>
<p>Similarly, we can also see Type[T] as a wrapper over TypeRepr.</p>
<pre><code class="lang-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span></span>(x: <span class="hljs-type">Expr</span>[<span class="hljs-type">Int</span>])(using <span class="hljs-type">Quotes</span>): <span class="hljs-type">Expr</span>[<span class="hljs-type">Int</span>] =
  <span class="hljs-keyword">import</span> quotes.reflect.*
  <span class="hljs-keyword">val</span> tree: <span class="hljs-type">Term</span> = x.asTerm

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">g</span></span>[<span class="hljs-type">T</span>: <span class="hljs-type">Type</span>](using <span class="hljs-type">Quotes</span>) =
  <span class="hljs-keyword">import</span> quotes.reflect.*
  <span class="hljs-keyword">val</span> tpe: <span class="hljs-type">TypeRepr</span> = <span class="hljs-type">TypeRepr</span>.of[<span class="hljs-type">T</span>]
</code></pre>
<p>Both Terms and TypeReprs (and therefore Exprs and Types) have an associated symbol, the underlying untyped AST,exposing similar api as java's reflection:</p>
<ul>
<li><p><code>declaredFields</code> and <code>declaredMethods</code> : fields ,members and methods inside a class def</p>
</li>
<li><p><code>flags</code> allows you to check multiple properties of a symbol</p>
</li>
<li><p><code>companionClass</code> and <code>companionModule</code> jump to and from the companion object/class</p>
</li>
<li><p><code>TypeRepr.baseClasses</code> list of symbols of classes extended by a type, like sealed trait.</p>
</li>
<li><p><code>Symbol.pos</code> the position where the symbol is defined, the source code of the definition, the filename where the symbol is defined,etc</p>
</li>
</ul>
<h2 id="heading-get-extra-info-from-ast-child-node">get extra info from AST child node</h2>
<p>sometimes we want to get the type of member of a class:</p>
<pre><code class="lang-scala">boxTpe.memberType(leafSym)
</code></pre>
<p>here we need the parent type <strong>boxTpe</strong> for a child symbol <strong>leafSym.</strong></p>
<p>More details at <a target="_blank" href="https://docs.scala-lang.org/scala3/guides/macros/best-practices.html">https://docs.scala-lang.org/scala3/guides/macros/best-practices.html</a></p>
<h3 id="heading-organize-code">Organize code</h3>
<p>While working on the AST data structure, the heavy use of path dependent types for type safety adds extra complexity, so more care is needed when referring to types of the AST:</p>
<pre><code class="lang-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getDecls</span></span>(using <span class="hljs-type">Quotes</span>)(rootType: quotes.reflect.<span class="hljs-type">TypeRepr</span>) = {
    <span class="hljs-keyword">import</span> quotes.reflect.*
    <span class="hljs-keyword">val</span> typeSybs: <span class="hljs-type">Symbol</span> = rootType.typeSymbol
    <span class="hljs-keyword">val</span> decl: <span class="hljs-type">List</span>[<span class="hljs-type">Symbol</span>] = typeSybs.declarations
  }
</code></pre>
<p><strong>quotes</strong> here is not an object, but a method with implicit parameter that can be used in import, which is a huge jump from Scala 2:</p>
<pre><code class="lang-scala">transparent inline <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">quotes</span></span>(using inline q: <span class="hljs-type">Quotes</span>): q.<span class="hljs-keyword">type</span> = q
</code></pre>
<p>for keywords <strong>inline</strong> and <strong>transparent,</strong> check <a target="_blank" href="https://docs.scala-lang.org/scala3/guides/macros/inline.html">https://docs.scala-lang.org/scala3/guides/macros/inline.html</a></p>
<p>If you want to avoid this fancy <strong>inline transparent</strong> thing:</p>
<pre><code class="lang-scala">  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getDecls</span></span>(using q: <span class="hljs-type">Quotes</span>)(rootType: q.reflect.<span class="hljs-type">TypeRepr</span>) = {}
</code></pre>
<h2 id="heading-conclusion">conclusion</h2>
<p>In this guide, I provide a more theoretical perspective compared to the official guide while covering less material. Although Scala 3 macros are no longer experimental, it's still a research area and thus under-documented. When combining the new dependent typing, the interaction is nontrivial. In addition, an open problem is: to what extent can we achieve full dependent types with macros?</p>
<p>I recommend the resources below while I'm also trying to understand more about macros :</p>
<p><a target="_blank" href="https://github.com/nicolasstucki/">https://github.com/nicolasstucki/</a></p>
<p><a target="_blank" href="https://martinfriedrichberger.net/ecoop17.html">https://martinfriedrichberger.net/ecoop17.html</a></p>
]]></content:encoded></item><item><title><![CDATA[My first contribution to scala metals in 2023]]></title><description><![CDATA[what's metals
metals is the new Scala IDE with supreme support of Scala 3. Killer Features include worksheet :

that eval code on the air instantly . In my opinion, this way of combining the Haskell REPL and python's jupyter notebook is taking functi...]]></description><link>https://blog.functorcoder.com/my-first-contribution-to-scala-metals-in-2023</link><guid isPermaLink="true">https://blog.functorcoder.com/my-first-contribution-to-scala-metals-in-2023</guid><category><![CDATA[Scala]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[vscode extensions]]></category><category><![CDATA[metals]]></category><dc:creator><![CDATA[Eason Du]]></dc:creator><pubDate>Tue, 31 Jan 2023 20:41:36 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-whats-metals">what's metals</h2>
<p>metals is the new Scala IDE with supreme support of Scala 3. Killer Features include worksheet :</p>
<p><img src="https://docs.scala-lang.org/resources/images/scala3-book/metals-worksheet.png" alt /></p>
<p>that eval code on the air instantly . In my opinion, this way of combining the Haskell REPL and python's jupyter notebook is taking functional programming to the next level of productivity!</p>
<p>Another surprise is that running code like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675109800678/9380067c-dc3d-42ba-b024-ebdb82336d70.png" alt class="image--center mx-auto" /></p>
<p>takes only 1s thanks to the incremental compilation, which means it's even more convenient than writing scripts!</p>
<p>However, I find a small annoying thing: when expanding selections in comments, it's too wide so the whole file will be selected:<a target="_blank" href="https://github.com/scalameta/metals/issues/3615#issuecomment-1031257600">https://github.com/scalameta/metals/issues/3615#issuecomment-1031257600</a>,because the presentation compiler ignores comments.</p>
<h1 id="heading-into-the-metals-code">Into the metals code</h1>
<p>It's a bit complicated to navigate the metals codebase,but thanks to the help from active metals developer <a target="_blank" href="https://github.com/tgodzik">Tomasz Godzik</a> I learned the whole process of testing metals.</p>
<h1 id="heading-testing">testing</h1>
<h3 id="heading-run-test-with-sbt">run test with sbt</h3>
<p>It's convenient to test in sbt first. For my case, the relevant file for selection expansion is "SelectionRangeProvider" in subproject "cross", and the command corresponding test is in "cross/testOnly tests.pc.SelectionRangeSuite"(note the cross prefix! otherwise there'll be lots of errors). We can use println or <strong>pprint.log</strong> for debugging,which will also write in the <strong>metals.log</strong> file in .metals folder under project directory when going through manual test later.</p>
<h3 id="heading-manual-test-in-vscode">manual test in vscode</h3>
<p>After the initial success, It's time to test in the real world!</p>
<p>First, if you didn't change mtags project, then publishLocal is enough. otherwise if you changed mtags(here I only added this feature in for Scala 3 ) :</p>
<pre><code class="lang-plaintext">publishLocal;++3.2.1 mtags/publishLocal
</code></pre>
<p>"++3.2.1 mtags/publishLocal" is important, otherwise it will take long time to publish for all versions (and also generate lots of errors.. ).</p>
<p>Then, change the user config json in vscode(look for the publish version in previous steps ):</p>
<pre><code class="lang-plaintext">"metals.serverVersion": "0.11.13-SNAPSHOT"
</code></pre>
<p>Lastly, <strong>restart server</strong> in vscode command palette, and wait for metals to reload and check the metals.log .</p>
<h2 id="heading-misc">misc</h2>
<p>I recommend the below resources to get started:</p>
<p><a target="_blank" href="https://www.chris-kipp.io/blog/an-intro-to-the-scala-presentation-compiler">https://www.chris-kipp.io/blog/an-intro-to-the-scala-presentation-compiler</a></p>
<p><a target="_blank" href="https://github.com/scalameta/metals/blob/main/architecture.md">https://github.com/scalameta/metals/blob/main/architecture.md</a></p>
<p><a target="_blank" href="https://scalameta.org/metals/docs/contributors/getting-started">https://scalameta.org/metals/docs/contributors/getting-started</a></p>
<p>For those who are curious about where's the metals binary, here's the answer from <a target="_blank" href="https://github.com/scalameta/metals/issues/4920">https://github.com/scalameta/metals/issues/4920</a>:</p>
<pre><code class="lang-plaintext"> there is no binary location or anything. It simply puts together the necessary Metals classpath and runs it uses coursier.
</code></pre>
]]></content:encoded></item></channel></rss>