<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matt Hagy on Medium]]></title>
        <description><![CDATA[Stories by Matt Hagy on Medium]]></description>
        <link>https://medium.com/@matthagy?source=rss-3fe708dd30ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PDNnZBwJsojhJQT04AAXKw.jpeg</url>
            <title>Stories by Matt Hagy on Medium</title>
            <link>https://medium.com/@matthagy?source=rss-3fe708dd30ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:25:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matthagy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introducing DB From Zero]]></title>
            <link>https://medium.com/@matthagy/introducing-db-from-zero-7c0340c5b658?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c0340c5b658</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Tue, 28 Apr 2020 16:19:23 GMT</pubDate>
            <atom:updated>2020-04-28T16:19:23.337Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lear how to develop increasingly sophisticated databases from scratch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*yNfCk8-7hAj6a_nt3bCz3Q.png" /></figure><p>I’m excited to share DB From Zero (<a href="https://dbfromzero.com/">dbfromzero.com</a>) with you today! This is a new project that aims to explore different aspects and components of databases by developing increasingly sophisticated prototypes. Additionally, benchmarking is performed to quantify the impact of different design parameters and workloads, and thereby improve our intuition about databases. Today I’d like to share with you one of the recent projects.</p><h3>Log-Structured Merge-Tree for Persistent Reads and Writes</h3><p>The most recent project explores <a href="https://dbfromzero.com/log_structured_merge_tree.html">Log-Structured Merge-Tree for Persistent Reads and Writes</a>. The LSMTree is an interesting data structure that is commonly used in developing high-performance key/value stores. Projects including Google’s LevelDB and Facebook’s fork of LevelDB, RocksDB, use this data structure to support for high-volumes of random access reads and writes.</p><p>As discussed further in the <a href="https://dbfromzero.com/log_structured_merge_tree.html#Addressing_These_Challenges_Using_a_Log-Structured_Merge-Tree_LSMTree">project background section</a>, an LSMTree leverages multiple types of data containers with different properties, chiefly in-memory vs. on-disk, to achieve this high performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSwuRL9RGuNEZ-siXhWl4w.png" /><figcaption>Structure of an LSM Tree as Developed in This Project</figcaption></figure><p>Creating an LSMTree involves developing several interesting components with appropriate coordination between them to support concurrent operations. (<a href="https://dbfromzero.com/log_structured_merge_tree.html#Developing_Our_LSMTree_Storage_Engine">details</a>) In addition to development and testing, benchmarking is also performed to quantify the performance of our protoype LSMTree and we find it can achieve up to 328,400 operations/second using a high performance NVM drive and appropriate configuration and workloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*84wwITH5JB3uI9HzK5t2VA.png" /><figcaption>High-level benchmarking results of ourLSMTree</figcaption></figure><p>Additional details on benchmarking and more results can be found <a href="https://dbfromzero.com/log_structured_merge_tree.html#Analysis_of_Benchmarking_Results">here</a>.</p><h3>More to come…</h3><p>As of current, four projects have been created to explore different components of databases though hands on development. And this is just the start! More projects are in the pipeline and I’m quite excited from some of the future topics concerning transactions and serialization-level isolation.</p><p>Check back soon for new projects. Also, I’d appreciate your feedback on the current projects as well as ideas for new projects. Contact me at <a href="/service/mailto:mattthew.hagy@gmail.com">mattthew.hagy@gmail.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c0340c5b658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are millenials a sacrificial generation necessary for our advancement as a civilization?]]></title>
            <link>https://medium.com/@matthagy/are-millenials-a-sacrificial-generation-necessary-for-our-advancement-as-a-civilization-22eb5793edcf?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/22eb5793edcf</guid>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[society]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[millennials]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Sat, 13 Jul 2019 13:35:38 GMT</pubDate>
            <atom:updated>2019-07-13T13:35:38.491Z</atom:updated>
            <content:encoded><![CDATA[<h4>Millennials represent an interesting social and technological experiment in new ways of being and it’s questionable whether we’ve gotten the experiment right. What needs to be changed for the future?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GZ0c2D-h-dljItM4" /><figcaption>Photo by <a href="https://unsplash.com/@bendavisual?utm_source=medium&amp;utm_medium=referral">Benjamin Davies</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It seems every day we’re inundated with stories about the woes of millennials. They’re stressed with their jobs and personal lives and living under economically precarious situations with large debt loads. Blame has been attributed to such causes of social media and the modern economic system. We’re constantly asked to question what in our society needs to change to alleviate the problems of millennials.</p><p>In my opinion, speaking as millennial, we as a generation were simply the first to experience the unrealistic expectations created by our culture and amplified by social media. We live in a society that glorifies hedonistic experiences that can only be fueled by exceptional economic success. Luxuries once limited to the wealthy have become common expectations with everyone expecting yearly exotic vacations, designer clothes, and weekends at trendy clubs and restaurants. We believe that the middle-class lifestyle of homeownership and economic security — a lifestyle that people once struggled intensely to achieve — is a given and we must instead focus on economic and personal achievement beyond that.</p><p>We as millennials were told such was well within our grasp as long as we got a college degree. Of course, little attention was paid to the knowledge we acquired in college and the skillsets we developed. It was simply good enough to get the diploma. Millions of hapless youth believed this lie and took on heavy debt to fund their college education. Unfortunately, many pursued low-economic-value degrees and further failed to pursue their education with the vigor and intensity necessary to develop an economically-valuable skill set. Instead, they simply spent years of their youth drifting through college while racking up debt.</p><p>Their economic woes were exacerbated by college administrators that focused less on the value of their education and more on the marketing of their “college experience”. Untold sums of money were spent on such luxuries as gourmet dining, lush dorms, and recreational facilities to entice students. This money, of course, came from massive increases in college tuition, which thereby increased the level of debt that students had to shoulder to complete their “college experience.”</p><p>Millennials discovered the myth of college diploma value as they entered the workforce. They found that employers were more focused on skill sets and ability to deliver economic value. Millennials who had failed to develop employable skills in college found themselves competing for low-economic value work and were dismayed to discover how little value their expensive “college experience” provided.</p><p>This left millions of millennials in the unfortunate economic position of having a high debt load and low income. Combined with their previous unrealistic economic expectations that our culture had given them led many to a state of cognitive dissonance. Their rich economic expectations were simply incompatible with their lack of economically valuable skills and worse they were tied to large college loans. It’s not surprising that millennials are stressed and unhappy with their situation.</p><p>We can only hope that future generations will learn from the mistakes of millennials. Like millions of smokers before them, they may, unfortunately, serve primarily as a warning sign about what to avoid. Hopefully the “college degree myth” will die and instead future generations will focus on developing economically valuable skills, possibly even by avoiding college and instead attending vocational schools.</p><p>Further, hopefully, our culture will adapt to give young people more realistic goals about what they can achieve financially so that expectations are appropriate. This will likely entail changes to how we consume media, particularly social media so that we’re all given a more realistic view of how people like ourselves can live.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22eb5793edcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An implementation of the 2D Bond Fluctuation Model (BFM) for Polymer Physics]]></title>
            <link>https://medium.com/@matthagy/an-implementation-of-the-2d-bond-fluctuation-model-bfm-for-polymer-physics-69d2d85e643a?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/69d2d85e643a</guid>
            <category><![CDATA[macromolecule]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[polymer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Sun, 30 Jun 2019 15:16:35 GMT</pubDate>
            <atom:updated>2019-06-30T15:16:35.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*nG8oJfd1tTbZa6mYSwRrHQ.png" /><figcaption>Snapshot of polymer chain configuration in simulation</figcaption></figure><p>As a small programming project, I’ve implemented the Bond Fluctuation Model (BFM) for polymer physics in 2 dimensions using Java. You can find the code at <a href="https://github.com/matthagy/mc_bfm_2d">https://github.com/matthagy/mc_bfm_2d</a>.</p><p>Initially, I’ve experimented with how polymer chains diffuse through a small pore within a contained system.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTsdU-SBGFJs%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTsdU-SBGFJs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTsdU-SBGFJs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7caeda50bf2cb8c3748ed5080866b22c/href">https://medium.com/media/7caeda50bf2cb8c3748ed5080866b22c/href</a></iframe><p>A single trajectory gives the following quantitative results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Ax_Uceu2CJRp2e6Rth3PrQ.png" /></figure><p>Current results aren’t that interesting and instead just demonstrate the methods. To perform useful simulations, I’d need access to literature to learn about novel polymer systems and determine what has already been simulated. I’m hoping the methods may be useful to polymer physicists in Academia and Industry since the code is efficient and leverages the Java Virtual Machine.</p><p>Let me know if you’d like to use these methods in your work and I’ll help you get up to speed. You can contact me at <a href="/service/mailto:matthew.hagy@gmail.com">matthew.hagy@gmail.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69d2d85e643a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Investigating the long-time behavior of the two-dimensional Ising model by leveraging the Java…]]></title>
            <link>https://medium.com/@matthagy/investigating-the-long-time-behavior-of-the-two-dimensional-ising-model-by-leveraging-the-java-fa2bbc902fd9?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa2bbc902fd9</guid>
            <category><![CDATA[statistical-mechanics]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Sun, 23 Jun 2019 21:33:03 GMT</pubDate>
            <atom:updated>2019-06-23T21:33:03.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>Investigating the long-time behavior of the two-dimensional Ising model by leveraging the Java Virtual Machine (JVM)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*eFihPdzwEsgSI0b-" /></figure><h3>Summary</h3><p>Novel computational methods are developed to allow for very long time simulations of the two-dimensional Ising model with 10 billion Monte Carlo updates in each simulation. Using these methods, the time-dependent behavior of quenching from random initial states is analyzed to determine the quenching behavior. Simulations are run across a range of parameters, including the lateral size of the grid, <em>l</em>, and the pair interaction strength, <em>J</em>.</p><p>In some cases, the simulation trajectory converges to a configuration with a predominantly up spin or a predominantly down spin. There does not appear to be a simple relationship between the parameters of grid lateral size and interaction strength with the behavior of whether or not the simulation converges to a predominant state. In general, smaller lateral grid sizes results are more likely to converge to a single predominant state, which can be explained by the smaller number of spins that need to be aligned. Moderate interaction strengths are found to maximize the fraction of simulated systems that converge to a predominant state with higher interaction strengths leading the system to become arrested in a mixed state configuration.</p><h3>Background and Introduction</h3><p>The <a href="https://en.wikipedia.org/wiki/Ising_model">Ising model</a> is among the simplest models of cooperative behavior in physics and it useful for modeling such phenomena as ferromagnetism. Simpler physics models assume each individual entity operates independently of other entities within the systems. As cooperative phenomena are ubiquitous in nature, it is useful to understand the properties of such a simple model of cooperative interactions. Further, the Ising model has been related to Machine Learning models (see discussion in Quora: <a href="https://www.quora.com/How-is-the-Ising-model-related-to-machine-learning">How is the Ising model related to machine learning?</a>) and I postulate that it will be increasingly more important as researchers further work to explore and understand the structure of machine learning models.</p><p>In the present work, we consider the two-dimension Ising model, which consists of a periodic grid of cells whereby each cell interacts with its four nearest neighbors. Each cell can be in one of two states: up or down. Within this model, it is thermodynamically favorable for neighbors to have aligned spin and we can vary the pair interaction strength through model parameter <em>J</em>.</p><p>The following figure shows a small Ising model systems with a periodic grid of lateral size 25 cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*_-9-M2wjw8NUtDs1" /></figure><p>See the <a href="https://en.wikipedia.org/wiki/Ising_model">Wikipedia article on the Ising model for more details</a>. Additionally, you can experiment with the Ising model using <a href="https://matthagy.com/ising.html">this in-browser simulation</a>.</p><p>In general, there do not exist analytical solutions for the Ising model in two or more dimensions. Instead, numerical simulations are used to sample configurations of the Ising model for subsequent analysis. As in all numerical simulations, there are challenges in propagating the simulated system from an initial chosen configuration — which may be unrepresentative of the configurations of the system at thermal equilibrium — to configurations that are representative. This simulated process is hereby referred to as equilibration because we aim to generate thermodynamically likely configurations of the model.</p><p>Due to limitations of computational resources, it’s possible that we will never achieve an equilibrated configuration within the simulated system. Instead, the system will converge towards a local free energy minimum and only explore configurations near that free energy minimum. In such cases, we refer to the systems as being quenched in analogy with physical experiments whereby the system is rapidly brought to a low temperature and therefore the system gets trapped in a local free energy minimum.</p><p>To better illustrate this point, let us consider some example configurations of the two-dimensional Ising model. Conventionally, such simulations are initiated from a random initial configuration as shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*c_w4mvbCLDiS_uLe" /></figure><p>Monte Carlo methods are used to propagate the system towards thermal equilibrium, which yields more ordered states with sufficiently high pair interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*lcNMLNMu7GE5hmy5" /></figure><p>With a strong enough pair interaction, this can lead the system towards either a fully up spin or a fully down spin configuration for sufficiently small systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*zgk0Hbsj--tW5L-t" /></figure><p>In contrast, larger simulations will show regions of one spin or another. (Or at least such regions will exist at lower equilibration times with sufficiently high pair interaction strength.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*FAHSdyPcJjGNnIe_" /></figure><p>In large enough systems, it can even be challenging to visually inspect the individual regions as shown in the following lattice of lateral size 5000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*7qELSQOu9DCj8oO4" /></figure><p>Historically, physicists have studied the properties of such quenched Ising systems to better understand the role of cooperativity in physics. Considering such early work was performed over half a century ago, they had no choice but to investigate quenched systems due to the limitations of computer power.</p><p>Now, we have much more powerful computers and software engineering tools and can, therefore, push the methods further to longer equilibration times. In the present work, I leverage the <a href="https://en.wikipedia.org/wiki/Java_virtual_machine">Java Virtual Machine (JVM)</a> to develop a highly efficient simulation of the Ising model and run simulations using cloud resources. The simulations are used to explore the time-dependent equilibration/quenching of Ising model systems with varied size and pair interaction strength. You can find the code at <a href="https://github.com/matthagy/ising_java">https://github.com/matthagy/ising_java</a>.</p><h3>Results and Discussion</h3><p>Using the novel computational methods, a range lateral sizes, <em>l</em>, and pair interaction strengths, <em>J</em>, are simulated using ten billion Monte Carlo updates each. The average spin is computed throughout the simulation and the trajectory of this quantity is analyzed to ascertain the progression of equilibration.</p><p>Here’s a video of the simulation of <em>l</em>=500 and <em>J</em>=3<em>kT</em>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZcbQbHamlIA%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZcbQbHamlIA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZcbQbHamlIA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/522a0fbc12a71325767af931c7ffcfeb/href">https://medium.com/media/522a0fbc12a71325767af931c7ffcfeb/href</a></iframe><p>The trajectories of average spin for four different system sizes are shown in the following figures. For each interaction strength, 25 trajectories are collected and shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*sMbXF0MCWg_ct1DK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*Tyej95hBSucvE4eq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*GYGBg2CuexpfcIg8" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*oSIRebPxdvyFiPDK" /></figure><p>It is noteworthy that many of these trajectories appear to still be converging towards a terminal state, particularly so for the larger lateral size systems.</p><p>In inspecting these results, we can see cases where the trajectories terminate in either a fully up spin (1.0) or a fully down spin (-1.0). Other trajectories terminate with the system having a mix of up and down spins. It is noteworthy that the trajectories for <em>l</em>=500 don’t show terminal stabilization, which suggests these systems would tend towards a fully up or down terminal state if simulated for longer.</p><p>Next, trajectories are classified as either being in a configuration with a single predominant state or being in a mixed configuration. Specifically, the average spin of the last 100 configurations is computed for each simulation and if the mean spin is greater than 0.95 or less than -0.95, then the system is classified as being in a predominant state. The relationship between pair interaction strength and system lateral size on this behavior is shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*CFMeENEV7x_mBgRe" /></figure><p>It is noteworthy that a non-monotonic trend is observed with respect to pair interaction strength for smaller lateral sizes of 25 and 50. This suggests that stronger interactions make the system more likely to get stuck in local free energy minima.</p><h3>Conclusion</h3><p>This work demonstrates the power of modern computational technologies for performing long-time simulations. Further, the results show that even 10 billion Monte Carlo updates are insufficient for convergence of the quenching process. Nonetheless, the preliminary results show that such simulations can converge to a predominantly up or predominantly down configuration and the conditions under which this occurs is complex with respect to lateral grid size and pair interaction strength.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2bbc902fd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing simple chemical physics simulations that run in the browser]]></title>
            <link>https://medium.com/@matthagy/developing-simple-chemical-physics-simulations-that-run-in-the-browser-fa1665879c78?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1665879c78</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[chemistry]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 23:15:33 GMT</pubDate>
            <atom:updated>2019-04-11T23:55:01.257Z</atom:updated>
            <content:encoded><![CDATA[<h4>I’ve been experimenting with using Scala.js to create educational simulations and would like to share the results and what I’ve learned.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttZSOdAsB-SIrEO4xo1OQg.png" /><figcaption>Simulation snapshots</figcaption></figure><p>I’m a software engineer with a background in chemical physics and I’m excited to experiment with developing free online educational resources that teach chemical physics, particularly simulation. To that end, I’ve been exploring Scala.js and assorted JavaScript libraries. Here are some of the preliminary resources I’ve developed.</p><ul><li><a href="https://matthagy.com/random_walk.html">Random Walk in a Periodic Box</a></li><li><a href="https://matthagy.com/soft_spheres.html">Simulation of Soft Spheres in a Periodic Box</a></li><li><a href="https://matthagy.com/polymers.html">Simulation of Polymer Chains</a></li></ul><p>All the initial rough code is available at <a href="https://github.com/matthagy/chem_prog_exp">github.com/matthagy/chem_prog_exp</a>. I apologize for the current lack of documentation.</p><p>Chiefly, I’m using <a href="https://www.scala-js.org/">Scala.js</a>, which is a framework for writing Scala code that compiles to JavaScript so that we can write Scala that runs in the browser. I like how this allows us to leverage the full power of Scala for developing complex simulations using a clear and concise language with a functional (i.e., mathematical) formalization.</p><p>While I don’t know enough JavaScript (and know nothing about TypeScript) to fully comment on the pros/cons of Scala.js, I’ve found Scala.js to be a great language/framework for writing simulations, visualizations, and analyses that run in the browser. You can learn more about my general thoughts on Scala in my post, <a href="https://medium.com/@matthagy/initial-impressions-of-scala-from-a-java-and-python-data-engineer-c8e2038aca3d">Initial impressions of Scala from a Java and Python data engineer</a>.</p><p>Beyond Scala.js, I’ve also explored several JavaScript libraries related to developing simulations. <a href="https://threejs.org/">Three.js</a> has proven to be an excellent 3D rendering library and it has made it easy for me to develop simulation visualizations. <a href="https://plot.ly/javascript/">Plotly.js</a> makes the development of dynamic and interactive plots effortless; I’ve literally spent less than 15 minutes learning about this library. Lastly, I’ve found the <a href="https://ace.c9.io/">Ace</a> editor to be a robust, browser-based editor that allows me to represent simulation configuration in user-editable JavaScript.</p><p>Overall, I’m excited about how easy it has been to develop these simple, rough proof-of-concept simulations. I’m looking forward to developing more interactive and sophisticated simulations in the future as a hobby project. I’m also starting to brush up on my chemical physics knowledge so that I can make these into better educational resources.</p><p>I’m even starting to think about how some of these resources could be useful to practitioners; i.e., academic and industrial researchers and engineers. To that end, we’ll need the code to run outside of the browser and I think that should be straightforward if everything is in Scala since Scala primarily runs on the JVM. It might be cool to provide a simple, browser-based interface into simulations that run in the cloud. If I do this, it would be within a non-profit organization since I don’t think there’s much potential for profit margins.</p><p>Let me know what you think about this preliminary work and any ideas you have for how this work could evolve. I’m also certainly open to collaboration. You can reach me at <a href="/service/mailto:matthew.hagy@gmail.com">matthew.hagy@gmail.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1665879c78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Eternal Debate: Code or Documentation for Education?]]></title>
            <link>https://medium.com/@matthagy/the-eternal-debate-code-or-documentation-for-education-455b07b4510a?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/455b07b4510a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[perl]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 22:04:28 GMT</pubDate>
            <atom:updated>2019-03-27T23:37:39.159Z</atom:updated>
            <content:encoded><![CDATA[<h4>IMO, doesn’t matter if we’re all spending more time reading and learning… All I care about is helping Chemists get better at developing and applying software.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wl1r123vWGXA09se" /><figcaption>Photo by <a href="https://unsplash.com/@gaellemarcel?utm_source=medium&amp;utm_medium=referral">Gaelle Marcel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I used to wonder why it was so <strong>frustrating</strong> to use previous generation tools to start solving new problems. E.g., using Perl/HTML to implement a website in the late 90s. All I learned from that was Python 2.3 and it took several years before I finally got back to coding in a lame undergrad research job. Cool that all of us budding Engineers got some real management experience in our minimum wage jobs while we wasted time in high school. Otherwise, we might all be writing Scala code like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*N97DYQROM5nAjUIa5PQOsA.png" /></figure><p><em>(Yep, you’re gonna have to read between the lines here to figure out my message about what matters in the evolution of technology education. Trust me, it’s more fun that way. And yes, I’m combining stories from many people I’ve known over the years. Even left in some typos to make it clear this is a rush job.)</em></p><p>Now I think I realize that the frustration of working with weak technology was a little <strong>exciting</strong> and actually made me want to learn more, but it was always unclear what we all needed to learn as a professional community of Engineers, Researchers, and Educators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DUI6XamCQ4DuyzNu" /><figcaption>Photo by <a href="https://unsplash.com/@thutra0803?utm_source=medium&amp;utm_medium=referral">Tra Nguyen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hence, in this blog post, I’m gonna explore some ideas of advancing technology education in all disciplines. Long term, hoping I can start further applying some of these ideas in Chemistry education at the primary school level by better leveraging code and documentation in new code-based teaching tools. Some of these products may even be useful to practitioners. I label these tools as purely digital microscopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YQaz41LczRmjU7Us" /><figcaption>Photo by <a href="https://unsplash.com/@cheaousa?utm_source=medium&amp;utm_medium=referral">Ousa Chea</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here’s my lame PoC. <a href="http://matthagy.github.io/PyLJFluid/">http://matthagy.github.io/PyLJFluid/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYtSB6_J2l1dDlMU5OB5JA.png" /></figure><p>If we want people to learn to apply these tools, then we need to give them a bit of an incentive, even if it’s just really understanding how to build the next generation of better software while earning a living. Might seem a little lame if we’re always constantly refactoring code, but if we’re solving problems that matter at the same time, then maybe it’s an arbitrage that we can all learn to accept.</p><p>Personally, I hope one day to be just another lame PostDoc advancing this work by writing and deploying some grants. Hope to write code up until my eternal retirement.</p><p>Some of us, myself included, may just need to learn the appropriate way to manage the frustration of this constant evolution. E.g., everyone who thought Data Science was a terminal career path. As a Ph.D., trust me, you don’t get tenure in corporate America. You may even get something that looks like the opposite: a job that is hard to quit. You gotta keep evolving and adapting or you’ll be outcompeted by the next generation of professionals. E.g., Lawyers in the 90s.</p><p><em>IMO: It is lucky that I’m learning that writing just happens to be a great way to learn and let off a little bit of steam. As is serving as an Editor for any publication. I’m certain many OSS GitHub projects would love a new maintenance team?</em></p><p>Over time, the frustration may slowly evolve into motivation to help the organizations get more accomplished because the organizations supporting them are so important and people can be highly fluid between organizations when they choose to.</p><p>But then the hard challenge becomes finding out the appropriate arbitrage to deploy our limited resources. After all, even Bill Gates has more money than he knows what to do with. Wouldn’t it be a really lame way for Jeff Bezos to give away all of his excess money if all he had to do was write Bill Gates a check? After all, I heard Jeff Bezos says that he already said thanks to Bill Gates when Jeff took over the title. Thankfully the top title keeps getting lamer and lamer, at least in my personal opinion. And no one seems to know what to do with the fucking money! Even Google wants us to write them some grants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQWegoDIlfNmnGoi-4va3Q.png" /></figure><p>Is it possible then that the story of how Jeff Bezos started Amazon after quitting his VP-level role at DESCO (a hedge fund) is just another historical rewriting? Or maybe that was just the only way to set up the appropriate arbitrage to get the best price for important books that some of his associates really needed, including my father and me. And later the academic research teams I’ve served in over nine years. We are all truly grateful for Amazon.</p><p>After all, do we even remember when the first Python manual was published? I wonder how long it took to write? Must’ve been expensive to get someone to do that dirty job and further the number of customers was highly limited. I remember paying $40+ for important books on Amazon back in the 90s and it always seemed like amazing arbitrage. Glad that many of these books are now free. Could we write some more that include interactive, OSS code?</p><p>And there could be an infinite number of Scala books since Scala includes macros. Hence, we can always extend Scala into something more unnecessarily complex to learn. Why with any luck, Scala may even become the next Perl. Who wouldn’t love maintaining a Perl/HTML website for their entire career? Probably someone just looking for something more complex to develop, with the minimal amount of discipline. Instead, we’ll need to write new programming languages for chemistry. I’m working on teaching the basics.</p><ol><li><a href="https://medium.com/@matthagy/quickly-learning-the-basics-of-scala-through-structure-and-interpretation-of-computer-programs-ed5bfa90e8dc">Quickly learning the basics of Scala through Structure and Interpretation of Computer Programs examples</a></li><li><a href="https://medium.com/@matthagy/a-brief-tour-of-lists-in-scala-and-algorithmically-processing-them-in-sicp-exercises-935ff4d77775">A brief tour of lists in Scala and algorithmically processing them in SICP exercises</a></li><li><a href="https://medium.com/@matthagy/interactively-exploring-reddit-posts-using-basic-scala-in-your-browsers-f394843069de">Interactively exploring Reddit posts using basic Scala in your browser</a></li></ol><p><em>(Yep, you’re gonna have to take some time to learn anything from this stream of consciousness.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SDalGiEQFOqYWvaF" /><figcaption>Photo by <a href="https://unsplash.com/@dbmartin00?utm_source=medium&amp;utm_medium=referral">David Brooke Martin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>More to come later…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=455b07b4510a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What does a Principal Data Scientist look like in 2025?]]></title>
            <link>https://medium.com/data-science/what-does-a-principal-data-scientist-look-like-in-2025-545a571ec89f?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/545a571ec89f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Wed, 06 Mar 2019 16:01:37 GMT</pubDate>
            <atom:updated>2019-06-08T13:56:15.370Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sure is an exciting time to be in data science! Particularly so with the magic of machine learning. Why it’s so exciting that it’s attracting millions of highly intelligent and deeply trained future professionals. Hence, I think we should reflect on the future of data science. Here are my predictions…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsgDatJBZ15kNeF1gGhbDA.jpeg" /></figure><p>It’s 2025 and one of the most coveted careers pinnacles in large corporations is Principal Data Scientist (PDS). It should be clear from the title that this is an elite role. Some innovative companies have even started using the title “Senior Data Manager” to attract the right candidates in 2025.</p><p>PDSs are charged with the mission of leveraging their strengths in ML to solve the hardest artificial intelligence problems facing tech companies. For example, social media companies are still searching for the perfect autonomous content moderating technologies. And only PDSs can help them.</p><p>PDSs are uniquely suited to solve such problems due to their advanced training. For example, PDSs advancing the state-of-the-art in comment moderations have each completed a Ph.D. in digital anthropological communication with ML applications.</p><p>In their training, they’ve each received five days of in-person lectures on such complex topics as meme quality and whether or not a comment counts as a hateful or if it was just meant ironically. Further, in the second week of their boot camp, they each complete an independent ML-research project and write a three-paragraph thesis. On the last day, everyone in the class gets to defend their thesis and pick up their Ph.D. certificate.</p><p>In 2019, we might struggle to see how one could complete such an advanced ML project in only one week despite no prior experience. Isn’t ML still hard? Well, of course, it’s still hard! That’s why we need PDSs. And they’re certainly experts in ML. They’ve each read the 80-page Machine Learning as a Service (MLaaS) manual provided by Google Cloud Platform (GCP). (Don’t be intimidated by this long book, it’s only a picture book. Or, as one might say, a slide deck.)</p><p>Hence, each PDS has mastered this technology and therefore knows how to click through the ML wizard — always accepting the default settings — and finally, click the big “Run Machine Learning!!!” button. (Yes, Google added the exclamation points in response to overwhelming customer feedback.)</p><p>But their expertise in ML alone are insufficient for them to solve such challenging artificial intelligence problems. For as every PDS knows, ML applied to poorly prepared data is useless. Hence, PDSs also need deep expertise in their problem domain so as to properly prepare their data. Their specialized graduate coursework trains them accordingly.</p><p>Further, PDSs are experts at leveraging data microscopes. These are advanced technologies that allow their highly-technical users to explore the structure of data and annotate data elements. For example, a PDS specialized in comment moderation knows how to discover flagged comments by clicking the appropriate tab in their data microscope. They then apply their professional judgment in annotating individual comments with the right labels. After roughly a week, they’ve prepared sufficient data (averaging 2k comments/day) to start applying state-of-the-art ML methods. In 2025, running MLaaS on GCP takes on average 4 minutes and costs $7.21.</p><p>A newly minted PDS Ph.D. may think this is where the project ends. But as any veteran knows, no ML solution is perfect on the first try. Instead, real-world data science is an iterative loop whereby we constantly improve the methods through user feedback. One might call this “organic reinforcement learning” whereby users of a platform let the PDS know where the AI methods are currently failing by contesting ML-predicted labels.</p><p>In an attempt to improve the ML performance, some junior PDSs may be tempted to play with the MLaaS settings in GCP — thinking they can do ML better than Google — but they soon find this to be in vain. For our God, Google, is omnipotent in the domain of ML. Instead, the problem is always insufficient prepared data. Back to the microscope!</p><p>And remember, don’t hit that “Run Machine Learning!!!” button more than once a week; it costs us real money.</p><p>As you might imagine, PDSs are well-compensated professionals in 2025. They average $18/hr and the top contractors can make north of $32/hr. These top professionals are chiefly distinguished by their emotional fortitude in such soul-racking domains as identifying child pornography. Hence, the big bucks. Like dentists before them, these professionals exhibit a statistically-significant higher rate of depression. Too bad they don’t know statistics.</p><p>Look out for part II where we consider how large teams of PDSs are coordinated to collaboratively tackle massive artificial intelligence problems in 2025. Spoiler: coordinating and managing PDSs is such a crummy job that only computers are willing to do it.</p><p><em>For a more serious discourse on the impact of Machine Learning as a Service on the data science field see “</em><a href="https://liveramp.com/engineering/opinion-our-exciting-journey-as-data-scientists-onwards-to-higher-levels-of-abstraction/"><em>Our Exciting Journey as Data Scientists Onwards to Higher Levels of Abstraction</em></a><em>.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545a571ec89f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-does-a-principal-data-scientist-look-like-in-2025-545a571ec89f">What does a Principal Data Scientist look like in 2025?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing scalaps: Scala-inspired data structures for Python]]></title>
            <link>https://medium.com/@matthagy/introducing-scalaps-scala-inspired-data-structures-for-python-53f3afc8696?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/53f3afc8696</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 04:38:53 GMT</pubDate>
            <atom:updated>2019-02-28T20:50:12.353Z</atom:updated>
            <content:encoded><![CDATA[<h4>A functional, object-oriented approach for working with sequences and collections. Also similar to Spark RDDs and Java Streams. Hope you find they simplify your code by providing a plethora of common algorithms for working with sequences and collections.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEzGGiFwTbHk9g2WxlhshA.png" /><figcaption>An example of using scalps to analyze Reddit posts</figcaption></figure><p>I’ve found that working on collections of elements by applying functions through well-defined algorithms (e.g., map, filter, and reduce) to greatly simplify my code and remove many sources of errors. Therefore I was delighted to discover that Scala really pushes this to the next level by introducing a plethora of built-in algorithms on data structures. These concepts share some similarities to Spark RDDs and Java Streams, but I find the Scala approach simpler and more elegant.</p><p>As I return to data analysis and machine learning with Python, I’ve found it helpful to port these concepts to Python in a new library, <a href="https://pypi.org/project/scalaps/">scalaps</a>. You can find the code at <a href="https://github.com/matthagy/scalaps">github.com/matthagy/scalaps</a>.</p><p>In this article, we’ll walk through a few examples of how scalaps can simplify our code. Let’s start with this basic, contrived example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6763cac879b680abb02e9b8d2ae82d6d/href">https://medium.com/media/6763cac879b680abb02e9b8d2ae82d6d/href</a></iframe><p>ScSeq is a wrapper around any sequence and it provides numerous methods for operating on its input sequence. Many of these methods return another ScSeq instance.</p><p>Rather than analyze the contrived example, let’s walk through a more realistic <a href="https://github.com/matthagy/scalaps/blob/master/examples/analyze_reddit_posts.py">example of analyzing Reddit posts using scalaps</a>. For background, we have a sample of Reddit posts in the following CSV format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/890cd972be99d074fb40a5914a33114c/href">https://medium.com/media/890cd972be99d074fb40a5914a33114c/href</a></iframe><p>We start by accessing the data and parsing it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28feeae527b248efaf9b9aafec8595e0/href">https://medium.com/media/28feeae527b248efaf9b9aafec8595e0/href</a></iframe><p>You can see the following ScSeq methods used in this example.</p><ul><li><strong>map(func): </strong>map a function across the current sequence to create another sequence</li><li><strong>to_frozen_list()</strong>: create a frozen, realized list of the current sequence as implemented in ScFrozenList.</li><li><strong>take(n)</strong>: return a sequence that will have at most the first n elements of the current sequence</li><li><strong>for_each(func)</strong>: call the function on every element of the sequence in order</li></ul><p>Here’s the equivalent conventional Python for these operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27b462156bacd3f62d5dbb5fada52a7c/href">https://medium.com/media/27b462156bacd3f62d5dbb5fada52a7c/href</a></iframe><p>Which is perfectly reasonable Python and we haven’t yet seen the strength of scalaps.</p><p>Next, let’s look at counting the number of elements that match a criteria.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8b08fb80e250d01b09f851be12bd95a/href">https://medium.com/media/c8b08fb80e250d01b09f851be12bd95a/href</a></iframe><p>This introduces two more ScSeq methods.</p><ul><li><strong>filter(func)</strong>: select elements that match a criteria</li><li><strong>count()</strong>: count the number of elements in the sequence</li></ul><p>Note that filter is lazy. It doesn’t evaluate to a realized collection but instead, is a lazily computed sequence. The same is true for other methods such as map. In fact, an entire ScSeq can be a lazy sequence when sourced from an appropriate lazy source. E.g., readings lines from a file.</p><p>In contrast, count is a sink. It realizes each element of the sequence through a chain of operations starting from the source. count is a constant memory sink and can, therefore, consume massive lazy sequences. Other sinks include to_fozen_list, which realizes the sequence into an immutable list of type ScFrozenList.</p><p>Once a ScSeq has been realized, it cannot run again. Instead, we can reconstruct the sequence to realize it again. It can be useful to have functions that build a sequence from passed-in source(s) so that we can easily reconstruct the sequence as needed. E.g.,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cbcdca0ad160d2a7008d2ea768c4544/href">https://medium.com/media/3cbcdca0ad160d2a7008d2ea768c4544/href</a></iframe><p>Returning to the Reddit post example, let’s compute the most popular subreddits in this sample of posts. This is accomplished with the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a4595cfbdd1010316cf459884303509/href">https://medium.com/media/1a4595cfbdd1010316cf459884303509/href</a></iframe><p>This introduces a few new scalaps concepts. First, we’re passing a string to map. This is interpreted as “select the attribute of that name for each element”. Similarly, integers are interpreted as integer item lookups in a collection.</p><p>Next, we use the method value_counts(). This sink computes an ScDict in which each key is an element from the sequence and the value is the number of times the key occurred. ScDict is an augmented Python dictionary that includes functionality such as returning ScSeqs for keys(), values(), and items(). In the example, we use the items() method to generate a sequence of key/value tuples.</p><p>The sequence is then sorted into a ScList using sort_by(key). Note, we’re using the integer 1 as the key so as to select the second element, the count, of each tuple. Hence, the list is now sorted by the number of posts.</p><p>reverse() is used to generate a ScSeq that is in the reversed order so that the posts are ordered by descending score. take(n) is used with n=5 to select the first five posts. Lastly, they’re printed through forach(print).</p><p>I find this to be a more elegant description of this algorithm than the comparable Python. Do you agree? If not, in your opinion, what would the comparable Python be and why is it more elegant? Let me know in the comment section below.</p><p>Lastly, let me leave you with a more sophisticated use of scalaps that computes the frequency of title words in each subreddit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29a2699a0884d83814756973fdc7dcd6/href">https://medium.com/media/29a2699a0884d83814756973fdc7dcd6/href</a></iframe><p>I won’t explain the full example. Instead, see if you can reason through what the code is doing based upon the naming of the methods and the names of the functions used with them.</p><p>I will point out two interesting methods.</p><ul><li><strong>flat_map(func)</strong>: takes a function that returns sequence for each element in the original sequence. Each returned sequence is expanded, in order, within a returned ScSeq.</li><li><strong>group_by(func)</strong>: construct an ScDict where the keys are computed by func and each value is an ScList with all the elements that have that same key.</li></ul><p>In reading through this example, what are you’re thoughts on the legibility of the Python code with scalaps? I personally find this approach easier to reason through relative to conventional Python. Further, I’ve used such a style in Scala, Java, and (Py)Spark so as to structure my code as applying functions to collections using built-in algorithms. I’ve come to find this approach simpler, more legible, and less error prone relative to conventional imperative programming.</p><p>Thanks for considering scalaps! I hope it can help simplify your code, improve the readability, and eliminate errors. Let me know what you think in the comment section below.</p><p>Again, you can find the code at <a href="https://github.com/matthagy/scalaps">https://github.com/matthagy/scalaps</a>. It is a nascent library and very much a work in progress. E.g., it needs tests and I’ll develop them once I get some feedback on the API. PR’s are also welcome.</p><p>These examples were derived from a Scala learning resource, <a href="https://towardsdatascience.com/interactively-exploring-reddit-posts-using-basic-scala-in-your-browsers-f394843069de">Interactively exploring Reddit posts using basic Scala in your browser</a>. Check it out if you’d like to learn more about the elegant and powerful programming language, Scala.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53f3afc8696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interactively exploring Reddit posts using basic Scala in your browser]]></title>
            <link>https://medium.com/data-science/interactively-exploring-reddit-posts-using-basic-scala-in-your-browsers-f394843069de?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/f394843069de</guid>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 18:28:27 GMT</pubDate>
            <atom:updated>2019-02-27T11:08:18.434Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article continues our journey through Scala. In these exercises, you’ll get to analyze actual Reddit posts using snippets of basic Scala code that you write and run in your browser. You may even discover some surprising behavior of Redditors.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vD6PNR9OdY8EIlItOo2wOg.jpeg" /></figure><p>This is part three of our tour through Scala. If you’re just arriving and would like to start at the beginning, checkout <a href="https://medium.com/@matthagy/quickly-learning-the-basics-of-scala-through-structure-and-interpretation-of-computer-programs-ed5bfa90e8dc">Quickly learning the basics of Scala through Structure and Interpretation of Computer Programs examples</a>.</p><p>Today we’re going to do some novel programming exercises based around actual Reddit data. I’ve prepared a random sample of roughly ten thousand posts from the month of October 2018 for us to interactively explore by writing basic Scala in widgets within this article.</p><p>Here’s a preview of some of the Scala we’ll be writing to analyze Reddit posts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/926933276cf07b603ecbb304341b4d10/href">https://medium.com/media/926933276cf07b603ecbb304341b4d10/href</a></iframe><p>Let’s dive right in and figure out how to access this data, run computations on it, and thereby analyze Redditors by writing and running Scala code directly in our browser.</p><p>The following code fetches the Reddit post data from a web server and shows the first few lines of the Reddit data. There are some new Scala concepts in the code that we won’t need to understand today since we’ll just be using the code to fetch the Reddit data. Instead, we’ll focus on the code we write to explore the data.</p><p>Aside: This is a generally cool feature of programming: we can commonly use functions in libraries developed by other programmers to perform computation for us, even when we don’t understand the details of the code in the library. Professional software engineers commonly use libraries in their work specifically so they don’t have to learn the details of how to solve a programming problem that someone else has already solved.</p><p>Hit “Run” on the following widget to run the code and see the results.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fscalafiddle.io%2Fsf%2FVMDY992%2F2&amp;src=https%3A%2F%2Fembed.scalafiddle.io%2Fembed%3Fsfid%3DVMDY992%2F2%26passive%26&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=scalafiddle" width="960" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a89310c2c23a0971d871fe1f1db94d/href">https://medium.com/media/c1a89310c2c23a0971d871fe1f1db94d/href</a></iframe><p>(Note, you can click “Edit on ScalaFiddle” on any ScalaFiddle widget in this article if you find the ScalaFiddle widget too horizontally compressed in the embedded form. In such cases, you’ll find the presentation on the ScalaFiddle website to be more readable.)</p><p>Pretty cool how easily we can access this interesting data, right? Now let’s figure out how to explore the data and compute novel results that provide interesting insights into Redditors.</p><p>We receive the data as one very long string. You can modify the Scala code in the previous ScalaFiddle widget to call.length on the string and print the number of characters. I.e., we’ll modify our anonymous function at the bottom of the code to have the following form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a7c0717ffd6403a002717199f1dbd6c/href">https://medium.com/media/4a7c0717ffd6403a002717199f1dbd6c/href</a></iframe><p>Run that and you’ll see that the data string consists of just under a million characters. Hence, we have some serious data to process here.</p><p>Let’s look at the sample again to see how we’ll want to process this long string.</p><pre>MarioAI,nicolasrene,recreation of Mario facing left since i havent got the original picture not the real thing but he did face left once in 1-2...,1<br>u_seksualios,seksualios,Seksuali gundanti ištvirkėlė Alektra Blue juodais drabužiais,1<br>Cuphead,[deleted],Just finished Cuphead in an hour and fifteen minutes.,0<br>videos,lonemonk,Trump On The Traps - Calvin Dick (2017),1 CryptoCurrency,Pseudoname87,Why does binance show a different price than other sites?,1</pre><p>This text data is in comma-separated value (CSV) format. Conventionally such data is shown as a table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/890cd972be99d074fb40a5914a33114c/href">https://medium.com/media/890cd972be99d074fb40a5914a33114c/href</a></iframe><p>We can see that each single line of the file corresponds to a single post. Hence, first, we’ll want to break this string up by lines to access the individual line for each post. We can split a string into substrings — based on a specific splitting character — using the string method split. To split into lines, we’ll use the newline character &quot;\n&quot; as the splitting character.</p><p>Lastly, we’ll convert the return value of split to a list using toList and show the number of lines. You can go back to the ScalaFiddle widget and modify our processing code to be as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/983180418dc95ff429bfb6061bb2967d/href">https://medium.com/media/983180418dc95ff429bfb6061bb2967d/href</a></iframe><p>The results show that we have roughly 11,000 Reddit posts in this data.</p><p>Now we still have some more work to do in preparing our data for programmatic exploration because each Reddit submissions contains multiple attributes. Going back to the sample, we see that each line is a comma-separated string of values for each post. In order, the attributes are:</p><ul><li><strong>subreddit</strong>: Subreddit to which post was submitted</li><li><strong>author</strong>: The user account who posted the submission</li><li><strong>title</strong>: The title of the post</li><li><strong>score</strong>: The voting score of the submission at the time the data was pulled</li></ul><p>We’ll again use String.split to access the individual fields of each post, this time using &quot;,&quot; as the splitting character.</p><p>We want a way to organize together all of the different attributes of a single post and for that, we can create a Scala class. At a high level, a class just allow us to organize together related data elements like the different attributes of a Reddit post. Here’s how we define a class for this data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24d783ed382a6734baab30596ce22572/href">https://medium.com/media/24d783ed382a6734baab30596ce22572/href</a></iframe><p>Here’s an example of how we can use the Post class. Modify the code as you like to get a feel for ourPost data type.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fscalafiddle.io%2Fsf%2FBviWyyZ%2F1&amp;src=https%3A%2F%2Fembed.scalafiddle.io%2Fembed%3Fsfid%3DBviWyyZ%2F1%26passive%26&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=scalafiddle" width="960" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ef2517f06b42ede7b0b6632ad42eb9a/href">https://medium.com/media/0ef2517f06b42ede7b0b6632ad42eb9a/href</a></iframe><p>We’ll cover classes in more detail in the future. For now, it’s good enough to know that this class defines a new data type to represent Reddit posts, with each post having four attributes: subreddit, author, title, and score.</p><p>Let’s now modify our processing code to parse our raw data into a list of posts. I.e., create aList[Post].</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fscalafiddle.io%2Fsf%2FRIQJQoS%2F5&amp;src=https%3A%2F%2Fembed.scalafiddle.io%2Fembed%3Fsfid%3DRIQJQoS%2F5%26passive%26&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=scalafiddle" width="960" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e145812ff9477681d6dcddf691ee8059/href">https://medium.com/media/e145812ff9477681d6dcddf691ee8059/href</a></iframe><p>Now we have a list of posts in val posts: List[Post]. So let’s start exploring this Reddit post data!</p><p>First, let’s count the number of posts for a single subreddit. You can add the following code to our processor function in the previous ScalaFiddle widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cf931c6b338fd4c7df8d4e0e448ead6/href">https://medium.com/media/0cf931c6b338fd4c7df8d4e0e448ead6/href</a></iframe><p>Here we’re using the filter method ofList to create a new list that just contains the posts that are from the subreddit “AskReddit”. In general, we can use filter with any function we write to select elements of a List and thereby create a new List that just contains those elements of interest.</p><p>Feel free to modify the code to count the number of posts in our sample for any subreddit you’re interested in.</p><p>Building off that exercise, let’s compute the number of posts for every single subreddit. In this computation, we’ll build a data structure that associates each subreddit with its posts count. This will require us to introduce a new Scala data structure called Map.</p><p>Map[K, V] is an association between keys of type K to values of type V. In this exercise, we’ll be building a Map[String, Int] to associate subreddit name to count of posts. Here are some examples of how we can work with such a map.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fscalafiddle.io%2Fsf%2Feb3BJ3S%2F1&amp;src=https%3A%2F%2Fembed.scalafiddle.io%2Fembed%3Fsfid%3Deb3BJ3S%2F1%26passive%26&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=scalafiddle" width="960" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/89a2815ee127e8119b3202c4f7763e73/href">https://medium.com/media/89a2815ee127e8119b3202c4f7763e73/href</a></iframe><p>Can you add code to create forthMap that adds the key &quot;new key&quot; with a value of 12 to our val map: Map[String, Int]?</p><p>For people familiar with other programming languages, you may be surprised to see that Map.updated returns another newMap. In general, Scala encourages us to use immutable data structures and therefore we avoid modifying anything in place. Instead, we create new data structures to represent the results of any change. Scala does some really clever things behind the scenes to make such updates efficient in both processing time and memory usage.</p><p>Note that Map[K, V].get(key) returns an Option[V]. Option is used to account for the fact that it’s possible we don’t have a value for the given key. Option is a general data type that can take two forms, Some(value) and None. Some(value) denotes that we do have a value for the key and we can access that value through Some.get. Whereas None denotes that there was no value for the key.</p><p>Option has a useful method getOrElse(alterantive). When called on Some it returns the value contained in Someand ignores alterantive. Whereas None.getOrElse(alternative) returns the value of alternative. We’ll use this method in our code to replace None with zero when we fetch the count for a subreddit that we currently don’t yet have a count for.</p><p>Using Map, here is how we can compute the number of posts for each subreddit.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fscalafiddle.io%2Fsf%2FUgZ4Dfg%2F2&amp;src=https%3A%2F%2Fembed.scalafiddle.io%2Fembed%3Fsfid%3DUgZ4Dfg%2F2%26passive%26&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=scalafiddle" width="960" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c75f27ec5039c66c7c052a6cd96964ff/href">https://medium.com/media/c75f27ec5039c66c7c052a6cd96964ff/href</a></iframe><p>Note how we’re using foldLeft, a variant of fold, to process each post and increment the count for the corresponding subreddit in the map. You may recall that fold is used to aggregate all values in a list down to a single value. In this case, the final value is aMap[String, Int] that associates subreddits to their count of posts.</p><p>A quicker refresher on fold functions: We call foldLeft with our initial value of aggregation and our folding function. fold calls our folding function for every element in the list. In each call, the folding function also receives the current value of the aggregation. Our function returns the updated value of the aggregate that incorporates the list element. The fold functions return the final value of aggregation after processing every element in the list using our folding function.</p><p>Spend some time reviewing this code to see if you can reason through how we’re computing the number of posts for each subreddit. As an exercise, can you modify this example code to instead count the number of posts for each user?</p><p>While the current results are nice, we’re more interested in knowing the results for the top subreddits; i.e., those with the most posts in this sample of Reddit posts. To that end, we’ll need a way to order the subreddits by the number of posts so that we can select the top few subreddits to show. In computer science terminology, such a process is referred to as sorting.</p><p>You can add the following code to the preceding example to sort the subreddits by post count and then show the top 10 in this sample of Reddit posts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4ac308ddf8bd869fba6ce6d192f3b5/href">https://medium.com/media/ce4ac308ddf8bd869fba6ce6d192f3b5/href</a></iframe><p>There are a few new things going on here. First, we’re converting subredditCount from Map[String, Int] to List[(String, Int)] using the Map.toList method. This introduces a new concept called tuples in that (String, Int) is the type for a length-two tuple where the first element is a string and the second element is an integer.</p><p>Tuples are a general data type in Scala that can be used to represent fixed length collections of elements whereby each position has a fixed type. E.g., (String, String, String, int) is a length-four tuple. We could’ve used this tuple type instead of the class Post to represent the data in a single Reddit post.</p><p>In general, classes are a more legible way to group together related elements. Tuples can be useful in some cases, particularly in cases where we want to write generic algorithms that use placeholder types. This is the case in wanting a general method to convert a Map[K, V] in a list of associated pairs, List[(K, V)].</p><p>Next, we’re using the method sortBy to sort our list of tuples. The method takes a function that computes a ranking score for each element of the list. The elements of the list are sorted by rank and a new list is returned by sortBy in which the elements are ordered. You can see that our ranking function just fetches the count for each subreddit by accessing the second element of the tuple, t._2.</p><p>The results for our sample of Reddit posts are as follows.</p><pre>(AskReddit,254)<br>(AutoNewspaper,214)<br>(The_Donald,84)<br>(CryptoCurrency,71)<br>(SteamTradingCards,69)<br>(RocketLeagueExchange,65)<br>(newsbotbot,65)<br>(videos,64)<br>(GlobalOffensiveTrade,59)<br>(PewdiepieSubmissions,58)</pre><p>In thinking about the numbers, we should remember that this is a small random sample of all Reddit posts so the counts are going to be much smaller than the full number of posts. Our sample is 0.1% sample of all Reddit posts in October 2018, so we could multiply these numbers by 1000 to estimate the total number of posts for each subreddit for this month.</p><p>With my passing familiarity with Reddit, I’d say these results seem consistent with my intuition about popular subreddits like “AskReddit”. What do you think?</p><p>Can you modify your earlier exercise code that computes the number of posts per author so that the results are sorted? Who are the top authors in this sample of Reddit posts?</p><p>Next, let’s see if our sample includes any posts with Scala in the title. You can add the following snippet to the previous ScalaFiddle widget to answer this question.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f8d75c668db103da255fbb7357948c7/href">https://medium.com/media/1f8d75c668db103da255fbb7357948c7/href</a></iframe><p>What do you think about these posts? Is every one of them about Scala or is there a deficiency in using this heuristic to programmatically identify relevant posts? We’ll consider more sophisticated ways to analyze posts soon.</p><p>What other words are interesting to you? Modify the code as you’d like to look for other posts that have certain keywords. In many ways, we’re building a simple, custom search engine to find posts relevant to our interests across this small sample.</p><p>Note, I myself have discovered a non-trivial amount of obscene language. As an exercise, you could write some Scala code to find posts that contain swear words. I’m not including example code for this because I don’t want to have a list of curse words on my blog. :)</p><p>In general, we’d be interested in computing the frequency of different words in post titles across each subreddit. Here’s some moderately sophisticated code that accomplishes such an analysis.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fscalafiddle.io%2Fsf%2F7xsbYu0%2F2&amp;src=https%3A%2F%2Fembed.scalafiddle.io%2Fembed%3Fsfid%3D7xsbYu0%2F2%26passive%26&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=scalafiddle" width="960" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5097bc3582ec90512bd9eb95750b7f8d/href">https://medium.com/media/5097bc3582ec90512bd9eb95750b7f8d/href</a></iframe><p>Take some time and think through this example. It’s a good review of many of the concepts we’ve considered so far in current and past articles. Reminder, that you can click “Edit on ScalaFiddle” on the widget to open the example in a separate window that doesn’t have the horizontal compression of the widget to better read the code.</p><p>The example code includes some concepts we haven’t yet explored. If you’d like, you could explore these concepts on your own — ahead of our shared journey through Scala — using resources at <a href="http://scala-lang.org/">scala-lang.org</a>. In general, that website is a great place to learn about Scala concepts. And, of course, a general Google search can also turn up some useful resources, including StackOverflow questions and answers.</p><p>One thing I’d like to explain at present is how this code example uses two cases of using pattern matching to deconstruct data structures. In these cases, we’re accessing the elements of a tuple through pattern matching deconstruction. Here’s an isolated example of deconstructing tuples in a function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fscalafiddle.io%2Fsf%2Frwujp7B%2F1&amp;src=https%3A%2F%2Fembed.scalafiddle.io%2Fembed%3Fsfid%3Drwujp7B%2F1%26passive%26&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=scalafiddle" width="960" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc336937444dbf6bb7f2c3eb0f88c08e/href">https://medium.com/media/cc336937444dbf6bb7f2c3eb0f88c08e/href</a></iframe><p>You can see we’ve defined the function in a non-standard fashion. In general, we’d primarily use this pattern in anonymous functions, which is what we’ve done in the word frequency example.</p><p>In addition to analyzing the Scala code, what do you think of these results? Do the word frequency results seem appropriate given your knowledge of Reddit? Are there any surprising results in highly frequent words for certain subreddits?</p><p>You can modify and extend these examples however you’d like to compute anything that interests you about Reddit posts. Here are some ideas for things you might want to compute for this sample of Reddit posts.</p><ul><li>What posts have the highest score? <em>(Example from intro of this article)</em></li><li>Which Redditors have the highest average scores?</li><li>Who are the most prolific-posting Redditors in each subreddit?</li><li>What words are frequent in high scoring posts? Versus what words are frequent in low scoring posts?</li><li>Which words have a generally low frequency across all posts, but a high frequency in specific subreddits? I.e., what words are uniquely characteristic of a given subreddit? We can quantify this by taking the ratio of subredditWordFrequency/generalWordFrequency for each subreddit/word pair and looking for high ratios. (This one is a good challenge to further develop your Scala proficiency.)</li></ul><p>I hope you’re enjoying applying Scala to analyze Reddit and learn a bit about Redditors. In the future, I’ll be showing you how to perform this analysis on the full set of Reddit posts for the month of October 2018. There are 11,306,843 posts in this month so we’ll need to learn how to apply Scala using the “big data” technology Spark.</p><p>You’ll be surprised to see how the code we write in these “big data” exercises is no more complicated than the code we’ve written in today’s exercises. Processing “big data” can be just as easy as small data when we use powerful technologies like Spark and Scala.</p><p>And thank you for working through another series of Scala exercises with me. I hope this one has been particularly fun because we’re getting to learn about real-world data. I’ll do what I can to create more exercises with this style.</p><p>I’d like to thank <a href="https://pushshift.io/">pushshift.io</a> for hosting Reddit data dumps. This is a really interesting source of data and it was easy for me to take a small sample from the full dataset for October 2018 for these examples and exercises. You can download this data yourself and write your own Scala code to start performing more sophisticated analyses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f394843069de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/interactively-exploring-reddit-posts-using-basic-scala-in-your-browsers-f394843069de">Interactively exploring Reddit posts using basic Scala in your browser</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief tour of lists in Scala and algorithmically processing them in SICP exercises]]></title>
            <link>https://medium.com/@matthagy/a-brief-tour-of-lists-in-scala-and-algorithmically-processing-them-in-sicp-exercises-935ff4d77775?source=rss-3fe708dd30ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/935ff4d77775</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Matt Hagy]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 00:07:44 GMT</pubDate>
            <atom:updated>2019-03-01T03:46:53.765Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s continue our journey through Scala using SICP exercises to demonstrate the elegance and simplicity of this powerful programming language in processing list data structures.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5GMt25zcqrodNdteA0lbA.jpeg" /></figure><p>This article builds off of part 1, <a href="https://medium.com/@matthagy/quickly-learning-the-basics-of-scala-through-structure-and-interpretation-of-computer-programs-ed5bfa90e8dc">Quickly learning the basics of Scala through Structure and Interpretation of Computer Programs examples</a>. That article also covers reasons for why you may want to learn Scala.</p><p>We continue our exploration of Scala using examples that solve exercises from the classic book, “<a href="https://web.mit.edu/alexmv/6.037/sicp.pdf">Structure and Interpretation of Computer Programs</a>” (SICP). Small exercises for the reader are also included.</p><p>Today we’re going to start working with some data in that we’re going to learn how to create and processes lists of elements. A list is a simple data structure that consists of a sequence of elements. There are many cases where we’ll need a collection of elements and lists can be a reasonable data structure in many of these cases. E.g., if we wanted to programmatically analyze some tweets from a famous person then we could store their tweets in a list for processing in Scala.</p><p>A list is constructed as a linear chain of elements whereby each element points to the next element in the list. Totally reasonable if that doesn’t sound intuitive. I think the concept is best illustrated with an example. The following figure shows a list of three elements; 12, 99, and 37.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*HOSlA3VwRI5nWdBQTNBAsw.png" /><figcaption>From Wikipedia article <a href="https://en.wikipedia.org/wiki/Linked_list">Linked list</a></figcaption></figure><p>Each list element consists of a value and a pointer to the next element. You can see how the first element of the list contains the value 12. This element also points to the second element in the list. The second element contains the value 99 and points to the third element. Finally, the third element of this list contains the value 37 and points to a special “end-of-list” terminal.</p><p>In Scala, we call this special terminal element Nil. We need such a terminal value to let us know when the list ends. We can think of Nil as a special element of the list that neither contains a value nor points to another value. It just exists to cap off the end.</p><p>So let’s go ahead and build the 12-to-99-to-37-to-Nil list in Scala.</p><p>Interestingly, we have to build the list starting from the tail. This makes sense when we reflect on how we’re going to build this list. We can’t create the first element until we have the second one since the first element needs to know what it’s going to point to when we create it. Similarly, we can’t create the second element until the third has been created.</p><p>So let’s start by creating the last non-Nil element of the list that contains the value 37 and points to Nil. Because lists are used all through Scala, the list element is given a special, concise name, ::. Yes, the formal name of the list element in Scala is just two colons. While unusual, as you work more with lists, you’ll come to appreciate the novel naming and brevity. Here’s the Scala code for creating a list with just the single element 37.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68c49247eacb73b0e55f222efb2c5ebf/href">https://medium.com/media/68c49247eacb73b0e55f222efb2c5ebf/href</a></iframe><p>We’re simply calling :: like a function and this corresponds to creating a new list element of type ::. Each :: element has two attributes:</p><ul><li>head : the value of the list element (e.g., 37 in this example)</li><li>tail : the pointer to the next element in the list (Nil in example)</li></ul><p>E.g.,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96f57c543a2356720e844f4b3545e1fc/href">https://medium.com/media/96f57c543a2356720e844f4b3545e1fc/href</a></iframe><p>Note that the Scala shows the single-element list ::(37, Nil) in a special format that downplays the role of individual list elements and just shows the values contained in the list. List(37) is the clearer representation of this list with just this one element. Scala could also show this as ::(37, Nil), but that’ll be harder to interpret when we get to longer lists.</p><p>Now let me introduce a generally cool Scala feature that motivates the :: naming convention: ::(head, tail) can also be written as head :: tail. E.g.,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/508fcef07499223f56e24c8036334589/href">https://medium.com/media/508fcef07499223f56e24c8036334589/href</a></iframe><p>Hence, :: can be thought of as a binary operator in math, similar to say + or -. Do you agree that this infix notation is a simpler syntax than ::(37, Nil)? We can appreciate it more when we see that multiple usages of :: can be chained in creating the rest of the list. Here’s what the code looks like to construct the full list with conventional constructor function calls.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b69c2146728568f750b32302c192de2/href">https://medium.com/media/0b69c2146728568f750b32302c192de2/href</a></iframe><p>Contrast that to the infix notation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/304795063f875722b9f5257cb662b692/href">https://medium.com/media/304795063f875722b9f5257cb662b692/href</a></iframe><p>Would you agree that the infix notation is a more legible way to define the elements that make up a list?</p><p>And we can do even better. The List(12, 99, 37) notation shown in the shell is a valid Scala expression to create a list of these three elements in the shown order. This is because List is a function for constructing lists. It can take any number of arguments, including zero. Behind the scenes, it does the work of creating the individual list elements and it returns the start of the list. The List function will be helpful as we create lists to process in today’s exercises.</p><p>Lists also introduce a new concept in terms of data types in that we want to be able to differentiate between lists with different types of elements. E.g., differentiating a list of Int values from a list of String values. This is necessary to ensure that all elements in a list conform to the same element type so we can write code that knows how to process all elements in an arbitrary list of a certain element type.</p><p>E.g., say we wanted to write a function to compute the sum of the values in a list of integers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c822e60a873017f23296c6daebeaaacd/href">https://medium.com/media/c822e60a873017f23296c6daebeaaacd/href</a></iframe><p>What would happen if we passed in a list of strings? E.g., List(&quot;a&quot;, &quot;b&quot;). If our code expected integers, then it would encounter an error when it tried to treat strings as integers. To avoid such errors, each Scala list type specifies the type of its list elements. The syntax for specifying a list of type X is List[X]. E.g., List[Int] and List[String].</p><p>This allows us to write the following type declaration for the list argument in our function that expects a list of integers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af17e3dcc13cdc469ed7af27a8bde005/href">https://medium.com/media/af17e3dcc13cdc469ed7af27a8bde005/href</a></iframe><p>And thereby Scala ensures that we can never accidentally call sumListIntegers with a list of anything other than integers.</p><h3>SICP List Exercises</h3><p>Let’s go ahead and implementsumListIntegers using our understanding of lists. As in part 1 of this series, we’re going to use recursion in place of looping to consider each element in computing the sum of a list.</p><p>Let me show you the example code and then explain what it’s doing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c45bc389661168447ae78a6a6ae5b59/href">https://medium.com/media/4c45bc389661168447ae78a6a6ae5b59/href</a></iframe><p>The main strategy is that we recurse on the sub-list formed by removing the first element. E.g., List(12, 99, 37).tail is the list List(99, 37). We then combine together the result of the recursive call with the value of the first element through addition. In turn, the recursive call to sumListIntegers with argument List(99, 37) again makes a recursive call, this time with an argument of List(37). And we’re not done yet! That call, in turn, calls sumListIntegers with the tail of List(37) which is Nil. The recursion then terminates because the empty list Nil has a sum of zero and we can return that.</p><p>That’s a lot of words. Let’s consider what the expansion looks like in math/code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22d96de412b75c85387ec168e4f03dd5/href">https://medium.com/media/22d96de412b75c85387ec168e4f03dd5/href</a></iframe><p>Take some time if you’d like and think through this recursion strategy to process all elements in a list. When you’re ready, you can then try out creating a recursive function to compute the length of a list by filling out the following template. I.e., count the number of elements in a list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec882ed82537327c27de171998750fe4/href">https://medium.com/media/ec882ed82537327c27de171998750fe4/href</a></iframe><p>You can test your solution in <a href="https://scastie.scala-lang.org/">Scastie</a>. (Note, you have to remove the lines that start with &gt; when running your code. I added those lines to show the expected output for each example input.)</p><p>Next, let’s consider a function that constructs a new list from its input list. E.g., let’s write a function to add five to every element of a List[Int]. This can be done recursively with the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/852f443f0da00140271575944c6a12d1/href">https://medium.com/media/852f443f0da00140271575944c6a12d1/href</a></iframe><p>Can you follow through how the recursive function calls build a new list that contains the results of adding five to each element of the input list? If not, take some time and work through the individual examples and reason through what the recursion chain looks like. I.e., write out the recursion expansion as we did with sumListIntegers.</p><p>Once you feel comfortable with the example, can you generalize the example to be a higher-order function that takes an arbitrary input function, func, in addition to a l: List[Int] and creates a new list that is the result of applying func to every element in the input list? Recall that a higher-order function is a function that takes other functions as input.</p><p>Let us call this new function map since it is mapping the function func across every element of the input list to create a new list. Here’s a template to get you started.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/714fae2a9047cc6c21ae02b0569aae12/href">https://medium.com/media/714fae2a9047cc6c21ae02b0569aae12/href</a></iframe><p>Again, you can test your solution in <a href="https://scastie.scala-lang.org/">Scastie</a>.</p><p>Once you’ve completed that exercise, let me show you a neat and more legible way to recurse over lists using Scala’s match expression. You may recall from the previous article how match allows us to define different conditions for matching a value. Scala then evaluates different code based upon which condition matches.</p><p>Here’s a neat way to implement add5toElement using match to determine whether or not we’re dealing with the Nil element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b281c77feab9d0db30988305196faa84/href">https://medium.com/media/b281c77feab9d0db30988305196faa84/href</a></iframe><p>You can see that we’re matching against the first element in the list. The first case matches Nil and terminates recursion since we’ve reached the end of the list. The second case statement is more interesting. Here we’re using deconstruction to not only match an :: element, but to also unpack its head and tail attributes into the local vals of h and t. We can then use these variables in processing the list element and recursing on the tail.</p><p>This starts to hint at some of the power of match. You’ll find many cases in Scala where match can be used to not only match against data but to also concisely access the attributes of a data type like ::. We’ll further explore match in later articles.</p><p>Can you modify your map function to use match?</p><p>We actually didn’t need to implement map. It’s already built into Scala. Specifically, lists in Scala have a map method (i.e., a function attached to the data structure) that we can use to apply a function to every element in the list, returning a new list of the results of applying the function. E.g.,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22be2027f798b483e775594a3d5b7d7b/href">https://medium.com/media/22be2027f798b483e775594a3d5b7d7b/href</a></iframe><p>It was still a great exercise to implement map to learn about recursion on lists, which is a common pattern in Scala. Nonetheless, you can commonly avoid writing your own recursive functions by leveraging builtin Scala algorithms like List.map.</p><p>As we’ll explore more in the future, map can work with lists of any element type as long as you pass in a function that can accept such elements. E.g., it doesn’t just work on List[Int], but it also works on List[String] and any other type of list as long as we have an appropriate function to map across the list. Further, the mapping function can have any return type and we get a list of elements with the return type of the given function.</p><p>This type flexibility is possible due to placeholder types in Scala. We’re gonna briefly look at simplified code examples for List that demonstrate this concept. In doing so, we’ll encounter a few parts of Scala that we haven’t yet studied and don’t be surprised if you can’t follow all of the code. I just want to introduce the idea that Scala has generic data structures like List that can hold any type of element and that this is accomplished through placeholder types. Here’s the simplified example code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7ece466896510410a5f1f92d6fa477e/href">https://medium.com/media/b7ece466896510410a5f1f92d6fa477e/href</a></iframe><p>No need to understand the details yet. Just see if it makes sense how both ::[A] and NilClass[A] implement the behavior of List[A] in terms of methods head, tail, and map. Further, these data structures can work on any generic type of list values as represented by the placeholder type A.</p><p>Only showing this example to hint at the power of Scala’s types. See if you can reason through why a calling map on aList[A] with a function of type f: A =&gt; B generates a List[B] where A and B can be any arbitrary Scala types. They can even be the same type.</p><p>To reiterate, :: and Nil are two types of List elements that have different behavior. Hence why we can use List[Int] to represent a sequence of :: elements that have Int values and terminate with Nil. We’ll explore this topic of traits and classes more in future articles.</p><p>There’s also a builtin list method called fold that can be used to aggregate across all elements in a list. E.g., we could re-implement sumListIntegers as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0d609e9f89726772bd4d94f02a85e2b/href">https://medium.com/media/d0d609e9f89726772bd4d94f02a85e2b/href</a></iframe><p>Note how we call fold with two different parameter lists. The first parameter list provides a starting value of aggregation, in this case, zero. The second parameter list takes a single function that operates on two elements.</p><p>Also, this example introduces the concept of an anonymous function in the code(aggregate: Int, element: Int) =&gt; aggregate + element. Anonymous functions can be useful to make our code more concise by not needing to define and name every function we write.</p><p>The “folding” function will be called multiple times. Each time it receives the current value of aggregation so far, as well as an element of the list. The function computes the new aggregation value, in this case by adding the list element value to the aggregate. This is repeated for every element in the list and results in a final aggregation value that returned by fold.</p><p>The name fold corresponds to how we create the recursion chain of form f(f(f(0, 37), 99), 12) for the folding function f with an input of List(12, 99, 37). We’re essentially repeatedly calling f and <em>folding</em> the list down to a single aggregate value through the recursion chain.</p><p>FYI, here’s a simplified implementation of fold in Scala. Take a few minutes and see if you can reason through some parts of what’s going on. Totally fine if you find some parts confusing and don’t yet understand them. We’ll be exploring the details of placeholder types and classes in the future.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c35aaebe40ce7320f5cb04ac79dd98b/href">https://medium.com/media/1c35aaebe40ce7320f5cb04ac79dd98b/href</a></iframe><p>Both map and fold can be used in many cases to simplify our processing of lists. Further, as we’ll see in future installments of this series, there are other Scala data structures that also implement map and fold methods for processing their elements. Lastly, there are many other useful algorithms implemented in built-in methods of Scala data structures that can simplify our code and we’ll explore them over time.</p><p>As always, thanks for following along on our journey through Scala. And please let me know if any part of this article could be made more clear so as to help future readers. Send any feedback to <a href="/service/mailto:matthew.hagy@gmail.com">matthew.hagy@gmail.com</a>.</p><p>Part three is out and it’s particularly fun in that you get to analyze Reddit data in your browser and learn a bit about Redditors. Checkout <a href="https://medium.com/@matthagy/interactively-exploring-reddit-posts-using-basic-scala-in-your-browsers-f394843069de">Interactively exploring Reddit posts using basic Scala in your browser</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935ff4d77775" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>