<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tomáš Zemanovič</title>
    <description>The latest articles on DEV Community by Tomáš Zemanovič (@tzemanovic).</description>
    <link>https://dev.to/tzemanovic</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F63810%2F6e903eb6-eca3-42fc-b3da-c61ecb6315d8.png</url>
      <title>DEV Community: Tomáš Zemanovič</title>
      <link>https://dev.to/tzemanovic</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tzemanovic"/>
    <language>en</language>
    <item>
      <title>State machine testing with Proptest</title>
      <dc:creator>Tomáš Zemanovič</dc:creator>
      <pubDate>Tue, 28 Mar 2023 00:00:00 +0000</pubDate>
      <link>https://dev.to/tzemanovic/state-machine-testing-with-proptest-2539</link>
      <guid>https://dev.to/tzemanovic/state-machine-testing-with-proptest-2539</guid>
      <description>&lt;p&gt;I’m excited to share the state machine testing support for Proptest crate that I’m trying to contribute back into upstream 🧡 and to include the contents of this post as a guide in the Proptest Book.&lt;/p&gt;

&lt;p&gt;Rust is very practical. It allows me to stay productive by guiding me through code with its type-checker and borrow-checker. In general though, more code means more opportunities for bugs to sneak in and I often surprise myself with just how many of them I miss when I pretend that I can interpret code in my head. As the old wisdom goes, types are no substitute for tests (even in e.g. pure functional languages with more expressive types) and Rust has some great facilities for testing. I love using Proptest as it enables me to test code thoroughly and go through cases that I wouldn’t have thought of myself.&lt;/p&gt;

&lt;p&gt;I’ve been using the state machine tests in &lt;a href="https://github.com/anoma/namada/search?l=Rust&amp;amp;q=StateMachineTest"&gt;Namada project&lt;/a&gt;. I’m all for OSS development, knowledge sharing to help others to form their opinion and improving the general state of the software development industry (don’t we all regularly encounter issues in software), but &lt;em&gt;please&lt;/em&gt; don’t mistake this for an endorsement of blockchains.&lt;/p&gt;

&lt;p&gt;Before this gets through 🤞, you can find the branch of Proptest that contains the state machine testing feature here &lt;a href="https://github.com/proptest-rs/proptest/pull/310"&gt;https://github.com/proptest-rs/proptest/pull/310&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.flickr.com/photos/155623578@N06/43514999232/in/photostream/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Jd-XPgov--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://tzemanovic.gitlab.io/posts/state-machine-testing-with-proptest/cicindela-aurulenta.jpg" alt="Cicindela Aurulenta by Portioid" title="Cicindela Aurulenta by Portioid" width="800" height="562"&gt;&lt;b&gt;Cicindela Aurulenta by Portioid&lt;/b&gt; / CC BY-SA 2.0&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Before using state machine testing, it is recommended to be at least familiar with the basic concepts of Proptest itself as it’s built on its essential foundations. That is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Strategies are composed and used to generate inputs to a state machine test.&lt;/li&gt;
&lt;li&gt;A test will attempt to shrink the generated transitions sequence on a discovery of a case that breaks some properties.&lt;/li&gt;
&lt;li&gt;It will capture regressions file with a seed that can be used to deterministically repeat the found case.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Be cautious that it may not be fully self-explanatory how to use it from its API and there are some opportunities for paper cuts. What follows is a more detailed description that will guide you through it.&lt;/p&gt;

&lt;p&gt;In short, use &lt;code&gt;AbstractStateMachine&lt;/code&gt; and &lt;code&gt;StateMachineTest&lt;/code&gt; to implement your state machine test and &lt;code&gt;prop_state_machine!&lt;/code&gt; macro to run it.&lt;/p&gt;

&lt;p&gt;If you just want to get started quickly, take a look at one of the examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;state_machine_heap.rs&lt;/code&gt; - a simple model to test an API of a heap data structure&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;state_machine_echo_server.rs&lt;/code&gt; - a more advanced model for an echo server with multiple clients talking to it&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To see what transitions are being applied in standard output as the state machine test executes, run these with e.g. &lt;code&gt;PROPTEST_VERBOSE=1 cargo run --example state_machine_heap&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The state machine testing support for Proptest is heavily inspired by the Erlang’s eqc_statem (see the paper &lt;a href="https://smallbone.se/papers/finding-race-conditions.pdf"&gt;Finding Race Conditions in Erlang with QuickCheck and PULSE&lt;/a&gt;) with some key differences. Most notably:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Currently, only sequential strategy is supported, but a concurrent strategy is planned to be added at later point.&lt;/li&gt;
&lt;li&gt;There are no “symbolic” variables like in eqc_statem. The state for the abstract state machine is separate from the concrete state machine.&lt;/li&gt;
&lt;li&gt;The post-conditions are not defined in their own function. Instead, they are part of the &lt;code&gt;apply_concrete&lt;/code&gt; function.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  When to use State Machine testing?
&lt;/h2&gt;

&lt;p&gt;State machine testing automates the checking of properties of a system under test (SUT) against an abstract state machine definition. It does this by trying to discover a counter-example that breaks the defined properties of the system and attempts to shrink it to a minimal sequence of transitions that still reproduce the issue.&lt;/p&gt;

&lt;p&gt;State machines are a very useful abstraction for reasoning about code. Many things from low-level to high-level logic and anywhere in between can be modelled as a state machine. They are very effective for modelling effectful code, that is code that performs some state changes that can be too hard to test thoroughly with a more manual approach or too complex to verify formally.&lt;/p&gt;

&lt;p&gt;Some fitting examples to give you an idea include (by no means exhaustive):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A data structure with an API that mutates its state&lt;/li&gt;
&lt;li&gt;An API for a database&lt;/li&gt;
&lt;li&gt;Interactions between a client(s) and a server&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There is some initial investment needed to set the test up and it usually takes a bit more time to run than simple prop tests, but if correctness is important for your use case, you’ll be rewarded with a test that is so effective at discovering bugs it might feel almost magical, but as you’ll see, you could have easily implemented it yourself. Also, once you have the test setup, it is much easier to extend it and add new properties to check.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use it
&lt;/h2&gt;

&lt;p&gt;State machine testing is made up of two parts, an abstract state machine definition that drives the inputs to a test and a test definition for a SUT that replicates the same transitions as the abstract state machine to find any possible divergence or conditions under which the defined properties (in here post-conditions and invariants) start to break.&lt;/p&gt;

&lt;h3&gt;
  
  
  Abstract state machine strategy
&lt;/h3&gt;

&lt;p&gt;You can get started with state machine testing by implementing &lt;code&gt;trait AbstractStateMachine&lt;/code&gt;, which is used to drive the generation of a sequence of transitions and can also be compared against the state of the SUT. At the minimum, this trait requires two associated types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;type State&lt;/code&gt; that represents the state of the abstract state machine.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;type Transition&lt;/code&gt; with possible transitions of the state machine. This is typically an &lt;code&gt;enum&lt;/code&gt; with its variants containing input parameters for the transitions, if any.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You also have to implement three associated functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;To initialize the abstract state machine:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To generate transitions:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To apply the given transition on the abstract state:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Additionally, you may want to override the default implementation of:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn preconditions(state: &amp;amp;Self::State, transition: &amp;amp;Self::Transition) -&amp;gt; bool
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By default, this simply returns &lt;code&gt;true&lt;/code&gt;, which implies that there are no pre-conditions. Pre-conditions are a way of restricting what transitions are valid for a given state and you’ll &lt;em&gt;only&lt;/em&gt; need to restrict the transitions whose validity depends on the current state. This ensures that the abstract state machine will only produce and shrink to a sequence of valid valid transitions. It may not be immediately apparent that the current state may be affected by shrinking. With the example of selecting of keys of a hash map for &lt;code&gt;fn transitions&lt;/code&gt;, you’ll need to check that the transition’s key is still present in the hash map, which may no longer be true after some shrinking is applied.&lt;/p&gt;

&lt;p&gt;You can either implement &lt;code&gt;AbstractStateMachine&lt;/code&gt; for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A data structure that will represent your abstract state machine and set the associated &lt;code&gt;type State = Self;&lt;/code&gt; or&lt;/li&gt;
&lt;li&gt;An empty &lt;code&gt;struct&lt;/code&gt;, which may be more convenient than making a wrapper type if you’re using a foreign type for the &lt;code&gt;type State&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Definition of a state machine test
&lt;/h3&gt;

&lt;p&gt;With that out of the way, you can go ahead and implement &lt;code&gt;StateMachineTest&lt;/code&gt;. This also requires two associated types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;type ConcreteState&lt;/code&gt; which is the type that represents the SUT.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;type Abstract&lt;/code&gt; with the type for which you implemented the &lt;code&gt;AbstractStateMachine&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are also three associated functions to be implemented here (some types are slightly simplified for clarity):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Initialize the concrete state:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Apply the &lt;code&gt;transition&lt;/code&gt; on the concrete state:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Check properties that apply in any state:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Make the state machine test runnable
&lt;/h3&gt;

&lt;p&gt;Finally, to run the &lt;code&gt;StateMachineTest&lt;/code&gt;, you can use the &lt;code&gt;prop_state_machine!&lt;/code&gt; macro. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;prop_state_machine! {
  #[test]
  fn name_of_the_test(sequential 1..20 =&amp;gt; MyStateMachineTest);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You pick a &lt;code&gt;name_of_the_test&lt;/code&gt; and a single numerical value or a range after the &lt;code&gt;sequential&lt;/code&gt; keyword for a number of transitions to be generated for the state machine execution. The &lt;code&gt;MyStateMachineTest&lt;/code&gt; is whatever you’ve implemented the &lt;code&gt;StateMachineTest&lt;/code&gt; for.&lt;/p&gt;

&lt;p&gt;And that’s it. You can run the test, perhaps with &lt;code&gt;cargo watch&lt;/code&gt; as you develop it further, and see if it can find some interesting counter-examples to your properties.&lt;/p&gt;

&lt;h3&gt;
  
  
  Extra tips
&lt;/h3&gt;

&lt;p&gt;Because a state machine test may be heavier than regular prop tests, if you’re running your tests in a CI you may want to override the default &lt;code&gt;proptest_config&lt;/code&gt;’s &lt;code&gt;cases&lt;/code&gt; to include fewer cases in a single run. You can also use &lt;code&gt;PROPTEST_CASES&lt;/code&gt; environment variable and during development it is preferable to override this to run many cases to get a better chance of catching those pesky &lt;del&gt;bugs&lt;/del&gt; , erm, defects.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Given that there are thought to be in the region of another four million species that we have not yet even named, there is no doubt that scientists will be kept happily occupied studying them for millennia, so long as the insects remain to be studied. Would the world not be less rich, less surprising, less wonderful, if these peculiar creatures did not exist?&lt;/p&gt;

&lt;p&gt;– &lt;cite&gt;Dave Goulson, Silent Earth&lt;/cite&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So let’s leave bugs alone and only squash defects instead!&lt;/p&gt;

&lt;p&gt;Because the output of a failed test case can be a bit hard to read, it is often convenient to print the transitions. You can do that by simply setting the &lt;code&gt;proptest_config&lt;/code&gt;’s &lt;code&gt;verbose&lt;/code&gt; to &lt;code&gt;1&lt;/code&gt; or higher. Again, if you don’t want to keep this in your test’s config or if you’d prefer to override the config, you could also use the &lt;code&gt;PROPTEST_VERBOSE&lt;/code&gt; environment variable instead.&lt;/p&gt;

&lt;p&gt;Another helpful config option that is good to know about is &lt;code&gt;timeout&lt;/code&gt; (&lt;code&gt;PROPTEST_TIMEOUT&lt;/code&gt; via an env var) for tests that may take longer to execute.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does it work
&lt;/h2&gt;

&lt;p&gt;This section goes into the inner workings of how the state machine is implemented, omitting some less interesting details. If you’re only interested in using it, you can consider this section an optional read.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;AbstractStateMachine::sequential_strategy&lt;/code&gt; sets up a &lt;code&gt;Sequential&lt;/code&gt; strategy that generates a sequence of transitions from the definition of the &lt;code&gt;AbstractStateMachine&lt;/code&gt;. The acceptability of each transition in the sequence depends on the current state of the state machine and &lt;code&gt;AbstractStateMachine::preconditions&lt;/code&gt;, if any. The state is updated by the transitions with the &lt;code&gt;AbstractStateMachine::apply_abstract&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Sequential&lt;/code&gt; strategy is then fed into Proptest like any other strategy via the &lt;code&gt;prop_state_machine!&lt;/code&gt; macro and it produces a &lt;code&gt;Vec&amp;lt;Transition&amp;gt;&lt;/code&gt; that gets passed into &lt;code&gt;StateMachineTest::test_sequential&lt;/code&gt; where it is applied one by one to the SUT. Its post-conditions and invariants are checked during this process and if a failing case is found, the shrinking process kicks in until it can shrink no longer.&lt;/p&gt;

&lt;p&gt;The shrinking strategy which is defined by the associated &lt;code&gt;type Tree = SequentialValueTree&lt;/code&gt; of the &lt;code&gt;Sequential&lt;/code&gt; strategy is to iteratively apply &lt;code&gt;Shrink::InitialState&lt;/code&gt;, &lt;code&gt;Shrink::DeleteTransition&lt;/code&gt; and &lt;code&gt;Shrink::Transition&lt;/code&gt; (this can be found in &lt;code&gt;proptest/src/strategy/state_machine.rs&lt;/code&gt;):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We start by trying to delete transitions from the back of the list until we can do so no further (the list has reached the &lt;code&gt;min_size&lt;/code&gt; - that is the variable that gets set from the chosen range for the number of transitions in the &lt;code&gt;prop_state_machine!&lt;/code&gt; invocation).&lt;/li&gt;
&lt;li&gt;Then, we again iteratively attempt to shrink the individual transitions, but this time starting from the front of the list from the first transition to be applied.&lt;/li&gt;
&lt;li&gt;Finally, we try to shrink the initial state until it’s not possible to shrink it any further.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The last applied shrink gets stored in the &lt;code&gt;SequentialValueTree&lt;/code&gt;, so that if the shrinking process ends up in a case that no longer reproduces the discovered issue, the call to &lt;code&gt;complicate&lt;/code&gt; in the &lt;code&gt;ValueTree&lt;/code&gt; implementation of the &lt;code&gt;SequentialValueTree&lt;/code&gt; can attempt to undo it.&lt;/p&gt;




&lt;h2&gt;
  
  
  Closing thoughts
&lt;/h2&gt;

&lt;p&gt;If you have some use case where state machine testing can be applied I hope that this guide will make it easier to get you started. As always, I’d appreciate any feedback and if you have any issues with using this Proptest feature or some interesting exhibit discovered with its help, please don’t hesitate to share it!&lt;/p&gt;

</description>
      <category>rust</category>
      <category>proptest</category>
      <category>statemachines</category>
      <category>testing</category>
    </item>
    <item>
      <title>Rust coding style</title>
      <dc:creator>Tomáš Zemanovič</dc:creator>
      <pubDate>Fri, 03 Mar 2023 00:00:00 +0000</pubDate>
      <link>https://dev.to/tzemanovic/rust-coding-style-3ebj</link>
      <guid>https://dev.to/tzemanovic/rust-coding-style-3ebj</guid>
      <description>&lt;p&gt;This post is about a high-level Rust coding style (as in it doesn’t go into specific details), partly inspired by data-oriented design and partly by ML-based functional programming languages, which imho fits quite naturally into Rust and makes for ergonomic, flexible and easily extensible APIs. It’s nothing advanced, but I hope this would be useful for people coming to Rust, perhaps with some background in one of the common OOP languages.&lt;/p&gt;

&lt;p&gt;I’ll try to sum up the main points into a handful of guiding principles, highlighted in block quotes for easy skim reading. If you don’t agree with something, I invite you to read the supporting arguments and if you still don’t agree I’d love to hear your opinion.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.flickr.com/photos/rling/6632800923/in/photostream" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Ftzemanovic.gitlab.io%2Fposts%2Frust-coding-style%2Fsponge-decorator-crab.jpg" title="Sponge Decorator Crab by Richard Ling" alt="Sponge Decorator Crab by Richard Ling" width="400" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Data-oriented design originated in games development and is very well suited for performance and opens the door to better optimization. When you pick Rust over some higher-level language in which you, for example, don’t need to think about ownership, you probably care about performance and might want to optimize your code at some point and even if you don’t, you’ll reasonably expect good out-of-box performance. But of course, there are many other great reasons to use Rust too, not least its great community!&lt;/p&gt;

&lt;p&gt;Somewhat analogously to the rule of least power, I think that &lt;code&gt;fn&lt;/code&gt;s with &lt;code&gt;struct&lt;/code&gt;, &lt;code&gt;enum&lt;/code&gt; , &lt;code&gt;type&lt;/code&gt; aliases and &lt;code&gt;mod&lt;/code&gt;s are not only sufficient for most things we commonly do but sticking to them is advantageous. In most modern computer architectures, data layout and locality are of the utmost importance for performance.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Pay a lot of attention to your data structures, they have a huge impact on what you’ll be able to do.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It’s not just for performance sake, data structures are very helpful in getting a good understanding of the problem and implementing a solution in a clear, readable and maintainable way. To quote Mike Acton “if you don’t understand the data, you don’t understand the problem”.&lt;/p&gt;

&lt;p&gt;In functional programming, we take advantage of the fact that sum types (&lt;code&gt;enum&lt;/code&gt;s in Rust) allow you to express data of arbitrary cardinality (number of possible variants), so you can:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Make invalid states impossible to represent with your data types.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If it’s not clear how to do that, there are great articles and talks you can find on the topic.&lt;/p&gt;

&lt;p&gt;A very simple example: Say you have a type (or arguments to a function) in which you want to have either &lt;code&gt;A&lt;/code&gt;, &lt;code&gt;B&lt;/code&gt;, or neither of them. If you simply use two &lt;code&gt;Option&lt;/code&gt; types (&lt;code&gt;NotXorOpts&lt;/code&gt; below), it’s possible to represent a value with both of &lt;code&gt;A&lt;/code&gt; and &lt;code&gt;B&lt;/code&gt; present. But you can very quickly define a custom &lt;code&gt;enum&lt;/code&gt; type that rules that out:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct A;
struct B;

type NotXorOpts = (Option&amp;lt;A&amp;gt;, Option&amp;lt;B&amp;gt;);

enum XorOpts {
  A(A),
  B(B),
  Neither,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The essence of it is to &lt;a href="https://guide.elm-lang.org/appendix/types_as_sets.html" rel="noopener noreferrer"&gt;think of types as sets&lt;/a&gt;. In particular, Rust &lt;code&gt;enum&lt;/code&gt;s act as closed sets - open sets can be represented with &lt;code&gt;trait&lt;/code&gt;s. Often, &lt;code&gt;trait&lt;/code&gt;s are used in places where closed sets are sufficient.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Prefer to only use &lt;code&gt;trait&lt;/code&gt;s if and when you &lt;strong&gt;need&lt;/strong&gt; open sets.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That is, only use them when you don’t know or cannot forsee all the possible variants.&lt;/p&gt;

&lt;p&gt;You can often see encapsulation being achieved by keeping fields of data structures private, which looks satisfying because it can prevent the consumer from doing modifications that would break some abstractions. In a &lt;code&gt;struct&lt;/code&gt;, fields are private by default so you do get directed into this, but there are other ways to achieve encapsulation. Here, I want to advocate:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Never&lt;/strong&gt; hide data fields of types that appear in your public API.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When you’re using a crate and its abstraction doesn’t exactly fit with what you’re doing, having all public data types may allow to make it suit your use case without having to wrangle it with some transmutations, fork it or worse abandon it altogether. As we know, pretty much all the abstractions in software are leaky. Furthermore, when you do care about the layout of your data and some abstraction is trying to hide it from you, it is only getting in the way of that.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Instead of putting your invariants on data types, place them on functions, document them, and use &lt;code&gt;debug_assert!&lt;/code&gt;s generously.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Another pain point which might ruin your day is that when you follow the data hiding encapsulation technique, you’ll be limited in what you can do when you’re using a method that requires you to mutably borrow the data you’re working with (&lt;code&gt;&amp;amp;mut self&lt;/code&gt;). Before the mutable borrow is returned (to avoid any confusion, I do not mean the keyword &lt;code&gt;return&lt;/code&gt;, but rather the moment when the mutable reference of the thing that’s being borrowed is released), you will not be able to call other methods on it that require immutable borrowing (&lt;code&gt;&amp;amp;self&lt;/code&gt;), even if you can reason yourself that the fields that are being mutated are different from the fields that you want to access immutably. While there are some proposals on how to allow such code to be expressed, when the fields are public, you’re all good to &lt;a href="https://doc.rust-lang.org/nomicon/borrow-splitting.html" rel="noopener noreferrer"&gt;partially borrow them directly&lt;/a&gt;! Simpler and easier.&lt;/p&gt;

&lt;p&gt;Let’s look at an example that may be given as a motivation for hiding data to achieve encapsulation. Say we have some list of integers, which can get large and we’ll want to often use its average without having to recompute it every time, so we might want to store it with the data. In an OOP way, this may looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(Default)]
struct AvgVec {
  data: Vec&amp;lt;i64&amp;gt;,
  avg: i64,
}

impl AvgVec {
  pub fn get_avg(&amp;amp;self) -&amp;gt; i64 { self.avg }

  pub fn push(&amp;amp;mut self, val: i64) {
    self.data.push(val);
    self.update_avg();
  }

  pub fn pop(&amp;amp;mut self) -&amp;gt; Option&amp;lt;i64&amp;gt; {
    let res = self.data.pop()?;
    self.update_avg();
    Some(res)
  }

  fn update_avg(&amp;amp;mut self) { todo!() }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whenever the &lt;code&gt;data&lt;/code&gt; changes, which here is only possible via the public &lt;code&gt;push&lt;/code&gt; and &lt;code&gt;pop&lt;/code&gt; methods, we call &lt;code&gt;update_avg&lt;/code&gt; and so we internally enforce data consistency, which is not a bad thing and after making it generic you might consider the problem solved. But we can achieve the same without hiding any data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct AvgVec(pub Vec&amp;lt;i64&amp;gt;);

impl AvgVec {
  /// Push a value and return the new average.
  pub fn push(&amp;amp;mut self, val: i64) -&amp;gt; i64 {
    self.0.push(val);
    self.avg()
  }

  /// If the data is not empty, returns a pair of the popped value and the new average.
  pub fn pop(&amp;amp;mut self) -&amp;gt; Option&amp;lt;(i64, i64)&amp;gt; {
    let res = self.0.pop()?;
    let new_avg = self.avg();
    Some((res, new_avg))
  }

  /// Compute the average value. Returns `0` if the data is empty.
  pub fn avg(&amp;amp;self) -&amp;gt; i64 { todo!() }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Admittedly, this does feel a bit trivial and contrived, but I hope it illustrates the point. If you can think of a better (counter-)example, I want to hear from you!&lt;/p&gt;

&lt;p&gt;A nice side effect of this style is that unlike in the first version if you forget to return the new average, it’s a type error. If you remove the call to &lt;code&gt;self.update_avg();&lt;/code&gt; or you forget to use it in a new function that mutates the state, you don’t get much help.&lt;/p&gt;

&lt;p&gt;Of course, it’s still a good practice to minimize how much you rely on the internals of some data type outside of its module(s), as you will be less likely affected if and when the data type changes, but even if you do, the type system has your back.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Use the module system to encapsulate logic.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For more complex modules, you can split it up into (private) sub-modules and then re-export (&lt;code&gt;pub use&lt;/code&gt;) the public parts from the parent module. The Rust compiler will even check for you when you accidentally expose something that is using another thing in its API that itself isn’t public.&lt;/p&gt;

&lt;p&gt;In Rust methods are just syntax sugar providing some convenience, but often, there is over-reliance on using methods for stuff that doesn’t need it, which I suspect is at least partly habitual from OOP languages. Taking the example from above, we could just as well do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub type Data = Vec&amp;lt;i64&amp;gt;;

/// Push a value and return the new average.
pub fn push(data: &amp;amp;mut Data, val: i64) -&amp;gt; i64 {
  data.push(val);
  avg(&amp;amp;data)
}

/// If the data is not empty, returns a pair of the popped value and the new average.
pub fn pop(data: &amp;amp;mut Data) -&amp;gt; Option&amp;lt;(i64, i64)&amp;gt; {
  let res = data.pop()?;
  let new_avg = avg(data);
  Some((res, new_avg))
}

/// Compute the average value. Returns `0` if the data is empty.
pub fn avg(data: &amp;amp;Data) -&amp;gt; i64 { todo!() }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Not everything needs to be a method, in fact, often a method can carry a lot of baggage when you only need a handful of things from &lt;code&gt;self&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Strive to reduce the inputs to your functions to the bare minimum needed to implement them.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This makes it easier to test such functions very thoroughly in isolation from things that are not relevant to them. You can build very readable code with plain functions using qualified symbols with similar usability to methods. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// This `mod` might be a file `space.rs`
pub mod space {
  pub struct Ship;

  pub fn yeet(ship: Ship) {}
  pub fn is_the_place() -&amp;gt; bool { true }
}

fn main() {
  let space_karen = space::Ship;
  space::yeet(space_karen);
  assert!(space::is_the_place());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you’re used to having a drop-down of possible methods to come up after you type &lt;code&gt;.&lt;/code&gt; following a name of a variable, switching to &lt;code&gt;::&lt;/code&gt; following a module name works much the same.&lt;/p&gt;

&lt;p&gt;Last but not least. While Rust’s type system is powerful and it will help you to find how to do things right and prevent many bugs, it also makes it very cheap to add tests and sometimes it can be easier to test against issues than it is to prevent them at type level.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay pragmatic, not everything needs to be solved at type level.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>rust</category>
      <category>codingstyle</category>
      <category>dataorienteddesign</category>
      <category>abstractions</category>
    </item>
    <item>
      <title>Abstraction levels in functional programming</title>
      <dc:creator>Tomáš Zemanovič</dc:creator>
      <pubDate>Thu, 27 Dec 2018 00:00:00 +0000</pubDate>
      <link>https://dev.to/tzemanovic/abstraction-levels-in-functional-programming-5cd2</link>
      <guid>https://dev.to/tzemanovic/abstraction-levels-in-functional-programming-5cd2</guid>
      <description>&lt;p&gt;&lt;em&gt;Update on December 29, 2018&lt;/em&gt;: I misinterpreted what was meant by the implementation inhabitants, so I scratched the sentence that talked about it. Thanks, Brian!&lt;/p&gt;

&lt;p&gt;Teaching and learning functional programming can be challenging. Many people will already have some experience of programming, which is usually very different from FP concepts. Analogies to other languages can sometimes do more damage than good (you’ve probably heard that you have to “unlearn” stuff when you’re starting to learn FP). I am delighted to see more people learning functional programming and find the effort that goes into making it accessible to a wider audience encouraging. I think that &lt;a href="https://elm-lang.org/"&gt;Elm&lt;/a&gt; has a great role to play in it.&lt;/p&gt;

&lt;p&gt;I’m a fan of the work Brian McKenna does with Haskell on that front (my personal favourite are his streams on building Sonic in Haskell). His recent post on &lt;a href="https://brianmckenna.org/blog/higher_kinded_parametricity"&gt;Higher Kinded Parametricity&lt;/a&gt; made me think about abstraction and its role in teaching and learning FP. The argument concerns Functor type class and the following function (not to be confused with the void type that originated in Algol, C and found in many popular OOP languages):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void ::
  Functor f =&amp;gt;
  f a
  -&amp;gt; f ()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To anyone versed in Haskell, this is a very basic example as Functor is a fundamental building block that appears in many places. To those who are less familiar, this could pose many new challenges.&lt;/p&gt;

&lt;p&gt;Upon opening &lt;a href="https://www.haskell.org/hoogle/"&gt;hoogle&lt;/a&gt;, you might find the definition of &lt;a href="http://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#t:Functor"&gt;Functor&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The Functor class is used for types that can be mapped over…&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Alright, so Functor is a class, but once again, these classes are nothing like OOP classes. Assuming some familiarity with the concept of &lt;code&gt;Maybe&lt;/code&gt; data type (in some languages called Optional), what would happen if we instead started from the bottom of the abstraction ladder and worked our way up?&lt;/p&gt;

&lt;p&gt;Haddock tells us that, for example, void replaces the contents of a &lt;code&gt;Maybe Int&lt;/code&gt; with unit (unit is denoted with &lt;code&gt;()&lt;/code&gt; ). In a basic form, we can express this as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void :: Maybe Int -&amp;gt; Maybe ()
void Nothing = Nothing
void (Just _) = Just ()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But for the purpose of this function, it’s irrelevant if the parameter was &lt;code&gt;Maybe Int&lt;/code&gt;, &lt;code&gt;Maybe Bool&lt;/code&gt; or &lt;code&gt;Maybe a&lt;/code&gt;, so we introduce parametric polymorphism:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void :: Maybe a -&amp;gt; Maybe ()
void Nothing = Nothing
void (Just _) = Just ()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A type starting with a lower case letter is polymorphic, meaning we can put another type in its place. Indeed, if we replace &lt;code&gt;a&lt;/code&gt; with &lt;code&gt;Int&lt;/code&gt; we’ll get exactly what we had in the previous level.&lt;/p&gt;

&lt;p&gt;Next, we could show that the kind of operation on &lt;code&gt;Maybe&lt;/code&gt; type where we do something with its contents is very common, so we define:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fmap :: (a -&amp;gt; b) -&amp;gt; Maybe a -&amp;gt; Maybe b
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first parameter accepts a function that gets applied to the content of the second argument, if it has any content.&lt;/p&gt;

&lt;p&gt;We can now use this to implement our void function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void :: Maybe a -&amp;gt; Maybe ()
void = fmap $ const ()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Elm, this is where we reach the ceiling of abstraction (note that in Elm, Haskell’s &lt;code&gt;const&lt;/code&gt; is named &lt;code&gt;always&lt;/code&gt; and &lt;code&gt;$&lt;/code&gt; is named &lt;code&gt;&amp;lt;|&lt;/code&gt; ) :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void : Maybe a -&amp;gt; Maybe ()
void = Maybe.map &amp;lt;| always ()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or for the &lt;code&gt;List&lt;/code&gt; data type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void : List a -&amp;gt; List ()
void = List.map &amp;lt;| always ()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You would have to implement this for each data type for which you’d want to use this function, which can be tedious. But, is this really more complicated than in Haskell? &lt;del&gt;Our &lt;code&gt;void&lt;/code&gt; implementation for &lt;code&gt;Maybe&lt;/code&gt; still has only a single inhabitant and the same with &lt;code&gt;List&lt;/code&gt;.&lt;/del&gt;&lt;/p&gt;

&lt;p&gt;Does this stop Elm from being incredibly practical or could this be a viable alternative for the currently most prominent web library React? I have reasons to think it exceeds React on many fronts&lt;sup&gt;1&lt;/sup&gt;&lt;sup&gt;2&lt;/sup&gt;. Those who pick up Elm will feel encouraged by being able to build great things using pure FP.&lt;/p&gt;

&lt;p&gt;Haskell can, of course, take the abstraction to another level thanks to the wonderful concept of type classes first introduced by the living legend Philip Wadler and Stephen Blott in 1988 as a way of taming ad-hoc polymorphism:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void :: Functor f =&amp;gt; f a -&amp;gt; f ()
void x = () &amp;lt;$ x
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And it can go much further with that. After all, type classes are built on category theory, the language of mathematics. But even mathematicians can struggle with abstraction. I recommend the work of Eugenia Cheng, who explains mathematics and category theory in the most accessible down to earth way&lt;sup&gt;3&lt;/sup&gt;. The following quote comes from her &lt;em&gt;How to bake PI: An Edible Exploration of the Mathematics of Mathematics&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A moment where advanced mathematicians sometimes reach their abstract limit is category theory. They react in much the same way that teenagers do when they need x’s and y’s - they say they don’t see the point, and resist any further abstraction.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As programmers we are lucky to have the context for learning about these concepts.&lt;/p&gt;

&lt;p&gt;If type classes are an essential part of your toolbox, then you’ll possibly find using Elm restricting. However, as this can be a scary territory for newcomers, it’s important to be sympathetic, especially if you teach FP using Haskell. Regardless, it shouldn’t have to be an exclusive choice. If and when Elm developers get the need to pursue the abstraction further, they’ll most definitely circle back to Haskell, PureScript or anything else with a more advanced type system. But I’m hopeful Elm will evolve to implement type classes in future.&lt;/p&gt;

&lt;p&gt;We all have different ways in which we learn most effectively. Did your previous experience affect your learning of functional programming? Wouldn’t it be more constructive if FP communities were more united over the common goal of teaching FP? Please share your thoughts.&lt;/p&gt;




&lt;ol&gt;
&lt;li id="fn1"&gt;&lt;p&gt;&lt;a href="https://elm-lang.org/blog/blazing-fast-html-round-two"&gt;Blazing Fast HTML&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn2"&gt;&lt;p&gt;&lt;a href="https://elm-lang.org/blog/small-assets-without-the-headache"&gt;Small Assets without the headache&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn3"&gt;&lt;p&gt;&lt;a href="http://eugeniacheng.com/math/books/"&gt;Books by Eugenia Cheng&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>elm</category>
      <category>haskell</category>
      <category>functional</category>
      <category>learning</category>
    </item>
    <item>
      <title>New, simpler and user-friendlier page</title>
      <dc:creator>Tomáš Zemanovič</dc:creator>
      <pubDate>Tue, 11 Dec 2018 00:00:00 +0000</pubDate>
      <link>https://dev.to/tzemanovic/new-simpler-and-user-friendlier-page-3mcf</link>
      <guid>https://dev.to/tzemanovic/new-simpler-and-user-friendlier-page-3mcf</guid>
      <description>&lt;p&gt;As we say in Czech “blacksmith’s mare walks barefoot” (or “the shoemaker’s children go barefoot” in English), my previous &lt;a href="https://tzemanovic.gitlab.io/"&gt;homepage&lt;/a&gt; with its Bootstrap based style looked admittedly so terrible that I myself didn’t enjoy looking at it anymore.&lt;/p&gt;

&lt;p&gt;I finally found some time to give it much needed revamp. Also, many current developments in our industry are, to put it lightly, less than ideal and I wanted to make sure I am not just adding more fuel to the fire. It’s not just the things we can see straight away&lt;sup&gt;1&lt;/sup&gt;, which are easier to laugh off, but more importantly the things that are hidden from most people’s sight&lt;sup&gt;2&lt;/sup&gt;. In that spirit, all the content on this site is now self-hosted (well, except for the comments, 🤔, maybe I’ll setup something like &lt;a href="https://github.com/Libbum/oration"&gt;this self-hosted commenting system&lt;/a&gt; one day).&lt;/p&gt;

&lt;p&gt;To keep things simple, without making it &lt;a href="https://bestmotherfucking.website/"&gt;too good&lt;/a&gt;, I’ve used &lt;a href="https://purecss.io/"&gt;Pure.css&lt;/a&gt; with its small, responsive modules. It is nice, but quite frankly, even though I’ve been making websites since my childhood, going back to CSS has been a total pain in the ass (even for something as simple as this website) after being spoilt with the awesome &lt;a href="https://package.elm-lang.org/packages/mdgriffith/elm-ui/latest/"&gt;elm-ui&lt;/a&gt; (previously style-elements) that I’ve been using at work for well over a year. But the best thing about using Elm has really been its welcoming, friendly and inclusive community.&lt;/p&gt;

&lt;p&gt;I’ve also added a simple &lt;a href="https://gitlab.com/tzemanovic/tzemanovic.gitlab.io/blob/master/src/Main.hs#L117"&gt;way to estimate reading time&lt;/a&gt; for the blog posts. If you’re interested, you can see the source for this page on &lt;a href="https://gitlab.com/tzemanovic/tzemanovic.gitlab.io"&gt;GitLab&lt;/a&gt;. Feel free to use any of it for your own page.&lt;/p&gt;




&lt;ol&gt;
&lt;li id="fn1"&gt;&lt;p&gt;&lt;a href="https://twitter.com/darylginn/status/1053646859686809600"&gt;Daryl Ginn on Twitter: “Every website in 2018…”&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn2"&gt;&lt;p&gt;&lt;a href="https://www.neustadt.fr/essays/against-a-user-hostile-web/"&gt;Against an Increasingly User-Hostile Web&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>userhostileweb</category>
      <category>hakyll</category>
      <category>purecss</category>
      <category>brunch</category>
    </item>
    <item>
      <title>RealWorld example with Haskell Yesod</title>
      <dc:creator>Tomáš Zemanovič</dc:creator>
      <pubDate>Tue, 14 Aug 2018 00:00:00 +0000</pubDate>
      <link>https://dev.to/tzemanovic/realworld-example-with-haskell-yesod-53b8</link>
      <guid>https://dev.to/tzemanovic/realworld-example-with-haskell-yesod-53b8</guid>
      <description>&lt;p&gt;This is an overview of an &lt;a href="https://github.com/tzemanovic/haskell-yesod-realworld-example-app"&gt;example implementation&lt;/a&gt; of &lt;a href="https://realworld.io/"&gt;the RealWorld&lt;/a&gt; backend built using the powerful &lt;a href="https://www.yesodweb.com/"&gt;Yesod framework&lt;/a&gt; written in Haskell.&lt;/p&gt;

&lt;p&gt;This project is essentially a RESTful API to a database and even though Yesod can do much more than that, you still get a lot of nice things that help along the way. For example, Yesod comes with some helper commands for common tasks (e.g. you can add a new handler using &lt;code&gt;yesod add-handler&lt;/code&gt;) and you can start a new project using one of the &lt;a href="https://docs.haskellstack.org/en/stable/GUIDE/#templates"&gt;stack templates&lt;/a&gt;. I’ve started this project with &lt;code&gt;stack new yesod-sqlite&lt;/code&gt; which scaffolded application with SQLite database connection, whose schema is created from &lt;a href="https://github.com/tzemanovic/haskell-yesod-realworld-example-app/blob/8411fa8a2ae8c2061323e58eaedd611186cf1394/app/config/models"&gt;persistent entity file&lt;/a&gt;. The scaffolded project is setup with:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;development server setup using ghcid with automatic rebuild and fast reloads&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/hpack"&gt;hpack&lt;/a&gt; for a nicer alternative to the Cabal package format&lt;/li&gt;
&lt;li&gt;behaviour specification using &lt;a href="https://hackage.haskell.org/package/hspec"&gt;hspec&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;fast and scalable logging using &lt;a href="https://hackage.haskell.org/package/fast-logger"&gt;fast-logger&lt;/a&gt; for requests and database queries&lt;/li&gt;
&lt;li&gt;log functions from &lt;a href="https://hackage.haskell.org/package/monad-logger"&gt;monad-logger&lt;/a&gt; that includes source code location in the log entries&lt;/li&gt;
&lt;li&gt;the fast &lt;a href="https://hackage.haskell.org/package/warp"&gt;Warp&lt;/a&gt; web server&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/classy-prelude"&gt;classy-prelude&lt;/a&gt; as an alternative prelude that removes all partial functions&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/persistent"&gt;persistent&lt;/a&gt; for type-safe database-agnostic data modelling and querying with automatic migrations in development&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/aeson"&gt;aeson&lt;/a&gt; for fast JSON parsing and encoding &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/keter"&gt;keter&lt;/a&gt; deployment system&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you want to learn more about Yesod, you can read the excellent &lt;a href="https://www.yesodweb.com/book"&gt;Developing Web Applications with Haskell and Yesod&lt;/a&gt; for free. Some other dependencies used in this project are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/esqueleto"&gt;esqueleto&lt;/a&gt; - type-safe EDSL for SQL queries on persistent backends&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/forma"&gt;forma&lt;/a&gt; - parse and validate form input&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/jwt"&gt;jwt&lt;/a&gt; - JSON Web Token (JWT) decoding and encoding &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://hackage.haskell.org/package/weeder"&gt;weeder&lt;/a&gt; - to detect dead code&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Project structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;app
├── app
├── package.yaml
│   ├── main.hs                     &lt;span class="s2"&gt;"The main entry point for production build."&lt;/span&gt;
│   ├── devel.hs                    &lt;span class="s2"&gt;"The main for development server."&lt;/span&gt;
│   └── DevelMain.hs                &lt;span class="s2"&gt;"The main for running inside GHCi."&lt;/span&gt;
├── config
│   ├── models                      &lt;span class="s2"&gt;"Persistent entity file with the database schema declaration."&lt;/span&gt;
│   ├── routes                      &lt;span class="s2"&gt;"Routes declaration for our RESTful API."&lt;/span&gt;
│   ├── settings.yml                &lt;span class="s2"&gt;"App runtime settings."&lt;/span&gt;
│   └── test-settings.yml           &lt;span class="s2"&gt;"Settings overrides for tests."&lt;/span&gt;
├── src
│   ├── Application.hs              &lt;span class="s2"&gt;"Loads the settings to initalize the app with a HTTP manager,"&lt;/span&gt;
│   │                               &lt;span class="s2"&gt;"logger and database connection pool."&lt;/span&gt;
│   │
│   ├── Foundation.hs               &lt;span class="s2"&gt;"Declares the foundation 'App' datatype which is accessible"&lt;/span&gt;
│   │                               &lt;span class="s2"&gt;"from every handler, type for routes loaded from &lt;/span&gt;&lt;span class="sb"&gt;`&lt;/span&gt;config/routes&lt;span class="sb"&gt;`&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
│   │                               &lt;span class="s2"&gt;"and authentication requirements for each route."&lt;/span&gt;
│   │
│   ├── Settings.hs                 &lt;span class="s2"&gt;"Declares and loads the app settings, which can be loaded from"&lt;/span&gt;
│   │                               &lt;span class="s2"&gt;"various sources."&lt;/span&gt;
│   │
│   ├── Import.hs                   &lt;span class="s2"&gt;"Commonly used module imports grouped for convenience."&lt;/span&gt;
│   ├── Model.hs                    &lt;span class="s2"&gt;"Generates types for models loaded from &lt;/span&gt;&lt;span class="sb"&gt;`&lt;/span&gt;config/models&lt;span class="sb"&gt;`&lt;/span&gt;&lt;span class="s2"&gt;."&lt;/span&gt;
│   ├── Database.hs                 &lt;span class="s2"&gt;"Database queries."&lt;/span&gt;
│   ├── Pagination.hs
│   ├── Handler                     &lt;span class="s2"&gt;"Handlers for the RESTful API."&lt;/span&gt;
│   │   ├── Articles.hs
│   │   ├── Profiles.hs
│   │   └── User.hs
│   ├── Database                    &lt;span class="s2"&gt;"Helpers for dealing with database."&lt;/span&gt;
│   │   └── Persist
│   │       ├── Extended.hs
│   │       └── Types
│   │           ├── Email           &lt;span class="s2"&gt;"Persistent field type for email, which is"&lt;/span&gt;
│   │           │   └── Internal.hs &lt;span class="s2"&gt;"stored in a case-insensitive string."&lt;/span&gt;
│   │           ├── Email.hs
│   │           ├── Password        &lt;span class="s2"&gt;"Persistent field type for password,"&lt;/span&gt;
│   │           │   └── Internal.hs &lt;span class="s2"&gt;"stored as a hash."&lt;/span&gt;
│   │           └── Password.hs
│   ├── Auth                        &lt;span class="s2"&gt;"Authentication using JWT token."&lt;/span&gt;
│   │   └── JWT.hs
│   └── Web                         &lt;span class="s2"&gt;"User input validation."&lt;/span&gt;
│       └── Forma
│           └── Extended.hs
├── &lt;span class="nb"&gt;test&lt;/span&gt;                            &lt;span class="s2"&gt;"The specs for user and profiles handlers."&lt;/span&gt;
│   ├── Handler
│   │   ├── ProfilesSpec.hs
│   │   └── UserSpec.hs
│   ├── Spec.hs
│   └── TestImport.hs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Some notes
&lt;/h2&gt;

&lt;p&gt;The handlers are implemented according to the &lt;a href="https://github.com/gothinkster/realworld/tree/master/api"&gt;API spec&lt;/a&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;Profiles&lt;/code&gt; module is the most simple one with handlers using persistent queries&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;User&lt;/code&gt; handlers deal with user input that is parsed and validated using the forma library&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;Articles&lt;/code&gt; handlers contain more complex queries and pagination for the article feed. Because their queries deal with multiple tables, I reached out to the esqueleto library, which provides a nice eDSL (a SQL language embedded in Haskell) for querying the database.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>haskell</category>
      <category>yesod</category>
      <category>rest</category>
      <category>example</category>
    </item>
    <item>
      <title>Functional programming for beginners</title>
      <dc:creator>Tomáš Zemanovič</dc:creator>
      <pubDate>Mon, 19 Mar 2018 00:00:00 +0000</pubDate>
      <link>https://dev.to/tzemanovic/functional-programming-for-beginners-2nh3</link>
      <guid>https://dev.to/tzemanovic/functional-programming-for-beginners-2nh3</guid>
      <description>&lt;p&gt;Recently, I attended &lt;a href="http://justtesting.org" rel="noopener noreferrer"&gt;Manuel Chakravarty&lt;/a&gt;’s YOW! night talk titled Demystifying Functional Programming, which inspired me to write this post.&lt;/p&gt;

&lt;p&gt;From my work, I gained some intuition that trying to teach FP by explaining the theory first didn’t work well. In hindsight, this seems almost obvious. A lot of us were taught math this way and sadly it has left many of us misunderstanding math or even despising it, even though it might be very useful in their chosen field&lt;sup&gt;1&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;What worked better was to show how elegantly FP solves many problems we were focusing on; one that required a use of parsers or another for which we were using reactive programming to process and analyse large quantities of data in real-time. These were some of the concepts I’ve learned in Haskell and was able to apply in Scala. They were harder to implement in the imperative way, which only complected them and that also made them harder to understand.&lt;/p&gt;

&lt;p&gt;My intuition really aligned with the content of Manuel’s talk. With his long-time experience and commitment to working with and teaching Haskell, Manuel discussed what we can do to advance FP from the stage of innovators and early adopters to early majority&lt;sup&gt;2&lt;/sup&gt;, which he summarised as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Examples first&lt;/li&gt;
&lt;li&gt;Teach design patterns&lt;/li&gt;
&lt;li&gt;Tight feedback loop&lt;/li&gt;
&lt;li&gt;Visualisation can be an effective tool&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Another seasoned Haskeller Gabriel Gonzalez has written some great advice for Haskell beginners&lt;sup&gt;3&lt;/sup&gt;, in which he recommends to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Avoid big-design-up-front&lt;/li&gt;
&lt;li&gt;Start programming at term-level (using simple values and functions)&lt;/li&gt;
&lt;li&gt;Build something useful&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you gave Haskell a try, but still find it too intimidating, I would recommend you having a look at Elm. Elm (which itself is written in Haskell) is a very small language in terms of the size of its grammar, which makes it a perfect fit for beginners. Not only is it very good at all the points above, it can also compete with other front-end frameworks like React. The whole notion of languages being general-purpose can be quite misleading&lt;sup&gt;4&lt;/sup&gt;, Elm is intentionally not a general-purpose language&lt;sup&gt;5&lt;/sup&gt; and it serves its intended purpose very well. You don’t have to take my word for it though, instead, you can watch a &lt;a href="https://youtu.be/EStQa0QsUb8" rel="noopener noreferrer"&gt;talk by Richard Feldman&lt;/a&gt;, who’s been using both React and Elm side-by-side in production for over a year.&lt;/p&gt;

&lt;p&gt;Cool, you got me, but…&lt;/p&gt;

&lt;h2&gt;
  
  
  Where do you start?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Ftzemanovic.github.io%2Fimages%2Felm-grove.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Ftzemanovic.github.io%2Fimages%2Felm-grove.jpg" alt="Welcome to Elm"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Of course, not everyone learns the same way. As a general recommendation I would say:&lt;/p&gt;

&lt;p&gt;Try not to learn too many things at once, keep things simple. This is especially important if you come to FP &lt;strong&gt;with prior experience&lt;/strong&gt; from imperative languages, which doesn’t translate well into FP concepts. You might have heard functional programmers say that when you start, you will have to unlearn things, and this is what they’re referring to. Honestly, you will need patience, because everything might seem slow at first. That’s okay, don’t give up and keep at it!&lt;/p&gt;

&lt;p&gt;Try to find someone who already has experience with FP and ask them for help with writing something simple. When you see FP applied to solving a real problem, you are very likely to learn faster. There are people who say they were able to pick up Elm this way within a week, but don’t set your expectations too high. Once again, everyone’s learning path is different. Look for FP &lt;a href="https://www.meetup.com/" rel="noopener noreferrer"&gt;meetups&lt;/a&gt; in your area, join &lt;a href="https://elmlang.herokuapp.com/" rel="noopener noreferrer"&gt;Elm on Slack&lt;/a&gt;, read the comprehensive &lt;a href="https://guide.elm-lang.org/" rel="noopener noreferrer"&gt;Elm Guide&lt;/a&gt;. Don’t start trying to write a full-blown single page app, there are ways to &lt;a href="http://elm-lang.org/blog/how-to-use-elm-at-work" rel="noopener noreferrer"&gt;gradually introduce Elm at work today&lt;/a&gt;. Or you can just play around &lt;a href="http://ellie-app.com/" rel="noopener noreferrer"&gt;directly from your browser&lt;/a&gt;, you don’t even have to install anything.&lt;/p&gt;

&lt;p&gt;Lastly, don’t be afraid to make mistakes, for it’s an important part of any learning process.&lt;/p&gt;




&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://lamport.azurewebsites.net/tla/math-knowledge.html" rel="noopener noreferrer"&gt;Leslie Lamport: Why Don’t Computer Scientists Learn Math?&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Diffusion_of_innovations" rel="noopener noreferrer"&gt;Wikipedia: Diffusion of innovations&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://www.haskellforall.com/2017/10/advice-for-haskell-beginners.html" rel="noopener noreferrer"&gt;Gabriel Gonzalez: Advice for Haskell beginners&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://worrydream.com/ClimateChange/#tools-modeling" rel="noopener noreferrer"&gt;Bret Victor: What can a technologist do about climate change? A personal view.&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://github.com/elm-lang/projects/blob/master/notes/on-general-purpose.md" rel="noopener noreferrer"&gt;Evan Czaplicki: On “General-Purpose” Languages&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>functional</category>
      <category>beginners</category>
    </item>
    <item>
      <title>One year of Elm in production</title>
      <dc:creator>Tomáš Zemanovič</dc:creator>
      <pubDate>Tue, 06 Mar 2018 00:00:00 +0000</pubDate>
      <link>https://dev.to/tzemanovic/one-year-of-elm-in-production-4a4</link>
      <guid>https://dev.to/tzemanovic/one-year-of-elm-in-production-4a4</guid>
      <description>&lt;p&gt;About a year ago, I started a new job where I build tools aimed at helping others provide a better user experience. As is common in the software industry, I inherited lots of poor vanilla JavaScript code. There were no tests, very little code structure or code re-use, mixed coding styles and as expected, a full menagerie of bugs, which frequently cropped up resulting in very poor user experience. With such a sorry state of things, it only made sense to try to take a wholly different approach - stop writing JavaScript and instead pick a higher level language that would make sure all the things are kept in check.&lt;/p&gt;

&lt;p&gt;As a functional programming enthusiast, I’ve been a keen user of Elm for some time and although I conceptually liked it better before version 0.17 with its higher-level abstraction of rendering visual elements contained in &lt;a href="http://package.elm-lang.org/packages/evancz/elm-graphics/1.0.1"&gt;elm-graphics library&lt;/a&gt;, the inclusion of HTML library made it possible to integrate it into existing front-end ecosystem with much less friction to the point where it actually became one of the top choices.&lt;/p&gt;

&lt;p&gt;If Elm code looks terrifyingly unfamiliar to you, fear not. It builds on top of very mature ML (Meta Language) family of programming languages. Elm itself is written in Haskell, which is as old as programming itself, but you can find a plethora of languages in this family:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="http://www.purescript.org/"&gt;PureScript&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;front-end language, more similar to Haskell&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://www.idris-lang.org/"&gt;Idris&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;general purpose language similar to Haskell, but with dependent types&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://www.scala-lang.org/"&gt;Scala&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;fusion of FP with OOP for the JVM&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="http://www.frege-lang.org/"&gt;Frege&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;Haskell for the JVM&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://eta-lang.org/"&gt;Eta&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;Haskell for the JVM&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://ocaml.org/"&gt;OCaml&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;FP with OOP&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="http://fsharp.org/"&gt;F#&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;Microsoft’s FP with OOP&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="https://github.com/Morgan-Stanley/hobbes"&gt;Hobbes&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;custom language built for embedding in C++&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href="http://sml-family.org/"&gt;Standard ML&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;general purpose popular language for compilers&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;As processors scaling predicted by Moore’s law is close to reaching its hard physical limits (as Herb Sutter famously put it the free lunch is over&lt;sup&gt;1&lt;/sup&gt;), the software industry will have to reach to tools that are better suited for dealing with concurrency. And these tools are functional programming languages. The interesting thing is that even if your application has no need to deal with concurrency, it can still benefit from FP, its foundation in mathematical concepts scares a lot people off, but it is its strong point. If the word mathematical puts you off, know that you don’t actually have to know about this to take advantage of it, just like you won’t fly off a rollercoaster if you don’t know its physics (anecdotally, it will probably be your last ride if the rollercoaster has been built with complete ignorance of physics).&lt;/p&gt;

&lt;p&gt;As most of software development education and training focuses on OOP, there are lots of developers who get the impression that thinking about things in terms of objects is somehow natural. But the limitation of this mindset becomes very apparent in a very popular OOP topic - Gang of Four’s design patterns&lt;sup&gt;2&lt;/sup&gt;. It also becomes apparent when implementation becomes so complex that no one can or even wants to work with it anymore. But where does this complexity come from, is it intrinsic to the problem domain? Most programmers know that tight coupling between unrelated concepts creates problems, in the same spirit I would say that the interleaving of data with behavior inside classes can create more problems than it solves. The declarative nature of FP languages removes much of the incidental complexity, the elephant we’re dragging around&lt;sup&gt;3&lt;/sup&gt;, introduced by imperative programs because we don’t need to think about execution to understand what is going on. In more conceptual words of professor Philip Wadler, some languages were discovered while others were invented&lt;sup&gt;4&lt;/sup&gt; and you can tell.&lt;/p&gt;

&lt;p&gt;The nice thing about Elm is that the community that has formed around it is very inclusive and welcoming. The language itself is very beginner friendly, to the point where some mistake its simplicity for a toy language. Don’t make the same mistake though, because Elm is up there with big names such as React, in fact, it is much more a complete solution than React. The simplicity of Elm is rooted in hard work that has been put into its design.&lt;/p&gt;

&lt;p&gt;Once you familiarize yourself with it, the Elm compiler will be your best friend. Its error messages are so clear and helpful that they’ve influenced other languages, such as Rust. The language comes with a package manager &lt;a href="https://github.com/elm-lang/elm-package"&gt;elm-package&lt;/a&gt; and the libraries released in Elm automatically adhere to semantic versioning. You can even use it to &lt;a href="https://github.com/elm-lang/elm-package#updating-dependencies"&gt;check what has changed between different versions of a given package&lt;/a&gt;. For interactive coding, there is &lt;a href="https://github.com/elm-lang/elm-repl"&gt;elm-repl&lt;/a&gt; and &lt;a href="https://github.com/elm-lang/elm-reactor"&gt;elm-reactor&lt;/a&gt;. The performance of Elm generated code is great and when needed optimization is a simple function call away.&lt;/p&gt;

&lt;p&gt;So far, Elm’s simple yet powerful design has helped us to stay focused on our goal of building a great product and we expect that the payoff will be even greater in the long run. At the moment, we have about 16k Elm lines of code in production, steadily translating pleasant development experience into pleasant user experience and we have more on their way.&lt;/p&gt;




&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://www.gotw.ca/publications/concurrency-ddj.htm"&gt;Herb Sutter: The Free Lunch Is Over&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://youtu.be/oB8jN68KGcU"&gt;Ted Newark: Why Functional Programming Matters @ Devoxx Poland 2016&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://youtu.be/rI8tNMsozo0"&gt;Rich Hickey: Simplicity Matters keynote @ Rails Conf 2012&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://youtu.be/IOiZatlZtGU"&gt;Philip Wadler: Propositions as Types @ Strange Loop 2015&lt;/a&gt;↩&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>elm</category>
      <category>functional</category>
    </item>
  </channel>
</rss>
