<?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: Serokell</title>
    <description>The latest articles on DEV Community by Serokell (@serokell).</description>
    <link>https://dev.to/serokell</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%2F542408%2Fb27d70ed-cf94-4eea-ab90-62b4b8c32af2.jpg</url>
      <title>DEV Community: Serokell</title>
      <link>https://dev.to/serokell</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/serokell"/>
    <language>en</language>
    <item>
      <title>Rust vs. Haskell</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 14 Feb 2023 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/rust-vs-haskell-2a44</link>
      <guid>https://dev.to/serokell/rust-vs-haskell-2a44</guid>
      <description>&lt;p&gt;Rust and Haskell don’t shy away from powerful features. As a result, both languages have steep learning curves compared with other languages. Trying to learn Rust or Haskell can be frustrating, especially in the first couple of months.&lt;/p&gt;

&lt;p&gt;But if you already know Rust, you have a head start with Haskell; and vice versa.&lt;/p&gt;

&lt;p&gt;In this article, we want to show how knowledge of one of these languages can help you get up to speed with another.&lt;/p&gt;

&lt;p&gt;We won’t cover all the similarities or differences and won’t talk about language domains. Our main goal is to show the bridge between the languages; you can decide whether you want to walk it.&lt;/p&gt;

&lt;p&gt;We won’t cover syntax as well, but get ready to switch between indentation and braces, as well as read code in opposite directions. 😉&lt;/p&gt;

&lt;h2&gt;
  
  
  Basic concepts
&lt;/h2&gt;

&lt;p&gt;Haskell and Rust have both been influenced by the &lt;a href="https://en.wikipedia.org/wiki/ML_(programming_language)"&gt;ML&lt;/a&gt; programming language. ML has strong static typing with type inference, and so do Haskell and Rust.&lt;/p&gt;

&lt;p&gt;There are other similarities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;algebraic data types;&lt;/li&gt;
&lt;li&gt;pattern matching;&lt;/li&gt;
&lt;li&gt;parametric polymorphism;&lt;/li&gt;
&lt;li&gt;ad-hoc polymorphism.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We’ll cover all of these later in the article, but first, let’s talk about compilers. Both languages focus on safety – they are extremely good at compile-time checks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Type system
&lt;/h3&gt;

&lt;p&gt;If you’re coming from one of these languages, we don’t have to convince you that types are our friends: they help us avoid silly mistakes and reduce the number of bugs.&lt;/p&gt;

&lt;p&gt;Rust and Haskell have similar type systems. Both support conventional basic types, such as integers, floats, booleans, strings, etc. Both make it easy to create new types, use newtypes, and type aliases.&lt;/p&gt;




&lt;p&gt;🙂 When using strings, Rust beginners puzzle over &lt;code&gt;String&lt;/code&gt; vs. &lt;code&gt;&amp;amp;str&lt;/code&gt;, and Haskell beginners puzzle over &lt;code&gt;String&lt;/code&gt; vs. &lt;code&gt;Text&lt;/code&gt; vs. &lt;code&gt;ByteString&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;Rust can infer types when possible.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bools = vec![true, false, true];
let not_head = bools[0].not(); // false, has type bool

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But omitting function parameter types is not allowed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn get_double_head(ints) {
// ^ error: expected one of `:`, `@`, or `|`
// note: anonymous parameters are removed in the 2018 edition (see RFC 1685)
// help: if this is a parameter name, give it a type
// help: if this is a type, explicitly ignore the parameter name
    ints[0] * 2
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Omitting function return types is also not allowed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn get_double_head(ints: Vec&amp;lt;i32&amp;gt;) {
    ints[0] * 2
// ^^^^^^^^^^^ expected `()`, found `i32`
// help: try adding a return type: `-&amp;gt; i32`
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Rust, we always have to specify both:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn get_double_head(ints: Vec&amp;lt;i32&amp;gt;) -&amp;gt; i32 {
    ints[0] * 2
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Haskell can infer types when they’re not ambiguous.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bools = [True, False, True]
let notHead = not (head bools) -- False, has type Bool

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We don’t have to annotate function parameters and return types.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getDoubleHead ints =
  head ints * 2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it usually results in a warning, and adding a type signature is a good practice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getDoubleHead :: [Integer] -&amp;gt; Integer
getDoubleHead ints =
  head ints * 2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 &lt;strong&gt;Note:&lt;/strong&gt; You can test the Haskell code snippets by pasting them in the &lt;a href="https://downloads.haskell.org/ghc/latest/docs/users_guide/ghci.html"&gt;REPL&lt;/a&gt;. Rust doesn’t have an interactive environment, so you have to reorganize the snippets and use the &lt;code&gt;main&lt;/code&gt; function if you want to give them a try.&lt;/p&gt;




&lt;h3&gt;
  
  
  Variables and mutability
&lt;/h3&gt;

&lt;p&gt;Rust variables are, by default, immutable – when you want a mutable variable, you have to be explicit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let immutable_x: i32 = 3;
    immutable_x = 1;
// ^^^^^^^^^^^^^^^ error: cannot assign twice to immutable variable


let mut mutable_x = 3; // 3
mutable_x = 1; // 1
mutable_x += 4; // 5

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are no mutable variables in Haskell – the syntax has no such thing as a reassignment statement. However, the value to which the variable is bound may be a mutable cell, such as &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/Data-IORef.html"&gt;&lt;code&gt;IORef&lt;/code&gt;&lt;/a&gt;, &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/Data-STRef.html"&gt;&lt;code&gt;STRef&lt;/code&gt;&lt;/a&gt;, or &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/Control-Concurrent-MVar.html"&gt;&lt;code&gt;MVar&lt;/code&gt;&lt;/a&gt;. The type system tracks mutability, and Haskell does not require a separate &lt;code&gt;mut&lt;/code&gt; keyword.&lt;/p&gt;




&lt;p&gt;💡 Note that Haskell allows name shadowing. But it’s discouraged and can be caught with a warning.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let immutable_x = 3
let immutable_x = 1
-- ^^^^^^^^^^^ warning
-- This binding for ‘immutable_x’ shadows the existing binding

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Rust, name shadowing is considered idiomatic. For example, the following code snippet reuses &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&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;// parse a string of the form "42,20"
let (x, y) = s.split_once(',').unwrap();
let x: i32 = x.parse().unwrap();
let y: i32 = y.parse().unwrap();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Haskell relies heavily on purely functional data structures, operations on which return new versions of data structures, while the original reference stays unmodified and valid.&lt;/p&gt;

&lt;p&gt;For example, if we have a map and want to do some operation on a slightly modified map, we can have a value that keeps the old map but also works with the new map (without much performance cost).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import qualified Data.HashMap.Strict as HashMap

let old = HashMap.fromList [("Donut", 1.0), ("Cake", 1.2)]
let new = HashMap.insert "Cinnamon roll" 2.25 old

print old
-- Prints: fromList [("Cake", 1.2),("Donut", 1.0)]
print new
-- Prints: fromList [("Cake",1.2),("Cinnamon roll", 2.25),("Donut", 1.0)]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 Yes, that’s how Haskell prints a map. Yes, it’s weird.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/Prelude.html#v:print"&gt;&lt;code&gt;print&lt;/code&gt;&lt;/a&gt; function converts values to strings by using &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/Prelude.html#v:show"&gt;&lt;code&gt;show&lt;/code&gt;&lt;/a&gt; and outputs it to the standard output. The result of &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/Prelude.html#t:Show"&gt;&lt;code&gt;show&lt;/code&gt;&lt;/a&gt; is a syntactically correct Haskell expression, which can be pasted right into the code.&lt;/p&gt;




&lt;p&gt;In Rust, standard operations mutate the collection, so there’s no way to access its state before the modification.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::collections::HashMap;

let mut prices = HashMap::from([("Cake", 1.2), ("Donut", 1.0)]);
prices.insert("Cinnamon roll", 2.25);

println!("{:?}", prices); 
// Prints: {"Cake": 1.2, "Donut": 1.0, "Cinnamon roll": 2.25}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;💡 What is &lt;code&gt;{:?}&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can use it to debug-format any type. It relies on the &lt;a href="https://doc.rust-lang.org/std/fmt/trait.Debug.html"&gt;&lt;code&gt;fmt::Debug&lt;/code&gt;&lt;/a&gt; trait, which &lt;strong&gt;should&lt;/strong&gt; be implemented for all public types.&lt;/p&gt;




&lt;p&gt;If we want to emulate Haskell when working with default collections, we have to &lt;a href="https://doc.rust-lang.org/std/clone/trait.Clone.html"&gt;&lt;code&gt;clone&lt;/code&gt;&lt;/a&gt; the old one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::collections::HashMap;

let old = HashMap::from([("Cake", 1.2), ("Donut", 1.0)]);
let mut new = HashMap::new();

new.clone_from(&amp;amp;old);
new.insert("Cinnamon roll", 2.25);

println!("{:?}", old); 
// Prints: {"Cake": 1.2, "Donut": 1.0}
println!("{:?}", new); 
// Prints: {"Cake": 1.2, "Donut": 1.0, "Cinnamon roll": 2.25}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 Note that persistent data structures in Haskell are usually designed for cheap cloning, so most operations have &lt;code&gt;O(log n)&lt;/code&gt; complexity. In Rust, we don’t tend to clone that often, so access and mutation typically have &lt;code&gt;O(1)&lt;/code&gt; and cloning – &lt;code&gt;O(n)&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;💡 Haskell has mutable constructs (such as &lt;a href="https://hackage.haskell.org/package/array-0.5.4.0/docs/Data-Array-ST.html"&gt;&lt;code&gt;STArray&lt;/code&gt;&lt;/a&gt; and &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/Data-IORef.html"&gt;&lt;code&gt;IORef&lt;/code&gt;&lt;/a&gt;), which you can use when you need mutability.&lt;/p&gt;




&lt;h2&gt;
  
  
  Algebraic data types (ADTs)
&lt;/h2&gt;

&lt;p&gt;In simple terms, ADTs are a way to construct types. Haskell uses the single keyword &lt;code&gt;data&lt;/code&gt; to declare product and sum types, while Rust uses &lt;code&gt;struct&lt;/code&gt; and &lt;code&gt;enum&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To learn more about algebraic data types, check out our &lt;a href="https://serokell.io/blog/algebraic-data-types-in-haskell"&gt;article on ADTs&lt;/a&gt; in Haskell.&lt;/p&gt;

&lt;h3&gt;
  
  
  Product types (structs)
&lt;/h3&gt;

&lt;p&gt;In Rust, product types are represented by structs, which come in two forms:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;tuple structs;&lt;/li&gt;
&lt;li&gt;structs with named fields.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A tuple struct has no names:
struct SimpleItem(String, f64);

// A struct has named fields: 
#[derive(Debug)]
struct Item {
    name: String,
    price: f64,
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which is quite similar to Haskell’s datatypes and records.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- A simple datatype with no names:
data SimpleItem = SimpleItem String Double

-- A record has named fields: 
data Item = Item
  { name :: String
  , price :: Double
  }
  deriving (Show)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that &lt;code&gt;#[derive(Debug)]&lt;/code&gt; corresponds to &lt;code&gt;deriving (Show)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In Haskell, we have to provide a type constructor (the name of our type) and a data constructor (used to construct new instances of the type), which are the same as in the previous snippet.&lt;/p&gt;

&lt;h4&gt;
  
  
  Creating instances of types
&lt;/h4&gt;

&lt;p&gt;We can create instances of product types. In Rust:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creating a tuple struct:
let simple_donut = SimpleItem("Donut".to_string(), 1.0);

// Creating an ordinary struct:
let cake = Item {
    name: "Cake".to_string(),
    price: 1.2,
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Haskell:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Creating an ordinary datatype:
let simpleDonut = SimpleItem "Donut" 1.0

-- Creating a record:
let donut = Item "Donut" 1.0
let cake = Item{name = "Cake", price = 1.2}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can use either the ordinary syntax or the record syntax to create records in Haskell.&lt;/p&gt;

&lt;h4&gt;
  
  
  Getting field values
&lt;/h4&gt;

&lt;p&gt;In Rust, we can get the value of a field by using dot notation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let cake_price = cake.price;
println!("It costs {}", cake_price); 
// Prints: "It costs 1.2"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Haskell, we have been using field accessors (basically, getters), such as &lt;code&gt;price&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;let cakePrice = price cake
print $ "It costs " ++ show cakePrice 
-- Prints: "It costs 1.2"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But since GHC 9.2, we can use dot notation as well.&lt;/p&gt;




&lt;p&gt;💡GHC is the Glasgow Haskell Compiler, the most commonly used Haskell compiler.&lt;/p&gt;






&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let cakePrice = cake.price
print $ "It costs " ++ show cakePrice 
-- Prints: "It costs 1.2"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;🤑 What is &lt;code&gt;$&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use the dollar sign (&lt;code&gt;$&lt;/code&gt;) to avoid parentheses.&lt;/p&gt;

&lt;p&gt;Function application has higher precedence than most binary operators. The following usage results in a compilation error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- These are the same:
print "It costs " ++ show cakePrice

(print "It costs ") ++ (show cakePrice)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;$&lt;/code&gt; is also a function application operator (&lt;code&gt;f $ x&lt;/code&gt; is the same as &lt;code&gt;f x&lt;/code&gt;). But it has very low precedence. The following usage works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- These are the same:
print $ "It costs " ++ show cakePrice

print ("It costs " ++ show cakePrice)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h4&gt;
  
  
  Updating field values
&lt;/h4&gt;

&lt;p&gt;In Rust, if the struct variable is mutable, we can change its values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut cake = Item {
    name: "Cake".to_string(),
    price: 1.2,
};

cake.price = 1.4;

println!("{:?}", cake); 
// Prints: Item { name: "Cake", price: 1.4 }    

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Haskell, a record update returns another record, and the original one stays unchanged (as we’ve covered in the mutability section).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let cake = Item{name = "Cake", price = 1.2}

let updatedCake = cake{price = 1.4}

print cake
-- Prints: Item {name = "Cake", price = 1.2}
print updatedCake
-- Prints: Item {name = "Cake", price = 1.4}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we want to do something similar in Rust, we can use struct update syntax to copy and modify a struct.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pricy_cake = Item { price: 1.6, ..cake };

println!("{:?}", pricy_cake);
// Prints: Item { name: "Cake", price: 1.6 }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both languages have a simplified field initialization syntax if there are matching names in scope:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let name = "Cinnamon roll".to_string();
let price = 2.25;

let cinnamon_roll = Item { name, price }; // instead of “name: name”

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use it in Haskell, you have to enable &lt;a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/control.html#extension-GHC2021"&gt;&lt;code&gt;GHC2021&lt;/code&gt;&lt;/a&gt; or the &lt;a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/record_puns.html"&gt;&lt;code&gt;NamedFieldPuns&lt;/code&gt;&lt;/a&gt; extension.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let name = "Cinnamon roll"
let price = 2.25

let cinnamonRoll = Item{name, price} -- instead of “name = name”

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Sum types (enums)
&lt;/h3&gt;

&lt;p&gt;Here is an example of a simple sum type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(Debug)]
enum DonutType {
    Regular,
    Twist,
    ButtermilkBar,
}

let twist = DonutType::Twist;


data DonutType = Regular | Twist | ButtermilkBar
  deriving (Show)

let twist = Twist

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The variants don’t have to be boring and can contain fields (which can be unnamed or named).&lt;/p&gt;

&lt;p&gt;For example, we can have a &lt;code&gt;Donut&lt;/code&gt; with &lt;code&gt;DonutType&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;#[derive(Debug)]
enum Pastry {
    Donut(DonutType),
    Croissant,
    CinnamonRoll,
}

let twist_donut = Pastry::Donut(DonutType::Twist);


data Pastry
  = Donut DonutType
  | Croissant
  | CinnamonRoll
  deriving (Show)

let twistDonut = Donut Twist

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Partial field accessors
&lt;/h4&gt;

&lt;p&gt;Haskell allows partial field accessors, while Rust does not.&lt;/p&gt;

&lt;p&gt;For example, let’s take &lt;code&gt;Croissant&lt;/code&gt;: the &lt;code&gt;price&lt;/code&gt; field is present in both constructors, while &lt;code&gt;filling&lt;/code&gt; is present only in &lt;code&gt;WithFilling&lt;/code&gt;. In Rust, we get a compilation error when we try to access the filling of a plain croissant. In Haskell, we get a runtime error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Croissant {
    Plain { price: f64 },
    WithFilling { filling: String, price: f64 },
}

let plain = Croissant::Plain { price: 1.75 };

println!("{}", plain.price)
// ^^^^^
// error[E0609]: no field `price` on type `Croissant`


data Croissant
  = Plain {price :: Double}
  | WithFilling {filling :: String, price :: Double}

let plain = Plain 1.75

-- This is ok and works as expected:
print $ price plain
-- Prints: 1.75

-- This is not
print $ filling plain
-- runtime error: No match in record selector filling

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Pattern matching
&lt;/h3&gt;

&lt;p&gt;We could have used pattern matching to deconstruct values in the previous snippets. To illustrate this, let’s create a function that returns a receipt for a croissant.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn to_receipt(croissant: Croissant) -&amp;gt; String {
    match croissant {
        Croissant::Plain { price } =&amp;gt; format!("Plain croissant: ${price}"),
        Croissant::WithFilling { filling: _, price } =&amp;gt; {
            format!("Croissant with filling: ${}", price)
        }
    }
}

let croissant = Croissant::WithFilling {
    filling: "Ham &amp;amp; Cheese".to_string(),
    price: 3.35,
};
println!("{:?}", to_receipt(croissant));
// Prints: "Croissant with filling: $3.35"


toReceipt :: Croissant -&amp;gt; String
toReceipt croissant = case croissant of
  Plain price -&amp;gt; "Plain croissant: $" &amp;lt;&amp;gt; show price
  WithFilling _ price -&amp;gt; "Croissant with filling: $" &amp;lt;&amp;gt; show price

print $ toReceipt $ WithFilling "Ham &amp;amp; Cheese" 3.35
-- Prints: "Croissant with filling: $3.35"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Haskell also allows an alternative syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;toReceipt :: Croissant -&amp;gt; String
toReceipt (Plain price) = "Plain croissant: $" &amp;lt;&amp;gt; show price
toReceipt (WithFilling _ price) = "Croissant with filling: $" &amp;lt;&amp;gt; show price

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Partial patterns
&lt;/h4&gt;

&lt;p&gt;Rust is strict about pattern matches being complete.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn to_receipt(croissant: Croissant) -&amp;gt; String {
    match croissant {
// ^^^^^^^^^
        Croissant::Plain { price } =&amp;gt; format!("Plain croissant: ${}", price),
    }
}
// error[E0004]: non-exhaustive patterns:
// pattern `Croissant::WithFilling { .. }` not covered

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While Haskell allows partial pattern matches:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;toReceipt :: Croissant -&amp;gt; String
toReceipt croissant = case croissant of
  (PlainCroissant price) -&amp;gt; "Plain croissant: $" &amp;lt;&amp;gt; show price

print $ toReceipt $ WithFilling "Ham &amp;amp; Cheese" 3.35
-- runtime error: Non-exhaustive patterns in case

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it’s highly discouraged, and a warning can catch this at compile time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Pattern match(es) are non-exhaustive
In a case alternative:
  Patterns of type ‘Croissant’ not matched: WithFilling _ _

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Failure handling
&lt;/h2&gt;

&lt;p&gt;Now, let’s look at two commonly used ADTs: &lt;code&gt;Option&lt;/code&gt; / &lt;code&gt;Maybe&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; / &lt;code&gt;Either&lt;/code&gt;, as well as the standard ways of dealing with errors.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;Option&lt;/code&gt; / &lt;code&gt;Maybe&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; / &lt;code&gt;Either&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;Option&lt;/code&gt; has two variants: &lt;code&gt;None&lt;/code&gt; or &lt;code&gt;Some&lt;/code&gt;; &lt;code&gt;Maybe&lt;/code&gt;: &lt;code&gt;Nothing&lt;/code&gt; or &lt;code&gt;Just&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;// Defined in the standard library
enum Option&amp;lt;T&amp;gt; {
    None,
    Some(T),
}

let head = ["Donut", "Cake", "Cinnamon roll"].get(0);
println!("{:?}", head);
// Prints: Some("Donut")

let no_head: Option&amp;lt;&amp;amp;i32&amp;gt; = [].get(0);
println!("{:?}", no_head);
// Prints: None


-- Defined in the standard library
data Maybe a = Just a | Nothing

safeHead :: [a] -&amp;gt; Maybe a
safeHead (x : _) = Just x
safeHead [] = Nothing

print $ safeHead ["Donut", "Cake", "Cinnamon roll"]
-- Prints: Just "Donut"

print $ safeHead []
-- Prints: Nothing

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Result&lt;/code&gt; also has two variants: &lt;code&gt;Ok&lt;/code&gt; or &lt;code&gt;Err&lt;/code&gt;; &lt;code&gt;Either&lt;/code&gt;: &lt;code&gt;Right&lt;/code&gt; and &lt;code&gt;Left&lt;/code&gt; (by convention, &lt;code&gt;Right&lt;/code&gt; is success and &lt;code&gt;Left&lt;/code&gt; is failure).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Defined in the standard library
enum Result&amp;lt;T, E&amp;gt; {
    Ok(T),
    Err(E),
}

#[derive(Debug)]
struct DivideByZero;

fn safe_division(x: i32, y: i32) -&amp;gt; Result&amp;lt;i32, DivideByZero&amp;gt; {
    match y {
        0 =&amp;gt; Err(DivideByZero),
        _ =&amp;gt; Ok(x / y),
    }
}

println!("{:?}", safe_division(4, 2));
// Prints: Ok(2)

println!("{:?}", safe_division(4, 0))
// Prints: Err(DivideByZero)


-- Defined in the standard library
data Either a b = Left a | Right b
data DivideByZero = DivideByZero
  deriving (Show)

safeDivision :: Int -&amp;gt; Int -&amp;gt; Either DivideByZero Int
safeDivision x y = case y of
  0 -&amp;gt; Left DivideByZero
  _ -&amp;gt; Right $ x `div` y

print $ safeDivision 4 2
// Prints: Right 2

print $ safeDivision 4 0
// Prints: Left DivideByZero

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we work with either of the types, it’s common to pattern match to deal with different cases. Because it can be tiresome, both languages provide alternatives. Let’s check them out first.&lt;/p&gt;

&lt;p&gt;In Rust, we can get a value from an &lt;code&gt;Option&lt;/code&gt; or a &lt;code&gt;Result&lt;/code&gt; by calling &lt;code&gt;unwrap&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;println!("{:?}", safe_division(4, 2).unwrap());
// Prints: 2

println!("{:?}", safe_division(4, 0).unwrap());
// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: DivideByZero'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Calling it on a &lt;code&gt;None&lt;/code&gt; or &lt;code&gt;Error&lt;/code&gt; will &lt;a href="https://doc.rust-lang.org/std/macro.panic.html"&gt;panic&lt;/a&gt; the program, defeating the purpose of error handling.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;💡 What happens when a panic occurs?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By default, panics will print a failure message, unwind, clean up the stack, and abort the process. You can also configure Rust to display the call stack.&lt;/p&gt;




&lt;p&gt;We can use &lt;code&gt;unwrap_or()&lt;/code&gt; to safely unwrap values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let item = [].get(0).unwrap_or(&amp;amp;"Plain donut");

println!("I got: {}", item);
// Prints: I got: Plain donut

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 There are a couple of ways to safely unwrap values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;unwrap_or()&lt;/code&gt;, which eagerly evaluates the default value;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;unwrap_or_else()&lt;/code&gt;, which lazily evaluates the default value;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;unwrap_or_default()&lt;/code&gt;, which relies on the type’s &lt;code&gt;Default&lt;/code&gt; trait implementation.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;It’s not very idiomatic to get things out of things in Haskell, but the standard library provides a similar function called &lt;code&gt;fromMaybe&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;import Data.Maybe (fromMaybe)

let item = fromMaybe "Plain donut" $ safeHead []

print $ "I got: " ++ item
-- Prints: I got: Plain donut

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We prefer to chain things together in Haskell.&lt;/p&gt;

&lt;p&gt;We can chain multiple enums and operations in Rust using the &lt;code&gt;and_then()&lt;/code&gt; method. For example, we can sequence a few safe divisions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let eighth = safe_division(128, 2)
    .and_then(|x| safe_division(x, 2))
    .and_then(|x| safe_division(x, 2));

println!("{:?}", eighth); 
// Prints: Ok(16)

let failure = safe_division(128, 0).and_then(|x| safe_division(x, 2));
println!("{:?}", failure);
// Prints: Err(DivideByZero)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 These are lambdas (we’ll cover them in detail later):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|x| x + 2


\x -&amp;gt; x + 2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;In Haskell, we use the bind (&lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt;) operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let eighth = 
      safeDivision 128 2 &amp;gt;&amp;gt;= \x -&amp;gt;
          safeDivision x 2 &amp;gt;&amp;gt;= \x -&amp;gt;
            safeDivision x 2

print eighth -- Prints: Right 16

let failure = safeDivision 128 0 &amp;gt;&amp;gt;= \x -&amp;gt; safeDivision x 2
print failure
-- Prints: Left DivideByZero

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And last but not least, Rust provides the question mark operator (&lt;code&gt;?&lt;/code&gt;) to deal with &lt;code&gt;Result&lt;/code&gt; and &lt;code&gt;Option&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;use std::collections::HashMap;

let prices = HashMap::from([("Cake", 1.2), ("Donut", 1.0), ("Cinnamon roll", 2.25)]);

fn order_sweets(prices: HashMap&amp;lt;&amp;amp;str, f64&amp;gt;) -&amp;gt; Option&amp;lt;f64&amp;gt; {
    let donut_price = prices.get("Donut")?; // early return if None
    let cake_price = prices.get("Cake")?; // early return if None
    Some(donut_price + cake_price)
}

let total_price = order_sweets(prices);
println!("{:?}", total_price); 
// Prints: Some(2.2) 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The operation short-circuits in case of failure. For example, if we try to look up and use a non-existing item:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn order_sweets(prices: HashMap&amp;lt;&amp;amp;str, f64&amp;gt;) -&amp;gt; Option&amp;lt;f64&amp;gt; {
    let donut_price = prices.get("Donut")?;
    let cake_price = prices.get("Cake")?;
    let missing_price = prices.get("Something random")?; // Fails here

    Some(donut_price + cake_price + missing_price)
}

let total_price = order_sweets(prices);
println!("{:?}", total_price); 
// Prints: None

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in Haskell, we favor do-notation (syntactic sugar to chain special expressions; we are big fans of these).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap

let prices = HashMap.fromList [("Donut", 1.0), ("Cake", 1.2), ("Cinnamon roll", 2.25)]

orderSweets :: HashMap String Double -&amp;gt; Maybe Double
orderSweets prices = do
  donutPrice &amp;lt;- HashMap.lookup "Donut" prices -- early return if Nothing
  cakePrice &amp;lt;- HashMap.lookup "Cake" prices -- early return if Nothing
  Just $ donutPrice + cakePrice

let totalPrice = orderSweets prices
print totalPrice
-- Prints: Just 2.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And as expected, if one lookup fails, the whole function fails:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;orderSweets :: HashMap String Double -&amp;gt; Maybe Double
orderSweets prices = do
  donutPrice &amp;lt;- HashMap.lookup "Donut" prices
  cakePrice &amp;lt;- HashMap.lookup "Cake" prices
  missingPrice &amp;lt;- HashMap.lookup "Something random" prices -- Fails here
  Just $ donutPrice + cakePrice + missingPrice

let totalPrice = orderSweets prices
print totalPrice
-- Prints: Nothing

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  General failure philosophy
&lt;/h3&gt;

&lt;p&gt;We can split errors into two categories:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;recoverable errors or regular errors (such as a “file not found” error);&lt;/li&gt;
&lt;li&gt;unrecoverable errors or programmer mistakes (aka bugs, such as the “dividing by zero” error).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As we review in the previous section, the first category can be covered by enums. It’s the errors that we either want to handle, report to the user, or retry the operation that caused them.&lt;/p&gt;

&lt;p&gt;Let’s look into unrecoverable errors. Rust has a &lt;code&gt;panic!&lt;/code&gt; macro that stops program execution in case of an unrecoverable error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Hey users, don't forget to check for 0 yourselves!
fn optimistic_division(x: i32, y: i32) -&amp;gt; i32 {
    match y {
        0 =&amp;gt; panic!("This should never happen"),
        _ =&amp;gt; x / y,
    }
}

optimistic_division(2, 0);
// thread 'main' panicked at 'This should never happen' ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even though it’s possible, code like this is generally discouraged in Rust.&lt;/p&gt;

&lt;p&gt;Haskell developers painstakingly try to use types to avoid the need for errors in the first place. If you get approvals from at least two other developers and CTO, you can use &lt;code&gt;error&lt;/code&gt; (or &lt;code&gt;impureThrow&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;-- Hey users, don't forget to check for 0 yourselves!
optimisticDivision :: Int -&amp;gt; Int -&amp;gt; Int
optimisticDivision _ 0 = error "This should never happen"
optimisticDivision x y = x `div` y

optimisticDivision 2 0
-- error: This should never happen
-- CallStack (from HasCallStack): error, called at ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But let’s be honest: we’re all prone to think that we’re smarter than the compiler, which leads to an occasional “this should never happen” error message in the logs. Both standard libraries expose functions that can panic/error (for instance, accessing elements of the standard vector/list by index).&lt;/p&gt;




&lt;p&gt;💡 Haskell adds another dimension to failure handling by distinguishing pure functions from potentially impure ones. We’ll cover this later in the article.&lt;/p&gt;




&lt;h2&gt;
  
  
  Polymorphism
&lt;/h2&gt;

&lt;p&gt;Most polymorphism falls into one of two broad categories: parametric polymorphism (same behavior for different types) and ad-hoc polymorphism (different behavior for different types).&lt;/p&gt;

&lt;h3&gt;
  
  
  Parametric polymorphism
&lt;/h3&gt;

&lt;p&gt;Rust supports two types of generic code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;compile-time generics, similar to C++ templates;&lt;/li&gt;
&lt;li&gt;run-time generics, similar to virtual functions in C++ and generics in Java.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using &lt;a href="https://serokell.io/blog/rust-generics"&gt;compile-time generics&lt;/a&gt; (which we just call generics) is similar to using types with type variables in Haskell. For example, we can write a generic function that reverses any type of vector.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1] [1]
fn reverse&amp;lt;T&amp;gt;(vector: &amp;amp;mut Vec&amp;lt;T&amp;gt;) {
    let mut new_vector = Vec::new();

    while let Some(last) = vector.pop() {
        new_vector.push(last);
    }

    *vector = new_vector;
}

// [1]: `T` is a type parameter.
// The function is generic over the type `T`.
// That means that `T` can be of any type.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 We can use any identifier to signify a type parameter in Rust.&lt;/p&gt;

&lt;p&gt;It’s common to name generic types starting from the &lt;code&gt;T&lt;/code&gt; and continuing alphabetically. Sometimes the names can be more meaningful, for example, the types of keys and values: &lt;code&gt;HashMap&amp;lt;K, V&amp;gt;&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;The &lt;code&gt;reverse&lt;/code&gt; function iterates over the elements of a vector using the &lt;code&gt;while&lt;/code&gt; loop. We get the elements in the reverse order because &lt;code&gt;pop&lt;/code&gt; removes the last element from a vector and returns it. We can use this function with any vector:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut price_vector: Vec&amp;lt;f64&amp;gt; = vec![1.0, 1.2, 2.25];
reverse(&amp;amp;mut price_vector);
println!("{:?}", price_vector);
// Prints: [2.25, 1.2, 1.0]

let mut items_vector: Vec&amp;lt;&amp;amp;str&amp;gt; = vec!["Donut", "Cake", "Cinnamon roll"];
reverse(&amp;amp;mut items_vector);
println!("{:?}", items_vector);
// Prints: ["Cinnamon roll", "Cake", "Donut"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can write a similar function for Haskell lists. Note that the Rust function reverses the vector in place, while the Haskell function returns a new list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- [1]
reverseList :: [a] -&amp;gt; [a]
reverseList = go []
 where
  go accumulator [] = accumulator
  go accumulator (current : rest) = go (current : accumulator) rest

-- [1]: `a` is a type variable.
-- That means that `a` can be of any type.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use the intermediate &lt;code&gt;go&lt;/code&gt; function to recursively go over the original list and accumulate its elements in reverse order.&lt;/p&gt;




&lt;p&gt;💡 Type variable names in Haskell start with a lowercase letter.&lt;/p&gt;

&lt;p&gt;Conventions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Ordinary type variables with no particular meaning: &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt;, &lt;code&gt;c&lt;/code&gt;, etc.&lt;/li&gt;
&lt;li&gt;Errors: &lt;code&gt;e&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Famous typeclasses: &lt;code&gt;f&lt;/code&gt; (functors, applicatives), &lt;code&gt;m&lt;/code&gt; (monads), etc.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;We can use this function with any list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let priceList = [1.0, 1.2, 2.25]
print $ reverseList priceList
-- Prints: [2.25, 1.2, 1.0]

let itemsList = ["Donut", "Cake", "Cinnamon roll"]
print $ reverseList itemsList
-- Prints: ["Cinnamon roll", "Cake", "Donut"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Ad-hoc polymorphism
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://serokell.io/blog/rust-traits"&gt;Rust traits&lt;/a&gt; and &lt;a href="https://serokell.io/blog/haskell-typeclasses"&gt;Haskell typeclasses&lt;/a&gt; are siblings – their methods can have different implementations for different types.&lt;/p&gt;

&lt;p&gt;We’ve already seen (and even derived) one standard trait and typeclass: &lt;code&gt;Debug&lt;/code&gt; and &lt;code&gt;Show&lt;/code&gt;, which allow us to convert types to strings for debugging. Let’s derive and use another one for comparing values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(Debug, PartialEq)]
struct Item {
    name: String,
    price: f64,
}

let donut = Item {
    name: "Donut".to_string(),
    price: 1.0,
};

let cake = Item {
    name: "Cake".to_string(),
    price: 1.2,
};

println!("{}", donut == cake); 
// Prints: false

println!("{}", donut == donut); 
// Prints: true

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;💡&lt;code&gt;PartialEq&lt;/code&gt; and &lt;code&gt;Eq&lt;/code&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can’t derive &lt;code&gt;Eq&lt;/code&gt; for &lt;code&gt;Item&lt;/code&gt; in Rust because &lt;code&gt;Eq&lt;/code&gt; is not implemented for &lt;code&gt;f64&lt;/code&gt; (because &lt;code&gt;NaN != NaN&lt;/code&gt;).&lt;/p&gt;






&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Item = Item
  { name :: String
  , price :: Double
  }
  deriving (Show, Eq)

let donut = Item "Donut" 1.0
let cake = Item "Cake" 1.2

print $ donut == cake
-- Prints: False

print $ donut == donut
-- Prints: True

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It shouldn’t be surprising that we can also define our own typeclasses and traits. For example, let’s create one to tax data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;trait Taxable {
    fn tax(&amp;amp;self) -&amp;gt; f64;
}

// It's 10% of the price
impl Taxable for Item {
    fn tax(&amp;amp;self) -&amp;gt; f64 {
        self.price * 0.1
    }
}

println!("{}", donut.tax());
// Prints: 0.1

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Rust, we &lt;strong&gt;implement&lt;/strong&gt; the &lt;code&gt;Taxable&lt;/code&gt; trait for the &lt;code&gt;Item&lt;/code&gt; struct; in Haskell, we create an &lt;strong&gt;instance&lt;/strong&gt; of the &lt;code&gt;Taxable&lt;/code&gt; typeclass for the &lt;code&gt;Item&lt;/code&gt; datatype.&lt;/p&gt;




&lt;p&gt;💡 &lt;code&gt;tax&lt;/code&gt; is an instance method – a trait method that requires an instance of the implementing type via the &lt;code&gt;&amp;amp;self&lt;/code&gt; argument. The &lt;code&gt;self&lt;/code&gt; is an instance of the implementing type that gives us access to its internals.&lt;/p&gt;






&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Taxable a where
  tax :: a -&amp;gt; Double

-- It's 10% of the price
instance Taxable Item where
  tax (Item _ price) = price * 0.1

print $ tax donut
-- Prints: 0.1

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can implement functions that rely on typeclasses and traits. Such as a function that returns a sum of taxes for a collection of taxable elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn tax_all&amp;lt;T: Taxable&amp;gt;(items: Vec&amp;lt;T&amp;gt;) -&amp;gt; f64 {
    items.iter().map(|x| x.tax()).sum()
}

println!("{}", tax_all(vec![donut, cake])); 
// Prints: 0.22

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Rust, we use trait bounds to restrict generics: &lt;code&gt;&amp;lt;T: Taxable&amp;gt;&lt;/code&gt; declares a generic type parameter with a trait bound. In Haskell, we use (typeclass) constraints to restrict type variables; in the following snippet, it’s &lt;code&gt;Taxable a&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;taxAll :: Taxable a =&amp;gt; [a] -&amp;gt; Double
taxAll items = sum $ map tax items

print $ taxAll [donut, cake]
-- Prints: 0.22

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 We can use multiple constraints in both languages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn tax_everything&amp;lt;T: Taxable, U: Taxable + Eq&amp;gt;(items: Vec&amp;lt;T&amp;gt;, special: U) -&amp;gt; f64


taxEverything :: (Taxable a, Taxable b, Eq b) =&amp;gt; [a] -&amp;gt; b -&amp;gt; Double

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;On the surface, these mechanisms are quite similar, but there are some differences. Rust doesn’t allow orphan instances – a trait implementation must appear in the same crate (package) as either the type or trait definition. This prevents different crates from independently defining conflicting implementations (instances).&lt;/p&gt;

&lt;p&gt;In Haskell, we should define instances in the same module where the type is declared or in the module where the typeclass is. Otherwise, Haskell emits a warning.&lt;/p&gt;

&lt;p&gt;Also, Rust refuses to accept code with overlapping (ambiguous duplicate) instances. At the same time, Haskell allows several instances that apply to the same type – compilation fails only when we try to use an ambiguous instance.&lt;/p&gt;




&lt;p&gt;💡 &lt;strong&gt;Fun fact:&lt;/strong&gt; Haskell also has a mechanism called &lt;a href="https://wiki.haskell.org/GHC.Generics"&gt;Generics&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/GHC-Generics.html#t:Generic"&gt;&lt;code&gt;Generic&lt;/code&gt;&lt;/a&gt; typeclass allows us to define polymorphic functions for a variety of data types based on their generic representations – we can ignore the actual datatypes and work with their “shapes” or “structure” (that consists, for example, of constructors and fields).&lt;/p&gt;




&lt;h2&gt;
  
  
  Advanced topics
&lt;/h2&gt;

&lt;p&gt;We can’t go too deep on these topics because each deserves more attention, but we’ll provide basic comparisons and pointers for further learning.&lt;/p&gt;

&lt;h3&gt;
  
  
  Metaprogramming
&lt;/h3&gt;

&lt;p&gt;The next abstraction level is compile-time metaprogramming, which helps generate boilerplate code and is represented by macros and Template Haskell.&lt;/p&gt;

&lt;p&gt;Macros in Rust are built into the language. They come in two different flavors: declarative and procedural macros (which cover function-like macros, custom derives, and custom attributes). Declarative macros are the most widely used; they are referred to as “macros by example” or, more often, as plain “macros”.&lt;/p&gt;

&lt;p&gt;Let’s use them to make pairs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;macro_rules! pair {
    ($x:expr) =&amp;gt; {
        ($x, $x)
    };
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The syntax for calling macros looks almost the same as for calling functions.&lt;/p&gt;




&lt;p&gt;💡 We’ve been using the &lt;code&gt;println!&lt;/code&gt; macro throughout the article.&lt;/p&gt;






&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pair_ints: (i32, i32) = pair!(1);
println!("{:?}", pair_ints);
// Prints: (1, 1)

let pair_strs: (&amp;amp;str, &amp;amp;str) = pair!("two");
println!("{:?}", pair_strs);
// Prints: ("two", "two")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Template Haskell, also known as TH, is a language extension; the &lt;a href="https://hackage.haskell.org/package/template-haskell"&gt;&lt;code&gt;template-haskell&lt;/code&gt;&lt;/a&gt; package exposes a set of functions and datatypes for it.&lt;/p&gt;

&lt;p&gt;Let’s use it to make pairs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Language.Haskell.TH

pair :: ExpQ
pair = [e|\x -&amp;gt; (x, x)|]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have to define it in another module because top-level splices, quasi-quotes, and annotations must be imported, not defined locally. To use Template Haskell, we have to enable the &lt;a href="https://downloads.haskell.org/~ghc/9.2.1/docs/html/users_guide/exts/template_haskell.html#extension-TemplateHaskell"&gt;&lt;code&gt;TemplateHaskell&lt;/code&gt;&lt;/a&gt; extension.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{-# LANGUAGE TemplateHaskell #-}

let pairInts :: (Int, Int) = $pair 1
print pairInts
-- Prints: (1, 1)

let pairStrs :: (String, String) = $pair "two"
print pairStrs
-- Prints: ("two", "two")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Template Haskell doesn’t have a spotless reputation: it introduces extra syntax, increases complexity, and in the past, considerably affected compilation speed (it’s way better these days). Some people prefer to use alternative methods of reducing boilerplate, such as &lt;a href="https://wiki.haskell.org/GHC.Generics"&gt;Generics&lt;/a&gt; (&lt;a href="https://hackage.haskell.org/package/base-4.17.0.0/docs/GHC-Generics.html#t:Generic"&gt;&lt;code&gt;Generic&lt;/code&gt;&lt;/a&gt; typeclass).&lt;/p&gt;




&lt;p&gt;💡 Later versions of GHC support &lt;a href="https://serokell.io/blog/typed-template-haskell-overview"&gt;typed Template Haskell&lt;/a&gt;, which type-checks the expressions at their definition site rather than at their usage (like regular TH).&lt;/p&gt;




&lt;h3&gt;
  
  
  Runtime and concurrency
&lt;/h3&gt;

&lt;p&gt;Rust has no built-in runtime (scheduler). The standard library allows using OS threads directly through &lt;a href="https://doc.rust-lang.org/std/thread/"&gt;&lt;code&gt;std::thread&lt;/code&gt;&lt;/a&gt;. For example, we can spawn a thread:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::thread;
use std::time::Duration;

thread::spawn(|| {
    thread::sleep(Duration::from_secs(1));
    println!("Hello from the spawned thread!");
});
println!(“Spawned a thread”);

thread::sleep(Duration::from_secs(2));
println!("Hello from the main thread!");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Rust language defines &lt;code&gt;async/await&lt;/code&gt; but no concrete execution strategy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(Debug)]
struct Donut;

async fn order_donut() -&amp;gt; Donut {
    println!("Ordering a donut");
    Donut
}

async fn eat(donut: Donut) {
    println!("Eating a donut {:?}", donut)
}

async fn order_and_consume() {
    // Wait for the order before consuming it.
    // `await` doesn't block the thread
    let donut = order_donut().await;
    eat(donut).await;
}

// Blocks the current thread until the future is completed
use futures::executor::block_on;
block_on(order_and_consume());

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use the standard &lt;a href="https://docs.rs/futures/"&gt;&lt;code&gt;futures&lt;/code&gt;&lt;/a&gt;, which has its own executor but is not a full runtime. To get an asynchronous runtime in Rust, we have to use external libraries, such as &lt;a href="https://tokio.rs/"&gt;&lt;code&gt;Tokio&lt;/code&gt;&lt;/a&gt; and &lt;a href="https://async.rs/"&gt;&lt;code&gt;async-std&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here is a snippet of code that uses &lt;code&gt;Tokio&lt;/code&gt; to do some concurrent work using three different services and then either collect the successful result or return a timeout error (all the other errors are ignored for simplicity):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use tokio::time::timeout;

// Imagine `do_work` does some meaningful work
// async fn do_work(work: &amp;amp;Work, service: &amp;amp;Service) -&amp;gt; String

async fn concurrent_program(work: &amp;amp;Work) -&amp;gt; Result {
    timeout(Duration::from_secs(2), async {
        tokio::join!(
            do_work(work, &amp;amp;Service::ServiceA),
            do_work(work, &amp;amp;Service::ServiceB),
            do_work(work, &amp;amp;Service::ServiceC)
        )
    })
    .await
    .map(|(a, b, c)| Result::Success(vec![a, b, c]))
    .unwrap_or_else(|_| Result::Timeout)
}

// Still have to run this program
concurrent_program(&amp;amp;some_work).await;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note that this will run all the work concurrently on the same task. If we want to do the job simultaneously or in parallel, we need to call &lt;code&gt;tokio::spawn&lt;/code&gt; for each of the tasks to spawn and run it.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;💡 Rust doesn’t oblige you to stick to one type of concurrency model (such as threads, async, etc.). You can use any if you find a suitable crate (library).&lt;/p&gt;




&lt;p&gt;Haskell has green threads – the runtime system manages threads (instead of directly using native OS threads). The essential operation is forking a thread with &lt;code&gt;forkIO&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;import Control.Concurrent (threadDelay, forkIO)

forkIO $ do
  threadDelay $ 1000 * 1000
  print "Hello from the spawned thread!"

print "Spawned a thread"

threadDelay $ 2 * 1000 * 1000
print "Hello from the main thread!"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Various libraries in Haskell take advantage of green threads to provide powerful and composable APIs. For example, the &lt;a href="https://hackage.haskell.org/package/async"&gt;&lt;code&gt;async&lt;/code&gt;&lt;/a&gt; package (library). The following snippet uses &lt;code&gt;async&lt;/code&gt; to do concurrent work with three services and then assembles the result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (mapConcurrently)
import System.Timeout (timeout)

-- Imagine `doWork` does some meaningful work
-- doWork :: Work -&amp;gt; Service -&amp;gt; IO PartialResult

concurrentProgram :: Work -&amp;gt; IO Result
concurrentProgram work = do
  results &amp;lt;-
    timeout twoSeconds $
      mapConcurrently (doWork work) [ServiceA, ServiceB, ServiceC]
  pure $ case results of
    Just success -&amp;gt; Success success
    Nothing -&amp;gt; Timeout
 where
  twoSeconds = 1000 * 1000

-- Run the program
concurrentProgram someWork

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And we have to mention the &lt;a href="https://hackage.haskell.org/package/stm"&gt;Software Transactional Memory (STM)&lt;/a&gt; abstraction in Haskell, which allows us to group multiple state-changing operations and perform them as a single atomic operation.&lt;/p&gt;

&lt;p&gt;Imagine the situation: I have $0 and want to buy a donut for $3; also, I earn $1 per second. I can keep trying to buy a donut until I have sufficient funds. We have a typical money transfer transaction, which needs to be retried and can be simulated using STM. We don’t need to worry about transaction rollbacks or retries – STM handles all of these for us.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;runSimulation :: IO ()
runSimulation = do
  -- Start with 0
  wallet &amp;lt;- newTVarIO 0
  cashRegister &amp;lt;- newTVarIO 100

  -- Get paid at the same time
  _ &amp;lt;- forkIO $ getPaid wallet

  -- Try to make a donut-money transaction
  atomically $ do
    myCash &amp;lt;- readTVar wallet
    -- Check if I have enough money
    check $ myCash &amp;gt;= donutPrice
    -- Subtract the amount from my wallet
    writeTVar wallet (myCash - donutPrice)
    storeCash &amp;lt;- readTVar cashRegister
    -- Add the amount to the cash register
    writeTVar cashRegister (storeCash + donutPrice)

  myFinal &amp;lt;- readTVarIO wallet
  print $ "I have: $" ++ show myFinal

  storeFinal &amp;lt;- readTVarIO cashRegister
  print $ "Cash register: $" ++ show storeFinal
where
  donutPrice = 3

-- Put $1 in my wallet every second
getPaid :: TVar Int -&amp;gt; IO ()
getPaid wallet = forever $ do
  threadDelay $ 1000 * 1000
  atomically $ modifyTVar wallet (+ 1)
  print "I earned a dollar"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 &lt;a href="https://hackage.haskell.org/package/stm-2.5.1.0/docs/Control-Concurrent-STM-TVar.html"&gt;&lt;code&gt;TVar&lt;/code&gt;&lt;/a&gt; stands for transactional variable, which we can read or write to within STM, using operations such as &lt;a href="https://hackage.haskell.org/package/stm-2.5.1.0/docs/Control-Concurrent-STM-TVar.html#v:readTVar"&gt;&lt;code&gt;readTVar&lt;/code&gt;&lt;/a&gt; and &lt;a href="https://hackage.haskell.org/package/stm-2.5.1.0/docs/Control-Concurrent-STM-TVar.html#v:writeTVar"&gt;&lt;code&gt;writeTVar&lt;/code&gt;&lt;/a&gt;. We can perform a computation in the STM using the &lt;a href="https://hackage.haskell.org/package/stm-2.5.1.0/docs/Control-Monad-STM.html#v:atomically"&gt;&lt;code&gt;atomically&lt;/code&gt;&lt;/a&gt; function.&lt;/p&gt;




&lt;p&gt;When we run the program, we see that I must be paid at least three times before the transaction succeeds:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;runSimulation
-- Prints: 
-- "I earned a dollar"
-- "I earned a dollar"
-- "I earned a dollar"
-- "I have: $0"
-- "Cash register: $103"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Functions and functional programming
&lt;/h2&gt;

&lt;p&gt;Functions are widespread in both languages. Haskell and Rust support higher-order functions. Haskell is always functional, and functional Rust is frequently just proper, idiomatic Rust.&lt;/p&gt;

&lt;h3&gt;
  
  
  Lambdas and closures
&lt;/h3&gt;

&lt;p&gt;A lambda is an anonymous function that can be treated like a value. We can use lambdas as arguments for higher-order functions.&lt;/p&gt;

&lt;p&gt;In Rust:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bump = |i: f64| i + 1.0;
println!("{}", bump(1.2));
// Prints: 2.2

let bump_inferred = |i| i + 1.0;
println!("{}", bump_inferred(1.2));
// Prints: 2.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Haskell:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bump = \(i :: Double) -&amp;gt; i + 1.0
print $ bump 1.2
-- Prints: 2.2

let bumpInferred = \i -&amp;gt; i + 1.0
print $ bumpInferred 1.2
-- Prints: 2.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 Note that annotating a type variable might require the &lt;a href="https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/scoped_type_variables.html#extension-ScopedTypeVariables"&gt;&lt;code&gt;ScopedTypeVariables&lt;/code&gt;&lt;/a&gt; extension, depending on your usage. But also, writing lambdas like that can be redundant in Haskell. We could have written a normal function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let bump :: Double -&amp;gt; Double
    bump i = i + 1.0

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;We can use closures to capture values from the scope/environment in which they’re defined. For example, we can define a simple closure that captures the &lt;code&gt;outside&lt;/code&gt; variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|x| x + outside


\x -&amp;gt; x + outside

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Rust, each value has a lifetime. Because closures capture environment values, we have to deal with their ownership and lifetimes. For example, let’s write a function that returns a greeting function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn create_greeting() -&amp;gt; impl Fn(&amp;amp;str) -&amp;gt; String {
    let greet = "Hello,";
    move |name: &amp;amp;str| format!("{greet} {name}!")
}

let greeting_function = create_greeting();

println!("{}", greeting_function("Rust"));
// Prints: Hello, Rust!

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use &lt;code&gt;move&lt;/code&gt; to force the closure to take ownership of the &lt;code&gt;greet&lt;/code&gt; variable.&lt;/p&gt;




&lt;p&gt;💡 If we forget to use &lt;code&gt;move&lt;/code&gt;, we get an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0373]: closure may outlive the current function, but it borrows `greet`, which is owned by the current function
   |
   | |name: &amp;amp;str| format!("{greet} {name}!")
   | ^^^^^^^^^^^^ ----- `greet` is borrowed here
   | |
   | may outlive borrowed value `greet`
   |
note: closure is returned here
   |
   | |name: &amp;amp;str| format!("{greet} {name}!")
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `greet` (and any other referenced variables), use the `move` keyword
   |
   | move |name: &amp;amp;str| format!("{greet} {name}!")
   | ++++

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;💡 What is &lt;code&gt;Fn&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;How a closure captures and handles values from the environment determines which traits (one, two, or all three) it implements and how the closure can be used. There are three traits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://doc.rust-lang.org/stable/std/ops/trait.FnOnce.html"&gt;&lt;code&gt;FnOnce&lt;/code&gt;&lt;/a&gt; (can be called once);&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://doc.rust-lang.org/stable/std/ops/trait.FnMut.html"&gt;&lt;code&gt;FnMut&lt;/code&gt;&lt;/a&gt; (can be called more than once, may mutate state);&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://doc.rust-lang.org/stable/std/ops/trait.Fn.html"&gt;&lt;code&gt;Fn&lt;/code&gt;&lt;/a&gt; (can be called more than once, no state mutation).&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;In Haskell, we don’t worry much about closures.&lt;/p&gt;

&lt;h3&gt;
  
  
  Currying and partial application
&lt;/h3&gt;

&lt;p&gt;Currying is converting a function that takes multiple arguments into a function that takes them one at a time. Each time we call a function, we pass it one argument, and it returns another function that also takes one argument until all arguments are passed.&lt;/p&gt;

&lt;p&gt;In Haskell, all functions are considered curried, which might not be obvious because it’s hidden in the syntax: &lt;code&gt;Double -&amp;gt; Double -&amp;gt; Double&lt;/code&gt; is actually &lt;code&gt;Double -&amp;gt; (Double -&amp;gt; Double)&lt;/code&gt; and &lt;code&gt;add x y&lt;/code&gt; is actually &lt;code&gt;(add x) y&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;add :: Double -&amp;gt; Double -&amp;gt; Double
add x y = x + y

bump :: Double -&amp;gt; Double 
bump = add 1.0

full :: Double 
full = add 1.0 1.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we pass &lt;code&gt;1.0&lt;/code&gt; to &lt;code&gt;add&lt;/code&gt;, we get another function, &lt;code&gt;bump&lt;/code&gt;, which takes a double, adds 1 to it, and returns that sum as a result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add x y = x + y
bump = add 1.0

print $ bump 1.2
-- Prints: 2.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;bump&lt;/code&gt; is the result of partial application, which means we pass less than the total number of arguments to a function that takes multiple arguments.&lt;/p&gt;

&lt;p&gt;We can do this in Rust, but it’s not idiomatic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn add(x: f64) -&amp;gt; impl Fn(f64) -&amp;gt; f64 {
    move |y| x + y
}

let bump = add(1.0);

println!("{}", bump(1.2)); 
// Prints: 2.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are crates that make it easier like &lt;a href="https://crates.io/crates/partial_application"&gt;partial_application&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use partial_application::partial;

fn add(x: f64, y: f64) -&amp;gt; f64 {
    x + y
}

let bump2 = partial!(add =&amp;gt; 1.0, _);

println!("{}", bump(1.2)); 
// Prints: 2.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Currying and partial application are convenient when we pass functions around as values and allows us to use neat features, such as composition.&lt;/p&gt;

&lt;h3&gt;
  
  
  Function composition
&lt;/h3&gt;

&lt;p&gt;In Haskell, we can use function composition, which pipes the result of one function to the input of another, creating an entirely new function.&lt;/p&gt;




&lt;p&gt;💡 We use the dot operator (&lt;code&gt;.&lt;/code&gt;) to implement function composition in Haskell.&lt;/p&gt;




&lt;p&gt;For example, we can compose three functions to get a maximum price from the list and negate it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import qualified Data.HashMap.Strict as HashMap

-- HashMap.elems :: HashMap String Double -&amp;gt; [Double]
-- maximum :: [Double] -&amp;gt; Double
-- negate :: Double -&amp;gt; Double

negativeMaxPrice :: HashMap String Double -&amp;gt; Double
negativeMaxPrice = negate . maximum . HashMap.elems

let prices = HashMap.fromList [("Donut", 1.0), ("Cake", 1.2)]
print $ negativeMaxPrice prices 
-- Prints: -1.2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can technically do it in Rust, but it’s not commonly used and not part of the standard library.&lt;/p&gt;

&lt;h3&gt;
  
  
  Iterators
&lt;/h3&gt;

&lt;p&gt;In Rust, the iterator pattern allows us to traverse collections. Iterators are responsible for the logic of iterating over each item and determining when the sequence has finished.&lt;/p&gt;

&lt;p&gt;For example, let’s use iterators to get the total price of all the products except for donuts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::collections::HashMap;

let prices = 
  HashMap::from([("Donut", 1.0), ("Cake", 1.2), ("Cinnamon roll", 2.25)]);

let total: f64 = prices
    .into_iter()
    .filter(|&amp;amp;(name, _)| name != "Donut")
    .map(|(_, price)| price)
    .sum();

println!("{}", total); 
// Prints: 3.45

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Iterators are lazy — they don’t do anything unless they are consumed. We can also use &lt;a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect"&gt;&lt;code&gt;collect&lt;/code&gt;&lt;/a&gt; to transform an iterator into another collection. For example, we can return the prices instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::collections::HashMap;

let prices = 
  HashMap::from([("Donut", 1.0), ("Cake", 1.2), ("Cinnamon roll", 2.25)]);

let other_prices: Vec&amp;lt;f64&amp;gt; = prices
    .into_iter()
    .filter(|&amp;amp;(name, _)| name != "Donut")
    .map(|(_, price)| price)
    .collect();

println!("{:?}", other_prices);
// Prints: [1.2, 2.25]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Haskell, we work with collections directly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import qualified Data.HashMap.Strict as HashMap

let prices = 
      HashMap.fromList [("Donut", 1.0), ("Cake", 1.2), ("Cinnamon roll", 2.25)]

let total =
        sum
          $ HashMap.elems
          $ HashMap.filterWithKey (\name _ -&amp;gt; name /= "Donut")
          $ prices

print total 
-- Prints: 3.45


import qualified Data.HashMap.Strict as HashMap

let prices = 
      HashMap.fromList [("Donut", 1.0), ("Cake", 1.2), ("Cinnamon roll", 2.25)]

let otherPrices =
      HashMap.elems $
        HashMap.filterWithKey (\name _ -&amp;gt; name /= "Donut") prices

print otherPrices 
-- Prints: [1.2, 2.25]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Associated functions and methods
&lt;/h3&gt;

&lt;p&gt;In Rust, we can connect functions to particular types — via associated functions or methods. Associated functions are called on the type, and methods are called on a particular instance of a type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Item {
    name: String,
    price: f64,
}

impl Item {
    fn free(name: String) -&amp;gt; Item {
        Item { name, price: 0.0 }
    }

    fn print_receipt(&amp;amp;self) {
        println!("{}: ${}", self.name, self.price);
    }
}

// Calling an associated function:
let free_donut = Item::free("Regular donut".to_string());

// Calling a method:
free_donut.print_receipt(); 
// Prints: Regular donut: $0

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Haskell, we can’t and don’t.&lt;/p&gt;

&lt;h2&gt;
  
  
  Things we worry about in Rust
&lt;/h2&gt;

&lt;p&gt;Speaking of the things we don’t do in Haskell. It shouldn’t be a surprise that the feature that sets Rust apart is its ownership model and the borrow checker.&lt;/p&gt;

&lt;p&gt;Remember how we used &lt;code&gt;move&lt;/code&gt; to force the closure to take ownership of the variable?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn create_greeting() -&amp;gt; impl Fn(&amp;amp;str) -&amp;gt; String {
    let greet = "Hello,";
    move |name: &amp;amp;str| format!("{greet} {name}!")
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust is a statically memory-managed language, which requires us to think about the lifetimes of values.&lt;/p&gt;




&lt;p&gt;💡 If you want to learn more about this topic, check out the &lt;a href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html#understanding-ownership"&gt;Understanding Ownership&lt;/a&gt; chapter of the Rust book.&lt;/p&gt;




&lt;p&gt;And in Haskell? In Haskell, we have space leaks (but we usually don’t worry about those). 😉&lt;/p&gt;

&lt;h2&gt;
  
  
  Things we worry about in Haskell
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Laziness
&lt;/h3&gt;

&lt;p&gt;Haskell programs are executed using lazy evaluation, which doesn’t perform a computation until its result is required and avoids unnecessary computation.&lt;/p&gt;

&lt;p&gt;Laziness encourages programming in a modular style without worrying about intermediate data and allows working with infinite structures. Let’s illustrate this by writing a function that returns the first prime number larger than &lt;code&gt;10 000&lt;/code&gt;. We can start with an infinite list of naturals, filter the prime numbers, and take the first prime after &lt;code&gt;10 000&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;naturals :: [Int]
naturals = [1 ..]

-- Check there is no divisors for `n`
isPrime :: Int -&amp;gt; Bool
isPrime n = null [number | number &amp;lt;- [2 .. n - 1], n `mod` number == 0]

print $ take 1 $ filter (&amp;gt; 10000) $ filter isPrime naturals
-- Prints: [1000003]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because of laziness, the work stops right after it finds the correct prime number – no need to calculate the rest of the list or the rest of the primes.&lt;/p&gt;

&lt;p&gt;This computation takes &lt;code&gt;~40MB&lt;/code&gt; of memory &lt;em&gt;(YMMV)&lt;/em&gt;, primarily the runtime overhead. If we increase the number to &lt;code&gt;100 000&lt;/code&gt;, the memory usage stays the same.&lt;/p&gt;

&lt;p&gt;All good so far. What if we try something else? Let’s take &lt;code&gt;1 000 000&lt;/code&gt; naturals and return their sum along with the length of the list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nums = take 10000000 naturals
print $ (sum nums, length nums)
-- (500000500000,1000000)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This computation takes &lt;code&gt;~129MB&lt;/code&gt; of memory &lt;em&gt;(YMMV)&lt;/em&gt;. And if we take &lt;code&gt;10 000 000&lt;/code&gt; – the memory usage goes up to &lt;code&gt;~1.376GB&lt;/code&gt;. Oops.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;💡 Why does it happen?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because the &lt;code&gt;nums&lt;/code&gt; list is used for both &lt;code&gt;sum&lt;/code&gt; and &lt;code&gt;length&lt;/code&gt; computations, the compiler can’t discard list elements until it evaluates both.&lt;/p&gt;

&lt;p&gt;Note that &lt;code&gt;sum $ take 10000000 naturals&lt;/code&gt; runs in constant memory.&lt;/p&gt;




&lt;p&gt;💡 If you want to learn more, check out &lt;a href="https://www.youtube.com/watch?v=DSy7bscJL7k"&gt;our videos on laziness&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;So, it’s favorable to be mindful of how expressions are evaluated when working with data in Haskell to avoid space leaks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Purity
&lt;/h3&gt;

&lt;p&gt;Haskell is pure – invoking a function with the same arguments always returns the same result.&lt;/p&gt;

&lt;p&gt;As a consequence, in Haskell, there is no distinction between a zero-argument function and a constant.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;f(x, y) // functino with two arguments
f(x) // function with one argument
f() // function with zero arguments
C // constant


f x y -- function with two arguments
f x -- function with one argument
F -- zero argument / constant 
c -– zero argument / constant

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 Pure functions do not have side effects.&lt;/p&gt;




&lt;p&gt;Purity, together with laziness, raises some challenges. Without digging too deep into the rabbit hole, let’s look at an example pseudo-Haskell code. The following impure example reads 2 integers from the standard input and returns them as a list (pay attention to the order):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- `readNumber` is an impure function that reads a number from stdin

-- some impure computation
pseudoComputation =
  let first = readNumber
  let second = readNumber
  print [second, first]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we’ve learned, because of laziness, Haskell doesn’t evaluate an expression until it is needed: evaluation of &lt;code&gt;first&lt;/code&gt; and &lt;code&gt;second&lt;/code&gt; is postponed until they are used, and when it starts forcing the list, it starts with reading the &lt;code&gt;second&lt;/code&gt; number and then &lt;code&gt;first&lt;/code&gt;. Which is the opposite of what we want and expect.&lt;/p&gt;

&lt;p&gt;To deal with this mess, Haskell has &lt;code&gt;IO&lt;/code&gt; – a special datatype that offers better control over its execution. &lt;code&gt;IO&lt;/code&gt; is a description of a computation. When executed, it can perform arbitrary effects before returning a value of type &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;💡 Executing &lt;code&gt;IO&lt;/code&gt; is not the same as evaluating it. Evaluating an &lt;code&gt;IO&lt;/code&gt; expression is pure – it returns the same description. For example, &lt;code&gt;io1&lt;/code&gt; and &lt;code&gt;io2&lt;/code&gt; are guaranteed to be the same:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- some IO function 
-- doSomeAction :: String -&amp;gt; IO ()

let variable = doSomeAction "parameter"
let io1 = (var, var)


let io2 = (doSomeAction "parameter", doSomeAction "parameter")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;We’ve been using the &lt;code&gt;print&lt;/code&gt; function to print things out; here is its type signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print :: Show a =&amp;gt; a -&amp;gt; IO ()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can’t print outside of &lt;code&gt;IO&lt;/code&gt;. We get a compilation error if we try otherwise:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;noGreet :: String -&amp;gt; String
noGreet name = print $ "Hello, " &amp;lt;&amp;gt; name
-- ^^^^^^^^^^^^^^^^^^^^^^^^^
-- Couldn't match type: IO ()
-- with: String

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, we have an &lt;code&gt;IO&lt;/code&gt; function. How do we run it? We need to define the program’s &lt;code&gt;main&lt;/code&gt; &lt;code&gt;IO&lt;/code&gt; function – the program entry point – which the Haskell runtime will execute. Let’s look at the executable module example: it asks the user for the name, reads it, and prints the greeting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module Main where 

greet :: String -&amp;gt; IO ()
greet name = print $ "Hello, " &amp;lt;&amp;gt; name

main :: IO ()
main = do
  print "What's your name?"
  name &amp;lt;- getLine
  greet name

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 Remember the do-notation syntax that we used with &lt;code&gt;Maybe&lt;/code&gt; and &lt;code&gt;Either&lt;/code&gt;? We can use it with &lt;code&gt;IO&lt;/code&gt; as well! It’s convenient to put actions together.&lt;/p&gt;




&lt;p&gt;This differs from all the languages in which we can perform side effects anywhere and anytime.&lt;/p&gt;

&lt;p&gt;For completeness, this is how a main module looks like in Rust:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let two = one() + one();
    println!("Hello from main and {}", two);
}

fn one() -&amp;gt; i32 {
    println!("Hello from one");
    1
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that we can execute arbitrary side effects.&lt;/p&gt;

&lt;h3&gt;
  
  
  Higher-order programming
&lt;/h3&gt;

&lt;p&gt;In Haskell, we prefer general solutions for common patterns. For example, do-notation is syntactic sugar for the bind operator (&lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt;), which is overloaded for a bunch of types: &lt;code&gt;Maybe&lt;/code&gt;, &lt;code&gt;Either e&lt;/code&gt;, &lt;code&gt;[]&lt;/code&gt;, &lt;code&gt;State&lt;/code&gt;, &lt;code&gt;IO&lt;/code&gt;, etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;do
  x &amp;lt;- action1
  y &amp;lt;- action2
  f x y


-- Desugared version:
action1 &amp;gt;&amp;gt;= \x -&amp;gt;
  action2 &amp;gt;&amp;gt;= \y -&amp;gt;
    f x y

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As a result, we can use the notation to express many problems and deal with many use cases: optionality, non-determinism, error handling, state mutation, concurrency, etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Dealing with optionality: 
maybeSweets :: HashMap String Double -&amp;gt; Maybe Double
maybeSweets prices = do
  donutPrice &amp;lt;- HashMap.lookup "Donut" prices
  cakePrice &amp;lt;- HashMap.lookup "Cake" prices
  Just $ donutPrice + cakePrice

-- Dealing with IO:
ioSweets :: Statistics -&amp;gt; SweetsService -&amp;gt; IO Double
ioSweets statistics sweets = do
  print "Fetching sweets from external service"
  prices &amp;lt;- fetchPrices sweets
  updateCounters statistics prices
  pure prices

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is one of the design patterns for structuring code in Haskell. We implement them using typeclasses, and they are supported by laws (a whole different topic). When Haskell developers see that the library provides a datatype or an interface related to one of these typeclasses, they have some expectations and guarantees about its behavior.&lt;/p&gt;




&lt;p&gt;💡 Top 7 useful typeclasses everyone should know about:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Semigroup&lt;/code&gt;, &lt;code&gt;Monoid&lt;/code&gt;, &lt;code&gt;Functor&lt;/code&gt;, &lt;code&gt;Applicative&lt;/code&gt;, &lt;code&gt;Monad&lt;/code&gt;, &lt;code&gt;Foldable&lt;/code&gt;, and &lt;code&gt;Traversable&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;Higher-kinded types are the basis for these typeclasses. A higher-kinded type is a type that abstracts over some polymorphic type. Take, for instance, &lt;code&gt;f&lt;/code&gt; in the following &lt;code&gt;Functor&lt;/code&gt; definition:&lt;br&gt;
&lt;/p&gt;

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

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;f&lt;/code&gt; can be &lt;code&gt;Option&lt;/code&gt;, &lt;code&gt;[]&lt;/code&gt;, &lt;code&gt;IO&lt;/code&gt;, etc.; while &lt;code&gt;f a&lt;/code&gt; can be &lt;code&gt;Option Int&lt;/code&gt;, &lt;code&gt;[String]&lt;/code&gt;, &lt;code&gt;IO Bool&lt;/code&gt;, etc.&lt;/p&gt;

&lt;p&gt;You can check out &lt;a href="https://serokell.io/blog/kinds-and-hkts-in-haskell"&gt;Kinds and Higher-Kinded Types&lt;/a&gt; for a more detailed explanation.&lt;/p&gt;




&lt;p&gt;Rust doesn’t support higher-kinded types (yet), and it’s more complex to implement concepts such as monads and their friends. Instead, Rust provides alternative approaches to solve the problems that these typeclasses solve in Haskell:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If you want to deal with optionality or error handling, you can use &lt;code&gt;Option&lt;/code&gt;/&lt;code&gt;Result&lt;/code&gt; with the &lt;code&gt;?&lt;/code&gt; operator.&lt;/li&gt;
&lt;li&gt;If you want to deal with async code – &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;.await&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Turns out Rust and Haskell have a lot in common: both languages have a lot of features and can be frustrating to learn. Luckily they share a lot of concepts, and knowledge of one language can be helpful while pursuing another.&lt;/p&gt;

&lt;p&gt;And please remember that in both cases, the compiler has your back, so don’t forget that compilers are your friends. 😉&lt;/p&gt;

&lt;p&gt;For more articles on Haskell and Rust, follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt; or subscribe to the newsletter via the form below.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>haskell</category>
    </item>
    <item>
      <title>Get Started with Rust: Generics</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 03 Jan 2023 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/get-started-with-rust-generics-1j5f</link>
      <guid>https://dev.to/serokell/get-started-with-rust-generics-1j5f</guid>
      <description>&lt;h1&gt;
  
  
  Get Started with Rust: Generics
&lt;/h1&gt;

&lt;p&gt;Generic programming allows programmers to write general algorithms that work with arbitrary types. It reduces code duplication and provides type safety, which enables us to write more concise and clean code. This approach is also known as parametric polymorphism or templates in other languages.&lt;/p&gt;

&lt;p&gt;Rust supports two types of generic code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Compile-time generics, similar to C++ templates.&lt;/li&gt;
&lt;li&gt;Run-time generics, similar to virtual functions in C++ and generics in Java.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This article will cover compile-time generics (which we just call generics) and these questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Why do we use generics?&lt;/li&gt;
&lt;li&gt;How to use generic types in Rust?&lt;/li&gt;
&lt;li&gt;How to define custom types, functions, and methods with generics?&lt;/li&gt;
&lt;li&gt;How to restrict generics with traits?&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What are generics in Rust?
&lt;/h2&gt;

&lt;p&gt;Let’s start with an example, creating and printing a vector of integers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut int_vector = Vec::new();

int_vector.push(1);
int_vector.push(2);
int_vector.push(3);

for i in &amp;amp;int_vector {
    println!("{}", i);
}
// Prints:
// 1
// 2
// 3

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We call the &lt;code&gt;Vec::new&lt;/code&gt; function to create a new empty vector, add multiple elements with &lt;code&gt;push&lt;/code&gt;, and print all the elements.&lt;/p&gt;

&lt;p&gt;Rust is a statically typed language, meaning the compiler should know the types of all the variables at compile time. Once we push the first integer into the vector, the compiler recognizes &lt;code&gt;int_vector&lt;/code&gt; as a vector of integers, and it can’t store any other type. If we try to push &lt;code&gt;4.0&lt;/code&gt;, the code doesn’t compile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0308]: mismatched types
   |
   | int_vector.push(4.0);
   | ---- ^^^ expected integer, found floating-point number
   | |
   | arguments to this function are incorrect

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can write a similar program using strings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut str_vector = Vec::new();

str_vector.push("one");
str_vector.push("two");
str_vector.push("three");

for i in &amp;amp;str_vector {
    println!("{}", i);
}
// Prints:
// one
// two
// three

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This time, if we try to push &lt;code&gt;4&lt;/code&gt;, the code doesn’t compile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0308]: mismatched types
   |
   | str_vector.push(4);
   | ---- ^^^ expected `&amp;amp;str`, found integer
   | |
   | arguments to this function are incorrect

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Aside from the name and elements, both code snippets look pretty similar. With &lt;code&gt;Vec::new&lt;/code&gt;, we created and used two vectors: one that holds integers and another that holds strings. This is possible because vectors are implemented using generics. When we use &lt;code&gt;new&lt;/code&gt;, we construct a new empty &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt;, which can hold any type.&lt;/p&gt;




&lt;p&gt;💡 &lt;strong&gt;The &lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt; syntax&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use the &lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt; syntax when declaring generic types. &lt;code&gt;T&lt;/code&gt; is known as the type parameter, and it’s written between the angle brackets. &lt;code&gt;T&lt;/code&gt; represents any data type, which means there is no way to know what &lt;code&gt;T&lt;/code&gt; is at runtime – we can’t pattern match on it, can’t do any type-specific operations, and can’t have different code paths for different &lt;code&gt;T&lt;/code&gt;’s.&lt;/p&gt;

&lt;p&gt;You can use any letter to signify a type parameter, but it’s common to use &lt;code&gt;T&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;The compiler can often infer the type we want to use based on the value and how we use it. When we push a value of a specific type into a vector, the compiler figures out what kind of elements we want to store and infers the type of the vector. For example, when we populated &lt;code&gt;int_vector&lt;/code&gt; with &lt;code&gt;i32&lt;/code&gt; values, Rust inferred that its type is &lt;code&gt;Vec&amp;lt;i32&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If we don’t insert any elements into the vector and don’t give any hints about the elements of the vector, the code doesn’t compile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut int_vector = Vec::new();

for i in &amp;amp;int_vector {
    println!("{}", i);
}


error[E0282]: type annotations needed for `Vec&amp;lt;T&amp;gt;`
   |
   | let mut int_vector = Vec::new();
   | ^^^^^^^^^^^^^^
   |
help: consider giving `int_vector` an explicit type
    , where the type for type parameter `T` is specified
   |
   | let mut int_vector: Vec&amp;lt;T&amp;gt; = Vec::new();
   | ++++++++

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because we aren’t inserting any values into the vector anymore, Rust doesn’t know what kind of elements we intend to store. The error suggests that we can add an explicit type. With a type annotation, we can tell the compiler that the &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; in &lt;code&gt;int_vector&lt;/code&gt; will hold elements of the &lt;code&gt;i32&lt;/code&gt; type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// We specify the type within angle brackets
let mut int_vector: Vec&amp;lt;i32&amp;gt; = Vec::new();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can’t leave a vector without a specific type. We need to tell the compiler which concrete type we will use: explicitly (with type annotations) or implicitly (by using specific types).&lt;/p&gt;

&lt;p&gt;Let’s look at another example, a &lt;code&gt;HashMap&lt;/code&gt; collection, which has two generic types: key type and value type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::collections::HashMap;

let mut score_map: HashMap&amp;lt;&amp;amp;str, i32&amp;gt; = HashMap::new();
score_map.insert("Jamie", 16);
score_map.insert("Ashley", 71);

let mut codes_map: HashMap&amp;lt;u32, &amp;amp;str&amp;gt; = HashMap::new();
codes_map.insert(282, "type annotation error");
codes_map.insert(308, "mismatched types error");

let mut flags_map: HashMap&amp;lt;&amp;amp;str, bool&amp;gt; = HashMap::new();
flags_map.insert("required", true);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can create a hash map with any combination of keys and values. We don’t need to create a specific collection for all the possible types (e.g., &lt;code&gt;StringIntMap&lt;/code&gt;, &lt;code&gt;StringBoolMap&lt;/code&gt;, etc); we can use one collection and specify the types we want.&lt;/p&gt;




&lt;p&gt;💡 We can define multiple generic parameters by separating them with commas:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn take_three&amp;lt;T, U, V&amp;gt;(t: T, u: U, v: V) {}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s common to name generic types starting from the &lt;code&gt;T&lt;/code&gt; and continuing alphabetically. Sometimes the names can be more meaningful, for example, the types of keys and values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HashMap&amp;lt;K, V&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  How do generics work?
&lt;/h3&gt;

&lt;p&gt;In some sense, when we define a generic collection (e.g., &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt;), we define an infinite set of collections (such as &lt;code&gt;Vec&amp;lt;i32&amp;gt;&lt;/code&gt;, &lt;code&gt;Vec&amp;lt;i64&amp;gt;&lt;/code&gt;, and &lt;code&gt;Vec&amp;lt;&amp;amp;str&amp;gt;&lt;/code&gt;).&lt;/p&gt;




&lt;p&gt;💡 When Rust compiles generic code, it performs a process called monomorphization. We write generic code that works for some arbitrary type &lt;code&gt;T&lt;/code&gt;, and Rust generates specific uses of the code by filling in the concrete types at compile time. For example, it will generate code for &lt;code&gt;Vec&amp;lt;i32&amp;gt;&lt;/code&gt; and &lt;code&gt;Vec&amp;lt;&amp;amp;str&amp;gt;&lt;/code&gt;, but the resulting code will be different due to how each type works underneath.&lt;/p&gt;




&lt;p&gt;When we use generics, we can write code for multiple data types instead of rewriting the same code for each type, making the code more straightforward and less error-prone.&lt;/p&gt;

&lt;p&gt;Rust can make use of generics in several places:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Function and method definitions.&lt;/li&gt;
&lt;li&gt;Struct and enum definitions.&lt;/li&gt;
&lt;li&gt;Impl blocks.&lt;/li&gt;
&lt;li&gt;Trait definitions.&lt;/li&gt;
&lt;li&gt;Type aliases.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Generic definitions
&lt;/h2&gt;

&lt;p&gt;We will cover generics in various Rust definitions, starting with generic functions.&lt;/p&gt;

&lt;h3&gt;
  
  
  Generic functions
&lt;/h3&gt;

&lt;p&gt;Let’s play around with some vectors. Imagine that we want to write a function that reverses elements of any vector, including &lt;code&gt;int_vector&lt;/code&gt; and &lt;code&gt;str_vector&lt;/code&gt; we’ve seen before. We can write specialized functions for different kinds of vectors, such as &lt;code&gt;int_reverse&lt;/code&gt;, &lt;code&gt;str_reverse&lt;/code&gt;, and so on:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn int_reverse(vector: &amp;amp;mut Vec&amp;lt;int&amp;gt;) {...}

fn str_reverse(vector: &amp;amp;mut Vec&amp;lt;&amp;amp;str&amp;gt;) {...}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the actual type of the elements doesn’t matter when reversing a vector, these functions would have the same implementation and differ only in the types of their parameters. This is where generic functions come in – we can create one generic &lt;code&gt;reverse&lt;/code&gt; function that is generic over the type of vector elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1][2] [3]
fn reverse&amp;lt;T&amp;gt;(vector: &amp;amp;mut Vec&amp;lt;T&amp;gt;) {
    let mut new_vector = Vec::new();

    while let Some(last) = vector.pop() {
        new_vector.push(last);
    }

    *vector = new_vector;
}

// [1]: The generic definition follows the function name.
// [2]: The function is generic over the type `T`.
// [3]: The function takes a reference to a generic vector as an argument.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;reverse&lt;/code&gt; function iterates over the elements of a vector using the &lt;code&gt;while&lt;/code&gt; loop. We get the elements in the reverse order because &lt;code&gt;pop&lt;/code&gt; removes the last element from a vector and returns it.&lt;/p&gt;

&lt;p&gt;We can use this generic function with both of our vectors, as well as any other vector:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut int_vector: Vec&amp;lt;i32&amp;gt; = vec![1, 2, 3];
reverse(&amp;amp;mut int_vector);
println!("After: {:?}", int_vector);
// Prints:
// After: [3, 2, 1]

let mut str_vector: Vec&amp;lt;&amp;amp;str&amp;gt; = vec!["one", "two", "three"];
reverse(&amp;amp;mut str_vector);
println!("After: {:?}", str_vector);
// Prints:
// After: ["three", "two", "one"]

let mut bool_vector: Vec&amp;lt;bool&amp;gt; = vec![true, false, false, false];
reverse(&amp;amp;mut bool_vector);
println!("After: {:?}", bool_vector);
// Prints:
// After: [false, false, false, true]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This time, we use the &lt;code&gt;vec!&lt;/code&gt; macro to create a vector with initial values and pretty-print it with &lt;code&gt;{:?}&lt;/code&gt;. The &lt;code&gt;reverse&lt;/code&gt; works, but don’t try this in production – better use the built-in function &lt;code&gt;vector.reverse&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To sum up, with generics we write one function and delegate the task of writing repetitive code for all the different types to the compiler.&lt;/p&gt;

&lt;h3&gt;
  
  
  Generic enums
&lt;/h3&gt;

&lt;p&gt;We can use generics in other definitions as well. For instance, &lt;a href="https://doc.rust-lang.org/std/option/enum.Option.html" rel="noopener noreferrer"&gt;&lt;code&gt;Option&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/a&gt; is a generic enum frequently encountered in Rust:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1][2]
pub enum Option&amp;lt;T&amp;gt; {
  None,
// [3]
  Some(T),
}

// [1]: The generic definition follows the enum name.
// [2]: The enum is generic over the type `T`.
// [3]: The `Some` takes an argument of type `T`.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because it’s generic, we can use &lt;code&gt;Option&lt;/code&gt; to wrap any type we like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let o1: Option&amp;lt;i32&amp;gt; = Some(1);
let o2: Option&amp;lt;&amp;amp;str&amp;gt; = Some("two");
let o3: Option&amp;lt;bool&amp;gt; = Some(true);
let o4: Option&amp;lt;f64&amp;gt; = Some(4.0);
...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example, we can use it to wrap integers (&lt;code&gt;Option&amp;lt;i32&amp;gt;&lt;/code&gt;) and implement a safe division function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn safe_division(a: i32, b: i32) -&amp;gt; Option&amp;lt;i32&amp;gt; {
    match b {
        0 =&amp;gt; None,
        _ =&amp;gt; Some(a / b),
    }
}

println!("{:?}", safe_division(4, 2));
// Prints:
// Some(2)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or we can use &lt;code&gt;Option&lt;/code&gt; to safely access the elements of the &lt;code&gt;str_vector&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;let str_vector = vec!["one", "two", "three"];

let head = str_vector.get(0);
println!("{:?}", head);
// Prints:
// Some("one")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The &lt;a href="https://doc.rust-lang.org/std/vec/struct.Vec.html#method.get" rel="noopener noreferrer"&gt;&lt;code&gt;get&lt;/code&gt;&lt;/a&gt; method is a safe way to access an element of the vector at a given position: it either returns a reference to the element wrapped in &lt;code&gt;Some&lt;/code&gt; or &lt;code&gt;None&lt;/code&gt; if the position is out of bounds.&lt;/p&gt;

&lt;h3&gt;
  
  
  Generic structs
&lt;/h3&gt;

&lt;p&gt;In the same way, we can create generic structs. Let’s imagine we need to create a struct that holds user scores. If our program supports multiple kinds of scores, we don’t want to repeat ourselves and write code for all the different score types; we can keep the score generic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1][2]
struct Score&amp;lt;T&amp;gt; {
    user: String,
// [3]
    team_score: T,
// [4]
    scores: Vec&amp;lt;T&amp;gt;,
}

// [1]: The generic definition follows the struct name.
// [2]: The struct is generic over the type `T`.
// [3]: The `team_score` field is of type `T`.
// [4]: The `scores` field is of type `Vec&amp;lt;T&amp;gt;`.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At the point of usage, when we assign values to the struct’s parameters, we commit to the specific type for &lt;code&gt;T&lt;/code&gt;. We can use any type for the score, for example, integer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let int_score: Score&amp;lt;i32&amp;gt; = Score {
    user: "Lesley".to_string(),
    team_score: 1_641_213,
    scores: vec![5213, 1232, 1512],
};

println!(
    "Int score: user = {}, scores = {:?}",
    int_score.user, int_score.scores
);
// Prints:
// Int score: user = Lesley, scores = [5213, 1232, 1512]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or float:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let flt_score = Score {
    user: "Simone".to_string(),
    team_score: 54.2526,
    scores: vec![4.2526],
};

println!(
    "Float score: user = {}, scores = {:?}",
    flt_score.user, flt_score.scores
);
// Prints:
// Float scores: user = Simone, scores = [4.2526]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that we didn’t specify the type of &lt;code&gt;flt_score&lt;/code&gt;; the compiler can automatically infer the struct type from the used values.&lt;/p&gt;

&lt;p&gt;The compiler ensures that the type of &lt;code&gt;team_score&lt;/code&gt; is the same as the type of &lt;code&gt;scores&lt;/code&gt; elements because they are defined as &lt;code&gt;T&lt;/code&gt;. For example, using an integer for one and a float for another doesn’t work:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let broken_score = Score {
    user: "Simone".to_string(),
    team_score: 100,
    scores: vec![4.2526],
};


error[E0308]: mismatched types
    |
    | scores: vec![4.2526],
    | ^^^^^^ expected integer, found floating-point number

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Generic methods
&lt;/h3&gt;

&lt;p&gt;Furthermore, we can implement a generic method on generic structs. For example, we can implement a method to get the last score (assuming that &lt;code&gt;scores&lt;/code&gt; preserves the order):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1] [2]
impl&amp;lt;T&amp;gt; Score&amp;lt;T&amp;gt; {
// [3]
    fn last_score(&amp;amp;mut self) -&amp;gt; Option&amp;lt;&amp;amp;T&amp;gt; {
        self.scores.last()
    }
}

// [1]: The generic definition follows the `impl` keyword.
// [2]: The struct is generic over the type `T`.
// [3]: The function's return value is generic over `T`
// (It returns an optional reference to a value of type `T`).

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 &lt;strong&gt;Why are there multiple &lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, we declare the type parameter (&lt;code&gt;T&lt;/code&gt;) after the &lt;code&gt;impl&lt;/code&gt; keyword (&lt;code&gt;impl&amp;lt;T&amp;gt;&lt;/code&gt;), and then we use other &lt;code&gt;T&lt;/code&gt;s to refer to that first &lt;code&gt;T&lt;/code&gt;: to specify the struct type we are implementing (&lt;code&gt;Score&amp;lt;T&amp;gt;&lt;/code&gt;) or specify the return type (&lt;code&gt;Option&amp;lt;&amp;amp;T&amp;gt;&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;The distinction between these becomes more clear when we have more complex types; 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;impl&amp;lt;T&amp;gt; Pair&amp;lt;T, T&amp;gt; { ... }


impl&amp;lt;T&amp;gt; MyStruct&amp;lt;Vec&amp;lt;T&amp;gt;&amp;gt; { ... }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;We can use the &lt;code&gt;last_score&lt;/code&gt; method with any type of score:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let int_score: Score&amp;lt;i32&amp;gt; = Score {
    user: "Lesley".to_string(),
    team_score: 1_641_213,
    scores: vec![5213, 1232, 1512],
};

let last_int_score = int_score.last_score();
println!("Last score: {:?}", last_int_score);
// Prints:
// Last score: Some(1512)

let flt_score = Score {
    user: "Simone".to_string(),
    team_score: 54.2526,
    scores: vec![4.2526],
};

let last_flt_score = flt_score.last_score();
println!("Last score: {:?}", last_flt_score);
// Prints:
// Last score: Some(4.2526)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to constrain a generic type
&lt;/h2&gt;

&lt;p&gt;We’ve covered a few generics that take &lt;strong&gt;any&lt;/strong&gt; possible type: &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt;, &lt;code&gt;Option&amp;lt;T&amp;gt;&lt;/code&gt;, etc. This flexibility doesn’t come for free. Not knowing anything about the type limits the kind of things we can do with the values of this type: we can’t print them, compare them, etc.&lt;/p&gt;

&lt;p&gt;At least, in the previous examples, we knew something about the type of container, which allowed us to implement some functionality. What if we only have the type &lt;code&gt;T&lt;/code&gt;? Imagine a simple generic function that accepts a value of one type and returns a value of the same type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn quick_adventure&amp;lt;T&amp;gt;(t: T) -&amp;gt; T

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We don’t know anything about &lt;code&gt;T&lt;/code&gt;. The only thing we can do is return the parameter’s value. Quite boring and limiting:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn quick_adventure&amp;lt;T&amp;gt;(t: T) -&amp;gt; T {
    t
}

println!("{}", quick_adventure(17));
// Prints:
// 17

println!("{}", quick_adventure("out"));
// Prints:
// out

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 When we write a polymorphic function that works for different types, we limit the possibilities in implementation. For example, we can easily add or multiply if we write a function that works for a pair of integers. But if we write a function that works both for a pair of integers and a pair of strings, we can’t because strings don’t support these operations. However, we can use shared operations, like comparing two elements that work for integer and string values.&lt;/p&gt;

&lt;p&gt;Generics improve code readability. A “very” generic function can be, in great measure, described by the types themselves, which additionally serve as documentation.&lt;/p&gt;




&lt;p&gt;Let’s look at a more practical example. We implemented a generic &lt;code&gt;reverse&lt;/code&gt; function that reverses a vector in place. What if we change it and try to print the values instead of updating the vector?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn reverse_print&amp;lt;T&amp;gt;(vector: &amp;amp;mut Vec&amp;lt;T&amp;gt;) {
    while let Some(last) = vector.pop() {
        println!("{}", last);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It doesn’t compile!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0277]: `T` doesn't implement `std::fmt::Display`
    |
    | println!("{}", last);
    | ^^^^ `T` cannot be formatted with the default formatter
    |
help: consider restricting type parameter `T`
    |
    | fn reverse_print&amp;lt;T: std::fmt::Display&amp;gt;(vector: &amp;amp;mut Vec&amp;lt;T&amp;gt;) {
    | +++++++++++++++++++

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The compiler doesn’t know anything about the type. How is it supposed to print it? The error message suggests we should consider restricting the type parameter. Spoiler alert, we can do this with trait bounds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; If traits are fresh on your mind or you’ve recently read our article &lt;a href="https://serokell.io/blog/rust-traits" rel="noopener noreferrer"&gt;Traits in Rust&lt;/a&gt;, you can skip the following recap.&lt;/p&gt;

&lt;h3&gt;
  
  
  Recap on traits
&lt;/h3&gt;

&lt;p&gt;Traits allow us to define interfaces or shared behaviors on types. To implement a trait for a type, we must implement methods of that trait.&lt;/p&gt;

&lt;p&gt;All types implementing a given trait must support the functionality defined by this trait. For example, if we want to compare values of some type, it has to implement &lt;code&gt;PartialEq&lt;/code&gt; and &lt;code&gt;PartialOrd&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;#[derive(PartialEq, PartialOrd)]
struct LevelScore {
    main_score: i32,
    bonus_score: i32,
}

let my_score = LevelScore {
    main_score: 10,
    bonus_score: 5,
};

let your_score = LevelScore {
    main_score: 5,
    bonus_score: 2,
};

if my_score &amp;gt; your_score {
    println!("I have a bigger score!")
} else {
    println!("You have a bigger score!")
}
// Prints:
// I have a bigger score!

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Otherwise, we would get an error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// #[derive(PartialEq, PartialOrd)]
struct LevelScore {
    main_score: i32,
    bonus_score: i32,
}


error[E0369]: binary operation `&amp;gt;` cannot be applied to type `LevelScore`
    |
    | if my_score &amp;gt; your_score {
    | -------- ^ ---------- LevelScore
    | |
    | LevelScore
    |
note: an implementation of `PartialOrd&amp;lt;_&amp;gt;` might be missing for `LevelScore`
    |
    | struct LevelScore {
    | ^^^^^^^^^^^^^^^^^ must implement `PartialOrd&amp;lt;_&amp;gt;`
help: consider annotating `LevelScore` with `#[derive(PartialEq, PartialOrd)]`
    |
    | #[derive(PartialEq, PartialOrd)]
    |

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A trait is an interface that defines behaviors with a contract that other code can rely on. We can implement functions that accept types implementing our trait. These functions don’t need to know anything else about these types.&lt;/p&gt;

&lt;h3&gt;
  
  
  Trait bounds on generic functions
&lt;/h3&gt;

&lt;p&gt;Traits allow us to make certain promises about the type of behavior. We can use traits and generics to constrain a generic type, so it accepts only the types with a particular behavior and not just any type. As an example, we can restrict the generic type in &lt;code&gt;reverse_print&lt;/code&gt; using a trait bound:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::fmt::Display;

// [1] [2]
fn reverse_print&amp;lt;T: Display&amp;gt;(vector: &amp;amp;mut Vec&amp;lt;T&amp;gt;) {
    while let Some(last) = vector.pop() {
// [3]
        println!("{}", last);
    }
}

// The function is
// [1]: generic over `T` that is
// [2]: bound by the `Display` trait, which guarantees
// [3]: that values of type `T` can be printed.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;&amp;lt;T: Display&amp;gt;&lt;/code&gt; is the syntax to declare a generic type parameter with a trait bound. In this case, it means that &lt;code&gt;T&lt;/code&gt; is any type that implements the &lt;code&gt;Display&lt;/code&gt; trait, which also means that we can print it.&lt;/p&gt;

&lt;p&gt;Because string slices and integers implement the &lt;code&gt;Display&lt;/code&gt; trait, we can use &lt;code&gt;reverse_print&lt;/code&gt; with both &lt;code&gt;str_vector&lt;/code&gt; and &lt;code&gt;int_vector&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;let mut str_vector: Vec&amp;lt;&amp;amp;str&amp;gt; = vec!["one", "two", "three"];
reverse_print(&amp;amp;mut str_vector);
// Prints:
// three
// two
// one

let mut int_vector: Vec&amp;lt;i32&amp;gt; = vec![1, 2, 3];
reverse_print(&amp;amp;mut int_vector);
// Prints:
// 3
// 2
// 1

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it doesn’t work with types that don’t implement &lt;code&gt;Display&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;struct LevelScore(i32, i32);

let mut score_vector = vec![LevelScore(10, 5), LevelScore(5, 20)];

reverse_print(&amp;amp;mut score_vector);


error[E0277]: `LevelScore` doesn't implement `std::fmt::Display`
    |
    | reverse_print(&amp;amp;mut score_vector);
    | ------------- ^^^^^^^^^^^^^^^^^ `LevelScore` cannot be formatted with the default formatter
    | |
    | required by a bound introduced by this call
    |
    = help: the trait `std::fmt::Display` is not implemented for `LevelScore`
note: required by a bound in `reverse_print`

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Trait bounds on type parameters let us tell the compiler that we want the generic type to have particular behavior.&lt;/p&gt;

&lt;h3&gt;
  
  
  Multiple trait bounds
&lt;/h3&gt;

&lt;p&gt;We can specify more than one trait bound. Let’s write another generic function that works with vectors: &lt;code&gt;print_max&lt;/code&gt; should find and print the maximum element, which we can find by using the corresponding iterator and its method &lt;code&gt;max&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;use std::fmt::Display;

// [1]
fn print_max&amp;lt;T: Ord + Display&amp;gt;(elements: &amp;amp;[T]) {
    match elements.iter().max() {
        Some(max_value) =&amp;gt; println!("Max value: {}", max_value),
        None =&amp;gt; println!("Vector is empty"),
    }
}

// [1]: We use `+` to specify multiple traits.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This time, because we need to compare and print elements, we tell the compiler that &lt;code&gt;T&lt;/code&gt; can only be the types that implement both &lt;code&gt;Ord&lt;/code&gt; and &lt;code&gt;Display&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;💡 Because we don’t change the number of items, it’s recommended to use a slice (&lt;code&gt;&amp;amp;[T]&lt;/code&gt;) instead of a vector &lt;code&gt;&amp;amp;Vec&amp;lt;T&amp;gt;&lt;/code&gt;. If you want to refresh your knowledge, check out &lt;a href="https://doc.rust-lang.org/book/ch04-03-slices.html#the-slice-type" rel="noopener noreferrer"&gt;The Slice Type&lt;/a&gt; in the Rust book.&lt;/p&gt;




&lt;p&gt;There is an alternative syntax that helps make the function signature cleaner. Instead of writing the trait bound with the type parameter declaration, we can list traits after the function parameters:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::fmt::Display;

fn print_max&amp;lt;T&amp;gt;(elements: &amp;amp;[T]) // [1]
where // [2]
    T: Ord + Display, // [3]
{
    match elements.iter().max() {
        Some(max_value) =&amp;gt; println!("Max value: {}", max_value),
        None =&amp;gt; println!("Vector is empty"),
    }
}

// [1]: The function signature is followed by
// [2]: `where` clause, where we 
// [3]: specify the trait bounds.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With either syntax, the &lt;code&gt;print_max&lt;/code&gt; function works with any vector of elements, as long as their type implements both &lt;code&gt;Ord&lt;/code&gt; and &lt;code&gt;Display&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;let mut int_vector = vec![10, 200, 3];
print_max(&amp;amp;int_vector);
// Prints:
// Max value: 200

let mut str_vector = vec!["Go", "Scrabble", "Battleship", "Monopoly"];
print_max(&amp;amp;str_vector);
// Prints:
// Max value: Scrabble

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Trait bounds on other generics
&lt;/h3&gt;

&lt;p&gt;Trait bounds aren’t limited to generic functions. We can restrict any type parameter using traits.&lt;/p&gt;

&lt;p&gt;For example, we can use trait bounds on generic structs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1]
struct GameScore&amp;lt;T: Ord&amp;gt; {
    name: String,
    scores: Vec&amp;lt;T&amp;gt;,
}

impl&amp;lt;T: Ord&amp;gt; GameScore&amp;lt;T&amp;gt; {
    fn high_score(&amp;amp;self) -&amp;gt; Option&amp;lt;&amp;amp;T&amp;gt; {
// [2]
        self.scores.iter().max()
    }
}

// [1]: We bound `T` with the `Ord` trait.
// [2]: So we can use `max` to return the maximum score.


let taylor_score = GameScore {
    name: "taylor".to_string(),
    scores: vec![10, 200, 3],
};

println!("{:?}", taylor_score.high_score());
// Prints:
// Some(200)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We don’t have to restrict the whole struct. We can limit implementations; in other words, we can conditionally implement methods for types that implement specific traits. For example, we can create two &lt;code&gt;GameScore&lt;/code&gt; methods: &lt;code&gt;high_score&lt;/code&gt; that can be used when vector elements implement &lt;code&gt;Ord&lt;/code&gt; and &lt;code&gt;reverse_print_scores&lt;/code&gt; – when they implement &lt;code&gt;Display&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;use std::fmt::Display;

struct GameScore&amp;lt;T&amp;gt; {
    name: String,
    scores: Vec&amp;lt;T&amp;gt;,
}

impl&amp;lt;T: Ord&amp;gt; GameScore&amp;lt;T&amp;gt; {
    fn high_score(&amp;amp;self) -&amp;gt; Option&amp;lt;&amp;amp;T&amp;gt; {
        self.scores.iter().max()
    }
}

impl&amp;lt;T: Display&amp;gt; GameScore&amp;lt;T&amp;gt; {
    fn reverse_print_scores(&amp;amp;mut self) {
        while let Some(last) = self.scores.pop() {
            println!("{}", last);
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the case of integer vector, we can use both:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut taylor_score = GameScore {
    name: "taylor".to_string(),
    scores: vec![10, 200, 3],
};

println!("{:?}", taylor_score.high_score());
// Prints:
// Some(200)

taylor_score.reverse_print_scores();
// Prints:
// 3
// 200
// 10

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But if we have a custom type that only implements &lt;code&gt;Ord&lt;/code&gt;, we can only use one of the methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(PartialEq, PartialOrd, Eq, Ord, Debug)]
struct LevelScore(i32, i32);

let mut dale_score = GameScore {
    name: "Dale".to_string(),
    scores: vec![LevelScore(10, 5), LevelScore(5, 20)],
};

println!("{:?}", dale_score.high_score());
// Prints:
// Some(LevelScore(10, 5))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Calling the second method doesn’t compile because &lt;code&gt;LevelScore&lt;/code&gt; doesn’t implement &lt;code&gt;Display&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;dale_score.reverse_print_scores();


error[E0599]: the method `reverse_print_scores` exists for struct `GameScore&amp;lt;LevelScore&amp;gt;`, but its trait bounds were not satisfied
    |
    | struct GameScore&amp;lt;T&amp;gt; {
    | ------------------- method `reverse_print_scores` not found for this
...
    | struct LevelScore(i32, i32);
    | ---------------------------- doesn't satisfy `LevelScore: std::fmt::Display`
...
    | dale_score.reverse_print_scores();
    | ^^^^^^^^^^^^^^^^^^^^ method cannot be called on `GameScore&amp;lt;LevelScore&amp;gt;` due to unsatisfied trait bounds
    |

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Generics allows us to write both more flexible and more restrictive code. When we use generics, we can write generic code for multiple types and not worry about the implementation for concrete types.&lt;/p&gt;

&lt;p&gt;We learned how to use generics to write less code, create generic functions, structs, enums, methods, or traits, and restrict generics with trait bounds.&lt;/p&gt;

&lt;p&gt;This blog post covered how to achieve compile-time polymorphism (generic code) using generics. We can use trait objects to get a run-time polymorphism (similar to virtual functions in other languages). In the Rust Book, you can read about &lt;a href="https://doc.rust-lang.org/book/ch17-02-trait-objects.html" rel="noopener noreferrer"&gt;using trait objects&lt;/a&gt; to allow functions to perform dynamic dispatch and return different types at run-time.&lt;/p&gt;

&lt;p&gt;Lifetimes are another kind of generics that give the compiler information about how references relate to each other. We can ensure that references are valid as long as we want them. A good starting point is the &lt;a href="https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html" rel="noopener noreferrer"&gt;Validating References with Lifetimes&lt;/a&gt; chapter of the Rust Book.&lt;/p&gt;

&lt;p&gt;If you would like to read more beginner-friendly articles about Rust, be sure to follow us on &lt;a href="https://twitter.com/serokell" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; or subscribe to our newsletter via the form below.&lt;/p&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Machine Learning Trends for 2023</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Mon, 02 Jan 2023 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/machine-learning-trends-for-2023-5e4i</link>
      <guid>https://dev.to/serokell/machine-learning-trends-for-2023-5e4i</guid>
      <description>&lt;p&gt;Machine learning and artificial intelligence is a field that drives major innovations across different industries. It is predicted that in 2023, the AI market will reach $500 billion, and in 2030, &lt;a href="https://www.precedenceresearch.com/artificial-intelligence-market" rel="noopener noreferrer"&gt;$1,597.1 billion&lt;/a&gt; in size. This means that machine learning technologies will continue to be in high demand in the near future.&lt;/p&gt;

&lt;p&gt;However, the machine learning industry evolves very rapidly: new technologies and scientific research define how new products and services are built. At the end of 2022, everyone, from machine learning engineers to startup founders, is on the lookout for the most promising trends for the next year. If you want to learn about some of the hottest trends for the upcoming year, continue reading this article.&lt;/p&gt;

&lt;h2&gt;
  
  
  Machine learning technology trends
&lt;/h2&gt;

&lt;p&gt;We can never predict with 100% certainty what kind of technologies will be in demand next year, since new innovations appear every day. But here are some of the most promising machine learning trends for 2023, based on what we have seen in 2022.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Foundation models
&lt;/h3&gt;

&lt;p&gt;Large language models are an important innovation that has gained popularity recently and is most likely to stay with us in the nearest future. Foundation models are artificial intelligence tools that are trained on immense amounts of data, even compared to regular neural networks.&lt;/p&gt;

&lt;p&gt;Engineers try to achieve a new level of understanding by teaching the machines to not just search for patterns but also accumulate knowledge. Foundation models are incredibly helpful in content generation and summarization, coding and translation, and customer support. Well-known examples of foundation models are &lt;a href="https://arstechnica.com/information-technology/2022/11/openai-conquers-rhyming-poetry-with-new-gpt-3-update/" rel="noopener noreferrer"&gt;GPT-3&lt;/a&gt; and &lt;a href="https://midjourney.com/" rel="noopener noreferrer"&gt;MidJourney&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;An amazing thing about foundation models is that they can also scale fast and work with data they have never seen before, hence their wonderful generating capabilities. Leading providers of these solutions are &lt;a href="https://www.nvidia.com/en-us/deep-learning-ai/solutions/large-language-models/" rel="noopener noreferrer"&gt;NVIDIA&lt;/a&gt; and &lt;a href="https://openai.com/" rel="noopener noreferrer"&gt;Open AI&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Multimodal machine learning
&lt;/h3&gt;

&lt;p&gt;In such tasks as computer vision or natural language processing that involve interaction between the model and the real world, the model often has to rely only on one type of data, be it images or text. But in real life, we perceive the world around us through many senses: smell, hearing, feeling textures, and flavors.&lt;/p&gt;

&lt;p&gt;Multimodal machine learning suggests using the fact that the world around us can be experienced in multiple ways (called modalities) to build better models. The term “multimodal” in AI describes how to build ML models that can perceive the event in multiple modalities at a time, just like humans do.&lt;/p&gt;

&lt;p&gt;Building an MML can be achieved through combining different types of information and using them in training. For example, matching images with audio and text labels to make them easier to recognize. Multimodal machine learning is so far a young field that is yet to be developed and advanced in 2023, but many believe that it can be key to &lt;a href="https://www.nature.com/articles/s41467-022-30761-2" rel="noopener noreferrer"&gt;achieving general AI&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Transformers
&lt;/h3&gt;

&lt;p&gt;Transformers are a type of artificial intelligence architecture that performs transduction (or transformation) on an input sequence of data using encoder and decoder and transforms it into another sequence. Many foundation models are also built on transformers. However, we wanted to point them out separately since they are used for many other applications. In fact, it is reported that transformers are &lt;a href="https://exchange.scale.com/public/blogs/state-of-ai-report-2021-transformers-taking-ai-world-by-storm-nathan-benaich" rel="noopener noreferrer"&gt;taking the AI world by storm&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Also called Seq2Seq models, transformers are widely used in translation and other natural language processing tasks. Because transformers can analyze sequences of words rather than individual words, they generally show better results than ordinary artificial neural networks.&lt;/p&gt;

&lt;p&gt;Rather than simply taking all words in a sentence and translating them word by word, a transformer model is able to assign weights that assess the importance to each word in the sequence. Then, the model transforms it into a sentence in a different language that takes in consideration the assigned weights. Some of the leading solutions that can help you build transformer pipelines are &lt;a href="https://huggingface.co/" rel="noopener noreferrer"&gt;Hugging Face&lt;/a&gt; and &lt;a href="https://aws.amazon.com/comprehend/" rel="noopener noreferrer"&gt;Amazon Comprehend&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Embedded machine learning
&lt;/h3&gt;

&lt;p&gt;Embedded machine learning (or TinyML) is a subfield of machine learning that enables machine learning technologies to run on different devices.&lt;/p&gt;

&lt;p&gt;TinyML is used in household appliances, smartphones, and laptops, smart home systems, and more. As Lian Jye Su, AI &amp;amp; ML Principal Analyst at ABI Research &lt;a href="https://www.prnewswire.com/news-releases/tinyml-device-shipments-to-grow-to-2-5-billion-in-2030--up-from-15-million-in-2020--301290160.html" rel="noopener noreferrer"&gt;explains&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The proliferation and democratization of AI has fueled the growth of Internet of Things (IoT) analytics. Data collected from IoT devices are used to train Machine Learning (ML) models, generating valuable new insights into the IoT overall. These applications require powerful and expensive solutions that rely on complex chipsets.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The rising popularity of embedded machine learning systems is one of the major drives of the chipset manufacturing industry. If ten years ago, the number of transistors on a chipset doubled every two years, according to Moore’s law, which allowed us to predict the increase in computational power as well, in the last few years, we have seen a 40-60% leap per year. We believe that this tendency will persist in the upcoming years as well.&lt;/p&gt;

&lt;p&gt;With the wider proliferation of IoT technologies and robotics, embedded systems have gained even more importance. Tiny ML poses its own unique challenges that are yet to be resolved in 2023 as it requires maximum optimization and efficiency while saving resources.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Low-code and no-code solutions
&lt;/h3&gt;

&lt;p&gt;Machine learning and AI have penetrated literally every field from agriculture to marketing to banking. Making ML solutions easy to use by non-techy employees is often considered by managers as a key to maintaining the efficiency of the whole organization.&lt;/p&gt;

&lt;p&gt;However, instead of putting stuff through the long and costly process of learning programming, it’s much easier to simply choose apps that require zero or close to zero coding skills. But this is not the only issue no-code solutions are likely to solve.&lt;/p&gt;

&lt;p&gt;Gartner has found that the demand for high-quality solutions on the market is bigger than the possibilities to deliver – “it &lt;a href="https://www.gartner.com/smarterwithgartner/how-to-deliver-enterprise-mobile-apps-faster" rel="noopener noreferrer"&gt;grows at least 5x faster&lt;/a&gt; than IT capacity to deliver them”. No-code and low-code solutions can help bridge this gap and satisfy the demand. Similarly, low-code solutions enable tech teams alike to come up and test their hypothesis faster, reducing time-to-delivery and development costs. If 10 years ago, it would take a whole team of people to build an application or launch a website, today just one person can do the same and do it fast.&lt;/p&gt;

&lt;p&gt;Moreover, &lt;a href="https://adtmag.com/articles/2018/01/30/low-code-surveys.aspx" rel="noopener noreferrer"&gt;82% of organizations&lt;/a&gt; experience difficulties attracting and retaining the quality and quantity of software engineers and are willing to build and maintain their apps with the help of no-code and low-code techniques.&lt;/p&gt;

&lt;p&gt;While many low-code and no-code solutions have appeared in recent years, the general trend is that they still are inferior in quality compared to regular development. Startups that will be able to improve the situation will win on the AI market.&lt;/p&gt;

&lt;p&gt;Finally, it is worth mentioning that with the rapidly increasing computational power that is required to train an ML model (especially for real-time ML that runs in large organizations), cloud computing remains an important technology that lays behind the innovations. According to &lt;a href="https://explodingtopics.com/blog/cloud-computing-stats#top-cloud-computing-stats" rel="noopener noreferrer"&gt;statistics&lt;/a&gt;, about 60% of the world’s corporate data is stored in the cloud, and this number is likely to grow. In 2023, we will see &lt;a href="https://www.forbes.com/sites/bernardmarr/2022/10/17/the-top-5-cloud-computing-trends-in-2023/" rel="noopener noreferrer"&gt;increased investment in cloud security and resilience&lt;/a&gt; to satisfy the growing needs of the ML industry.&lt;/p&gt;

&lt;h2&gt;
  
  
  Top technological segments for ML in 2023
&lt;/h2&gt;

&lt;p&gt;Gartner &lt;a href="(https://www.gartner.com/smarterwithgartner/gartner-predicts-the-future-of-ai-technologies)"&gt;has defined the technological segments&lt;/a&gt; that are expected to have obtained the most machine learning presence in the next 7-8 years. Among the leading areas that they have mentioned are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Creative artificial intelligence.&lt;/strong&gt; AI used for generative texts, code, and even images and video has gained wide popularity in 2022, especially with the release of state-of-the-art image generation network by &lt;a href="https://midjourney.com/" rel="noopener noreferrer"&gt;MidJourney&lt;/a&gt;, &lt;a href="https://openai.com/dall-e-2/" rel="noopener noreferrer"&gt;DALLE-2&lt;/a&gt;, &lt;a href="https://huggingface.co/spaces/stabilityai/stable-diffusion" rel="noopener noreferrer"&gt;Stable Diffusion&lt;/a&gt;, and the new &lt;a href="https://beta.openai.com/playground?model=text-davinci-003" rel="noopener noreferrer"&gt;text-davinci-003&lt;/a&gt; by Open AI. Products and services that use generational AI for fashion, creativity, and marketing will be in high demand in 2023.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Distributed enterprise management.&lt;/strong&gt; With remote work becoming a norm, companies were bound to look for new ways to manage the workforce and maintain efficiency. According to Gartner, ML will help distributed companies to grow and increase their income.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Automation.&lt;/strong&gt; Autonomous software systems that can take on increasingly complicated tasks and adapt to quickly changing conditions are in high demand in many industries from security to banking. New innovations that provide for smarter automation will appear in 2023.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cybersecurity.&lt;/strong&gt; The importance of cybersecurity is growing every year with increasing digitalization of various fields of life and the necessity to protect sensitive information. ML and AI are believed to be crucial in the role of protecting private data and securing organizations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In 2023, machine learning will continue to be a promising and rapidly growing field that will present many interesting innovations. Large language models, multimodal machine learning, transformers, TinyML, and no-code and low-code solutions are the emerging technologies that will gain considerable importance in the near future.&lt;/p&gt;

&lt;p&gt;Some of the technical segments that will increasingly use ML in 2023 are creative AI, autonomous systems, distributed enterprise management, and cyber security. Gartner predicts that in 2023, ML will penetrate even more business fields helping to increase efficiency and work security.&lt;/p&gt;

&lt;p&gt;If you want to continue learning the latest news and gain inspiration from the leading professionals in the ML industry, stay tuned to our blog and follow us on &lt;a href="https://twitter.com/serokell" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>ai</category>
    </item>
    <item>
      <title>Get Started with Rust: Traits</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Mon, 07 Nov 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/get-started-with-rust-traits-4k40</link>
      <guid>https://dev.to/serokell/get-started-with-rust-traits-4k40</guid>
      <description>&lt;h1&gt;
  
  
  Get Started with Rust: Traits
&lt;/h1&gt;

&lt;p&gt;A trait is a basic language concept for defining shared behavior on types. Traits describe an interface that types can implement.&lt;/p&gt;

&lt;p&gt;Rust traits are a sibling of &lt;a href="https://docs.scala-lang.org/tour/traits.html"&gt;Scala traits&lt;/a&gt; and &lt;a href="https://serokell.io/blog/haskell-typeclasses"&gt;Haskell type classes&lt;/a&gt;, as well as a cousin of C++ and Java interfaces.&lt;/p&gt;

&lt;p&gt;This article will show you how to use traits in Rust. After reading it, you’ll be able to answer these questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What is a trait?&lt;/li&gt;
&lt;li&gt;Why do we use traits in Rust?&lt;/li&gt;
&lt;li&gt;How to implement and define traits in Rust?&lt;/li&gt;
&lt;li&gt;What does it mean to derive a trait, and when can we do it?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We expect that you are somewhat familiar with &lt;a href="https://serokell.io/blog/structs-in-rust"&gt;structs&lt;/a&gt; and &lt;a href="https://serokell.io/blog/enums-and-pattern-matching"&gt;enums&lt;/a&gt; in Rust.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a trait?
&lt;/h2&gt;

&lt;p&gt;Traits allow us to define interfaces or shared behaviors on types. To implement a trait for a type, we need to implement methods of that trait.&lt;/p&gt;

&lt;p&gt;For example, let’s look at the simplified version of the &lt;a href="https://doc.rust-lang.org/std/cmp/trait.PartialEq.html"&gt;&lt;code&gt;PartialEq&lt;/code&gt;&lt;/a&gt; trait, which allows us to define equality for user-defined types:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;trait PartialEq {
    fn eq(&amp;amp;self, other: &amp;amp;Self) -&amp;gt; bool;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a type to implement &lt;code&gt;PartialEq&lt;/code&gt;, it needs to implement its method: &lt;code&gt;eq&lt;/code&gt;. Implementing it allows us to write &lt;code&gt;x == y&lt;/code&gt; and &lt;code&gt;x != y&lt;/code&gt; for this type.&lt;/p&gt;

&lt;h2&gt;
  
  
  Traits are everywhere
&lt;/h2&gt;

&lt;p&gt;You don’t need to dig too deep to find traits in Rust. Let’s look at a couple of examples.&lt;/p&gt;

&lt;p&gt;You might be familiar with &lt;code&gt;for&lt;/code&gt; loops:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for i in [1, 2, 3] {
    println!("{i}");
}
// Prints: 
// 1
// 2
// 3

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust’s &lt;code&gt;for&lt;/code&gt; loop syntax is actually syntactic sugar for &lt;a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html"&gt;iterators&lt;/a&gt;, which are responsible for the logic of iterating over some items.&lt;/p&gt;

&lt;p&gt;There’s a trait in the standard library for converting something into an iterator called &lt;a href="https://doc.rust-lang.org/std/iter/trait.IntoIterator.html"&gt;&lt;code&gt;IntoIterator&lt;/code&gt;&lt;/a&gt;. This is usually implemented for types that describe a collection. This includes Vectors, HashMaps, and Options.&lt;/p&gt;

&lt;p&gt;Let’s look at another example.&lt;/p&gt;

&lt;p&gt;Imagine that we’ve defined a simple &lt;code&gt;Book&lt;/code&gt; struct and created an instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Book {
    title: String,
    author: String
}

let my_book = Book {
    title: String::from("Case of the Stuffed Goose"),
    author: String::from("Theo Witty"),
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What can we do with it? Can we print a book?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;println!("My book: {my_book}");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;No. The code doesn’t compile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: `Book` doesn't implement `std::fmt::Display`
help: the trait `std::fmt::Display` is not implemented for `Book`

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the compiler gives us a hint. &lt;code&gt;std::fmt::Display&lt;/code&gt; is a trait that we must implement for our &lt;code&gt;Book&lt;/code&gt; struct if we want to print it out.&lt;/p&gt;

&lt;p&gt;What else can we try? Can we compare two books?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let your_book = Book {
    title: String::from("Case of the Shrieking Bacon"),
    author: String::from("Casey Fennimore"),
};

if my_book == your_book {
    ...
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also no. We get a slightly different, but similar compilation error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: binary operation `==` cannot be applied to type `Book`
   |
   | my_book == your_book
   | ------- ^^ --------- Book
   | |
   | Book
   |
note: an implementation of `PartialEq&amp;lt;_&amp;gt;` might be missing for `Book`
help: consider annotating `Book` with `#[derive(PartialEq)]`
   |
   | #[derive(PartialEq)]
   |

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We must implement &lt;code&gt;PartialEq&lt;/code&gt; for our &lt;code&gt;Book&lt;/code&gt; struct if we want to check for equality using the &lt;code&gt;==&lt;/code&gt; operator.&lt;/p&gt;

&lt;p&gt;We’ve got a hint that we should provide an implementation for these traits. Let’s do that next.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to implement a trait?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  How to implement a trait manually?
&lt;/h3&gt;

&lt;p&gt;We should keep in mind that a trait defines an interface. In order for a type to implement a trait, it must provide definitions of all the required methods.&lt;/p&gt;

&lt;p&gt;Let’s implement the &lt;code&gt;PartialEq&lt;/code&gt; trait for &lt;code&gt;Book&lt;/code&gt;. The only method we have to define is &lt;code&gt;eq&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;impl PartialEq for Book {
    fn eq(&amp;amp;self, other: &amp;amp;Self) -&amp;gt; bool {
        self.title == other.title &amp;amp;&amp;amp; self.author == other.author
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are a lot of new words at once, so let’s take a closer look. The first line defines the trait implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//[1][2] [3] [4]
impl PartialEq for Book {

// [1]: `impl` keyword.
// [2]: The trait name (in this case, PartialEq).
// [3]: `for` keyword.
// [4]: The type name (in this case, Book).

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we have to define the method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1][2] [3]
    fn eq(&amp;amp;self, other: &amp;amp;Self) -&amp;gt; bool {
// [4]
        self.title == other.title &amp;amp;&amp;amp; self.author == other.author
    }
}

// [1]: Trait instance method has
// [2]: the **&amp;amp;self** parameter as the first parameter;
// [3]: any extra parameters must come after.
// [4]: Implementation details.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; &lt;code&gt;eq&lt;/code&gt; is an instance method – a trait method that requires an instance of the implementing type via the &lt;code&gt;&amp;amp;self&lt;/code&gt; argument. Traits can also define static methods that don’t require an instance and do not have &lt;code&gt;&amp;amp;self&lt;/code&gt; as their first parameter, but we aren’t going to cover them here.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;self&lt;/code&gt; is an instance of the implementing type that gives us access to its internals. For example, we can get our struct fields with &lt;code&gt;self.title&lt;/code&gt; and &lt;code&gt;self.author&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The actual implementation of &lt;code&gt;eq&lt;/code&gt; is quite primitive. We compare each field between the structs and make sure that all of them are equal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    self.title == other.title &amp;amp;&amp;amp; self.author == other.author

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 &lt;strong&gt;&lt;code&gt;&amp;amp;self&lt;/code&gt; is syntactic sugar for &lt;code&gt;self: &amp;amp;Self&lt;/code&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Self&lt;/code&gt; keyword is only available within type definitions, trait definitions, and &lt;code&gt;impl&lt;/code&gt; blocks. In trait definitions, &lt;code&gt;Self&lt;/code&gt; stands for the implementing type. For more information, see &lt;a href="https://doc.rust-lang.org/reference/paths.html#self-1"&gt;The Rust Reference&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;We can compare our books now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if my_book == your_book {
    println!("We have the same book!");
} else {
    println!("We have different books.");
}
// Prints: 
// We have different books.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;💡 &lt;strong&gt;Which common traits should my types implement?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is no list of required traits. If you are writing an application, implement traits that you need as the need arises. If you are writing a library that will be used by others, it’s trickier. On the one hand, not adding a trait can limit your library users. On the other hand, removing a “wrong” trait is not backward-compatible. You can find more information on interoperability in the &lt;a href="https://rust-lang-nursery.github.io/api-guidelines/interoperability.html"&gt;Rust API Guidelines&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;Defining traits can be tedious and error-prone. That’s why it’s common to ask the compiler for help. The Rust compiler can provide an implementation for some of the traits via the derive mechanism.&lt;/p&gt;

&lt;h3&gt;
  
  
  Deriving a trait
&lt;/h3&gt;

&lt;p&gt;Let’s drop the &lt;code&gt;PartialEq&lt;/code&gt; implementation for the &lt;code&gt;Book&lt;/code&gt; and rewind back to the compiler error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: binary operation `==` cannot be applied to type `Book`
   |
   | my_book == your_book
   | ------- ^^ --------- Book
   | |
   | Book
   |
note: an implementation of `PartialEq&amp;lt;_&amp;gt;` might be missing for `Book`
help: consider annotating `Book` with `#[derive(PartialEq)]`
   |
   | #[derive(PartialEq)]
   |

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The compiler not only tells us what the issue is but also suggests a solution for it. Let’s follow the instructions and annotate the &lt;code&gt;Book&lt;/code&gt; struct with &lt;code&gt;#[derive(PartialEq)]&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;#[derive(PartialEq)]
struct Book {
    title: String,
    author: String
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can compare the books again and it should behave the same:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if my_book == your_book {
    println!("We have the same book!");
} else {
    println!("We have different books.");
}
// Prints: 
// We have different books.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;derive&lt;/code&gt; generates the implementation of a trait for us. We don’t have to do the work ourselves. It provides a generally useful behavior that we don’t have to worry about. For example, in the case of derived &lt;code&gt;PartialEq&lt;/code&gt; on structs, two instances are equal if all the fields are equal, and not equal if any fields aren’t equal.&lt;/p&gt;

&lt;p&gt;We can derive multiple traits at the same time – &lt;code&gt;derive&lt;/code&gt; accepts a list of all the required traits inside the parentheses. Let’s try to derive &lt;code&gt;Display&lt;/code&gt; so we can print our books:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(PartialEq, Display)]
struct Book {
    title: String,
    author: String
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, it doesn’t compile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: cannot find derive macro `Display` in this scope

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It says that it can’t find the way to derive it in this scope. But the compiler won’t be able to find it in any scope! Because &lt;code&gt;Display&lt;/code&gt; can’t be derived. The &lt;code&gt;Display&lt;/code&gt; trait is used for user-facing output, and Rust cannot decide for you how to pretty print your type. Should it print the name of the struct? Should it print all the fields? You have to answer these and other questions yourself.&lt;/p&gt;

&lt;p&gt;Deriving is limited to a certain number of traits. In case you want to implement a trait that can’t be derived or you want to implement a specific behavior for a derivable trait, you can write the functionality yourself.&lt;/p&gt;




&lt;p&gt;💡 &lt;strong&gt;Which standard library traits can be derived?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Rust book’s &lt;a href="https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#appendix-c-derivable-traits"&gt;Appendix C: Derivable Traits&lt;/a&gt; provides a reference of all the derivable traits in the standard library.&lt;/p&gt;

&lt;p&gt;💡 &lt;strong&gt;Can the non-standard-library traits be derived?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes. Developers can implement &lt;code&gt;derive&lt;/code&gt; for their own traits through &lt;a href="https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros"&gt;procedural macros&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;💡 &lt;strong&gt;When should I implement and when should I derive traits?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When deriving is available, it provides a general implementation of the trait, which is what you want most of the time. If it’s not the case, you can manually define the desired behavior.&lt;/p&gt;




&lt;h2&gt;
  
  
  How to define a trait?
&lt;/h2&gt;

&lt;p&gt;Until now, we have only been talking about other people’s traits. But we can also define our own traits.&lt;/p&gt;

&lt;p&gt;Imagine that we want to estimate reading time. It shouldn’t matter what type of content we are reading (an article, a novel, or even a poem). We could use the following trait:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1]
trait Estimatable {
// [2] [3]
    fn estimate(&amp;amp;self) -&amp;gt; f64;
}

// [1]: The trait name (in this case, Estimatable).
// [2]: Trait methods (in this case, only one).
// [3]: The **&amp;amp;self** parameter, followed by other parameters (in this case, none)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; We are using a simple type for minutes for the sake of simplicity. Try not to do this at home! And try not to do this in production!&lt;/p&gt;

&lt;p&gt;Any type implementing the &lt;code&gt;Estimatable&lt;/code&gt; trait should define an &lt;code&gt;estimate&lt;/code&gt; method that calculates how long it might take to read something in minutes.&lt;/p&gt;

&lt;p&gt;Let’s try doing that.&lt;/p&gt;

&lt;h3&gt;
  
  
  Implementing a trait for an enum
&lt;/h3&gt;

&lt;p&gt;In the previous section, we implemented a trait for a struct. Let’s try working with an enum this time. Imagine that we have a personal blog with different kinds of content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Content {
    Infographic,
    PersonalEssay { text: String },
    TechArticle { text: String, topic: String },
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can define the &lt;code&gt;Estimatable&lt;/code&gt; trait for it. It’s not that different from implementing a trait for a struct, but note that we have to define behavior for all the enum variants:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl Estimatable for Content {
    fn estimate(&amp;amp;self) -&amp;gt; f64 {
        match self {
            Content::Infographic =&amp;gt; 1.0,

            Content::PersonalEssay { text } =&amp;gt; 
                word_count(text) / AVG_WORDS_PER_MINUTE,

            // You have to pay attention, especially when learning Rust
            Content::TechArticle { text, topic } =&amp;gt; {
                if topic == "Rust" {
                    word_count(text) / (0.5 * AVG_WORDS_PER_MINUTE)
                } else {
                    word_count(text) / (0.7 * AVG_WORDS_PER_MINUTE)
                }
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; For this example, imagine that &lt;code&gt;word_count&lt;/code&gt; is a function that returns the number of words in a string and &lt;code&gt;AVG_WORDS_PER_MINUTE&lt;/code&gt; is a constant for &lt;code&gt;250.0&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Default implementations
&lt;/h3&gt;

&lt;p&gt;Let’s revisit the &lt;code&gt;PartialEq&lt;/code&gt; trait. We saw a simplified version before, here is the actual definition:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub trait PartialEq&amp;lt;Rhs = Self&amp;gt;
where
    Rhs: ?Sized,
{
    const fn eq(&amp;amp;self, other: &amp;amp;Rhs) -&amp;gt; bool;

    const fn ne(&amp;amp;self, other: &amp;amp;Rhs) -&amp;gt; bool { ... }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we defined the &lt;code&gt;PartialEq&lt;/code&gt; implementation for the &lt;code&gt;Book&lt;/code&gt;, we only had to implement one method, &lt;code&gt;eq&lt;/code&gt;. But the definition clearly has two methods. How can this be?&lt;/p&gt;

&lt;p&gt;Trait definitions can provide default method definitions. &lt;code&gt;ne&lt;/code&gt; is a method with a default implementation.&lt;/p&gt;

&lt;p&gt;As an example, we can extend the &lt;code&gt;Estimatable&lt;/code&gt; trait with a &lt;code&gt;display_estimate&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;trait Estimatable {
    fn estimate(&amp;amp;self) -&amp;gt; f64;

    fn display_estimate(&amp;amp;self) -&amp;gt; String {
        format!("{} minute(s)", self.estimate())
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We don’t have to update the implementation for the &lt;code&gt;Content&lt;/code&gt; type. It works as expected based on &lt;code&gt;estimate&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;println!("Estimated read: {}", Content::Infographic.display_estimate())
// Prints:
// Estimated read: 1 minute(s)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sometimes it’s useful to have default behaviors for the trait methods. When someone implements the trait for their type, they can decide whether to keep or override the default implementations.&lt;/p&gt;

&lt;p&gt;Remember how we talked about iterators? The standard library provides a lot of useful methods for &lt;a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html"&gt;&lt;code&gt;Iterator&lt;/code&gt;&lt;/a&gt; such as &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt;, and &lt;code&gt;fold&lt;/code&gt;. As long as the collection implements either &lt;a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html"&gt;&lt;code&gt;Iterator&lt;/code&gt;&lt;/a&gt; or &lt;a href="https://doc.rust-lang.org/std/iter/trait.IntoIterator.html"&gt;&lt;code&gt;IntoIterator&lt;/code&gt;&lt;/a&gt;, you get these for free.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(0..10) // A range of integers
  .filter(|x| x % 2 != 0) // Keep only odd numbers
  .map(|x| x * x) // Square each number
  .collect::&amp;lt;Vec&amp;lt;usize&amp;gt;&amp;gt;(); // Return a new Vector
// [1, 9, 25, 49, 81]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to use traits in function parameters?
&lt;/h2&gt;

&lt;p&gt;Now that we know how to define our own traits, we can explore how to make use of them.&lt;/p&gt;

&lt;p&gt;A trait is an interface that defines behaviors with a contract that other code can rely on. We can implement functions that depend on this interface.&lt;/p&gt;

&lt;p&gt;In other words, we can implement functions that accept any type implementing our trait. The functions don’t need to know anything else about these types.&lt;/p&gt;

&lt;p&gt;Let’s see how we could implement a function similar to &lt;code&gt;println!&lt;/code&gt; that can print any &lt;code&gt;Estimatable&lt;/code&gt; type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1] [2] [3]  
fn summarize&amp;lt;T: Estimatable&amp;gt;(obj: T) {
    println!("Estimated read: {}", obj.display_estimate());
}

// [1]: The function takes any type T
// [2]: that is Estimatable.
// [3]: `obj` has a type T.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;&amp;lt;T: Estimatable&amp;gt;&lt;/code&gt; declares a generic type parameter with a &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html#trait-bound-syntax"&gt;trait bound&lt;/a&gt;. We can use trait bounds to restrict generics. In this case, it says that we accept any type &lt;code&gt;T&lt;/code&gt; that implements the &lt;code&gt;Estimatable&lt;/code&gt; trait. (If you would like to learn more about generic type parameters, see the &lt;a href="https://doc.rust-lang.org/book/ch10-01-syntax.html#generic-data-types"&gt;Generic Data Types&lt;/a&gt; chapter of The Rust Book.)&lt;/p&gt;

&lt;p&gt;In simple cases like this, we can use a more concise &lt;code&gt;impl Trait&lt;/code&gt; syntax, which is syntactic sugar for trait bounds. We can rewrite it as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1] [2] [3]
fn summarize(obj: impl Estimatable) {
    println!("Estimated read: {}", obj.display_estimate());
}

// [1]: The `obj` parameter should be a type
// [2]: that **impl** ements 
// [3]: the `Estimatable` trait.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The syntax &lt;code&gt;impl Trait&lt;/code&gt; is convenient in simple cases, while the trait bound syntax can express more complex use cases.&lt;/p&gt;

&lt;p&gt;Either way, we can now call &lt;code&gt;summarize&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;summarize(Content::Infographic)
// Prints:
// Estimated read: 1 minute(s)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we try calling the &lt;code&gt;summarize&lt;/code&gt; function with a type that doesn’t implement the &lt;code&gt;Estimatable&lt;/code&gt; trait, the code won’t compile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;summarize(my_book)
// error: the trait bound `Book: Estimatable` is not satisfied

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With traits, we can build functions that accept any type as long as it implements a certain behavior.&lt;/p&gt;




&lt;p&gt;💡 &lt;strong&gt;We can also use traits as return types from functions.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For example, you can return an iterator from a function. Using traits in return types is less common than in parameters. If you are interested, make sure to explore &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits"&gt;it in The Rust Book&lt;/a&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  How to extend traits?
&lt;/h2&gt;

&lt;p&gt;Rust doesn’t have a concept of inheritance. However, you can define supertraits to specify that a trait is an extension of another trait. For example, we can add another trait that adds a paywall to long reads on the website. For this, we need the ability to estimate from &lt;code&gt;Estimatable&lt;/code&gt;, so we’ll extend it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1] [2][3]
trait PayWallable : Estimatable {
    fn use_pay_wall(&amp;amp;self) -&amp;gt; bool;
}

// To define 
// [1]: a subtrait,
// [2]: that extends 
// [3]: the supertrait.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to implement a subtrait (&lt;code&gt;PayWallable&lt;/code&gt;), you must implement all the required methods of the trait itself (&lt;code&gt;PayWallable&lt;/code&gt;) as well as all the required methods of the supertrait (&lt;code&gt;Estimatable&lt;/code&gt;). When you implement a method on a subtrait, you can use the functionality of the supertrait:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl PayWallable for Book {
    fn use_pay_wall(&amp;amp;self) -&amp;gt; bool {
        self.estimate() &amp;gt; 10.0
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But if you don’t implement the supertrait, you will get a compiler error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[]: the trait bound `Book: Estimatable` is not satisfied
    |
    | impl PayWallable for Book {
    | ^^^^^^^^^^^ the trait `Estimatable` is not implemented for `Book`
    |

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can fix the error by implementing the supertrait as well:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl Estimatable for Book {
    fn estimate(&amp;amp;self) -&amp;gt; f64 {
        let book_content = get_book_content_todo();
        word_count(&amp;amp;book_content) / AVG_WORDS_PER_MINUTE
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Traits have many uses
&lt;/h2&gt;

&lt;p&gt;In this blog post, we’ve covered one major use case for traits. Traits can be used as &lt;strong&gt;interfaces&lt;/strong&gt;. Traits can serve as a contract that defines an interaction between components that use the interface. All types implementing a given trait must support the functionality defined by this trait, but it can be implemented differently for each type.&lt;/p&gt;

&lt;p&gt;For example, a &lt;code&gt;sort&lt;/code&gt; algorithm can be applied to a collection of items of any type, as long as they support comparison (implement the &lt;code&gt;Ord&lt;/code&gt; trait).&lt;/p&gt;

&lt;p&gt;But traits are more flexible than that. Look at what different things we can do with traits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Traits can be used to &lt;strong&gt;extend the functionality&lt;/strong&gt; of types. We can use traits to add methods to types that are defined in other libraries. For example, the &lt;code&gt;itertools&lt;/code&gt; library adds a lot of convenience methods to all iterators (outside of their definition).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Traits can be used for &lt;strong&gt;dynamic dispatch&lt;/strong&gt; (deciding which method to call at runtime). When used like this, they are very similar to Java interfaces.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are many other uses: traits as abstract classes, as mix-ins, as &lt;a href="https://doc.rust-lang.org/std/marker/index.html"&gt;behavioral markers&lt;/a&gt;, and for &lt;a href="https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#default-generic-type-parameters-and-operator-overloading"&gt;operator overloading&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Understanding traits and how the standard library traits work is an important part of learning Rust.&lt;/p&gt;

&lt;p&gt;We have learned that traits in Rust are a way to add functionality to structs or enums and define shared behavior between different types. We’ve also explored how to use traits as interfaces and peeked at the various uses of traits.&lt;/p&gt;

&lt;p&gt;If you would like to learn more about traits and the problems they solve, check out the Rust book chapters &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html"&gt;on traits&lt;/a&gt; and &lt;a href="https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#advanced-traits"&gt;advanced traits&lt;/a&gt;, and the Rust Blog &lt;a href="https://blog.rust-lang.org/2015/05/11/traits.html"&gt;post about traits&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;And if you would like to read more beginner-friendly articles about Rust, be sure to follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt; or subscribe to our newsletter via the form below.&lt;/p&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Get Started with Rust: Enums</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 25 Oct 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/get-started-with-rust-enums-2bme</link>
      <guid>https://dev.to/serokell/get-started-with-rust-enums-2bme</guid>
      <description>&lt;h1&gt;
  
  
  Get Started with Rust: Enums
&lt;/h1&gt;

&lt;p&gt;There are two ways to create custom data types in Rust: structs and enums.&lt;/p&gt;

&lt;p&gt;In contrast to &lt;a href="https://serokell.io/blog/structs-in-rust"&gt;structs&lt;/a&gt;, enums construct a type that has multiple variants and not multiple fields.&lt;/p&gt;

&lt;p&gt;While structs are a part of pretty much any programming language, enums are not so mainstream and are mostly seen in statically typed functional languages like Haskell or OCaml. But, as we’ll see, they are quite nice for domain modeling with types.&lt;/p&gt;

&lt;p&gt;This article will show you how to use enums in Rust. By the end of the article, you’ll know the answers to these questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How to define and instantiate an enum?&lt;/li&gt;
&lt;li&gt;When to use enums instead of structs?&lt;/li&gt;
&lt;li&gt;What is pattern matching, and why is it so useful?&lt;/li&gt;
&lt;li&gt;What are the &lt;code&gt;Option&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; enums, and how to use them?&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is an enum in Rust?
&lt;/h2&gt;

&lt;p&gt;Enums (short for enumerations) are a way to create compound data types in Rust. They let us &lt;em&gt;enumerate&lt;/em&gt; multiple possible variants of a type.&lt;/p&gt;

&lt;p&gt;For example, we can use enums to recreate a &lt;code&gt;Bool&lt;/code&gt; data type with two variants: &lt;code&gt;True&lt;/code&gt; and &lt;code&gt;False&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;// [1]  
enum Bool {
// [2]
    True,
    False,
}

// [1]: The name of the data type.
// [2]: The variants of the data type. 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can get a value of this type by constructing it with one of the two variants.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let is_true = Bool::True;
let is_false = Bool::False;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Enum variants are like structs: they can contain fields, which can be unnamed or named. In the example below, the &lt;code&gt;Alive&lt;/code&gt; variant contains an unnamed signed 8-bit integer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum HealthBar {
    Alive(i8),
    Dead,
}

let is_alive = HealthBar::Alive(100);
let is_dead = HealthBar::Dead;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we would like to signify that the field represents life points, we can use a named “life” field instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum HealthBar {
    Alive{life: i8},
    Dead,
}

let is_alive = HealthBar::Alive{life: 100};
let is_dead = HealthBar::Dead;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust enums might be familiar to you from other languages in the guise of &lt;a href="https://serokell.io/blog/algebraic-data-types-in-haskell#sum-types"&gt;sum types&lt;/a&gt; (Haskell and other FP languages) or &lt;a href="https://blog.logrocket.com/understanding-discriminated-union-intersection-types-typescript/"&gt;discriminated unions&lt;/a&gt;. Together with structs, they create a simple yet highly usable mechanism for encoding a lot of information in your types.&lt;/p&gt;

&lt;h3&gt;
  
  
  Enums vs. structs
&lt;/h3&gt;

&lt;p&gt;A struct has multiple fields. In contrast, an enum has multiple variants.&lt;/p&gt;

&lt;p&gt;But, while the concrete value of a struct type has multiple fields, a concrete value of an enum type is exactly one variant.&lt;/p&gt;

&lt;p&gt;Enums enable you to build clearer types and decrease the number of illegal states that your data can take.&lt;/p&gt;

&lt;p&gt;Let’s look at an example. We want to model a character in a game.&lt;/p&gt;

&lt;p&gt;It can have three states:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alive. In this case, it has life points.&lt;/li&gt;
&lt;li&gt;Knocked out. In this case, it has life points and a counter of turns it needs to wait to regain consciousness.&lt;/li&gt;
&lt;li&gt;Dead. In this case, it doesn’t need any additional fields.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Modeling it with only a struct is quite awkward. But we can try the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Player {
    state: String,
    life: i8,
    turns_to_wait: i8,
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we store the name of the state in a string. If the character is “dead”, their life should be 0. And if they are “knocked out”, they should have some turns to wait until they can act.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let dead_player = Player {
    state: "dead".to_string(),
    life: 0,
    turns_to_wait: 0,
};

let knocked_out_player = Player {
    state: "knocked out".to_string(),
    life: 50,
    turns_to_wait: 3,
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works, but it’s very wonky and obscures the states in type. You need to read the code or docs to know the available states, which diminishes the value of types as documentation. You can also use any kind of string in your code, such as “daed” or “knacked out”, without a compiler error.&lt;/p&gt;

&lt;p&gt;Using an enum, we can list all the possible states in a readable manner.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Player {
    Alive{life: i8},
    KnockedOut{life: i8, turns_to_wait: i8},
    Dead,
}

let dead_player = Player::Dead;
let knocked_out_player = Player::KnockedOut { 
    life: 50, 
    turns_to_wait: 3, 
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pattern Matching
&lt;/h2&gt;

&lt;p&gt;Enum types can have one of multiple variants. So if a function takes an enum, we need a way to adapt the function’s behavior depending on the variant of data it will encounter.&lt;/p&gt;

&lt;p&gt;This is done with pattern matching. If variants &lt;em&gt;construct&lt;/em&gt; values of a type, pattern matching &lt;em&gt;deconstructs&lt;/em&gt; them.&lt;/p&gt;

&lt;p&gt;Recall our &lt;code&gt;Bool&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;enum Bool {
    True,
    False,
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Suppose we want to create a function called &lt;code&gt;neg&lt;/code&gt; that returns the opposite of the boolean that we provide.&lt;/p&gt;

&lt;p&gt;This is how we can do it in Rust using pattern matching.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn neg(value: Bool) -&amp;gt; Bool {
// [1]
    match value {
// [2] [3]
        Bool::True =&amp;gt; Bool::False,
        Bool::False =&amp;gt; Bool::True,
    }
}

// [1]: The value we’re pattern matching on.
// [2]: Pattern we want to match. 
// [3]: Result.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result of a match statement can be either an expression or a statement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn print_value(value: Bool) {
    match value {
        Bool::True =&amp;gt; println!("Clearly true!"),
        Bool::False =&amp;gt; println!("Unfortunately false!"),
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want the result to be more than a single statement or expression, you can use curly braces.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn print_and_return_value(value: Bool) -&amp;gt; Bool {
    match value {
        Bool::True =&amp;gt; {
            println!("Clearly true!");
            Bool::True
        }
        Bool::False =&amp;gt; {
            println!("Unfortunately false!");
            Bool::False
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While this basic case highly resembles a case/switch statement, pattern matching can do much more. We can use pattern matching to assign values &lt;em&gt;while&lt;/em&gt; choosing the code path to execute. This enables us to easily work with nested values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn take_five(player: Player) -&amp;gt; Player {
    match player {
        Player::Alive { life: life } =&amp;gt; Player::Alive { life: life - 5 },
        Player::KnockedOut {
            life: life,
            turns_to_wait: turns_to_wait,
        } =&amp;gt; Player::KnockedOut {
            life: life - 5,
            turns_to_wait: turns_to_wait,
        },
        Player::Dead =&amp;gt; Player::Dead,
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To make the code example above even simpler, we can use the &lt;a href="https://serokell.io/blog/structs-in-rust#field-init-shorthand"&gt;field init shorthand&lt;/a&gt;. It lets us substitute &lt;code&gt;life:life&lt;/code&gt; with &lt;code&gt;life&lt;/code&gt; in pattern matching and construction of structs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn take_five(player: Player) -&amp;gt; Player {
    match player {
        Player::Alive { life } =&amp;gt; Player::Alive { life: (life - 5) },
        Player::KnockedOut {
            life,
            turns_to_wait,
        } =&amp;gt; Player::KnockedOut {
            life: (life - 5),
            turns_to_wait,
        },
        Player::Dead =&amp;gt; Player::Dead,
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above has one problem: it doesn’t take into account the fact that a player will die if their health reduces to 0. We can fix that with the help of &lt;a href="https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#extra-conditionals-with-match-guards"&gt;match guards&lt;/a&gt;. and &lt;a href="https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#ignoring-an-entire-value-with-_"&gt;wildcards&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Match guards&lt;/strong&gt; enable you to add &lt;code&gt;if&lt;/code&gt; conditions to the pattern. So we can make the pattern match if the life of &lt;code&gt;Player::Alive&lt;/code&gt; is larger than 5, for example.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If you put a &lt;strong&gt;wildcard&lt;/strong&gt; (marked by underscore) in a pattern, it will match anything. It can be used at the end of a match statement to handle all the remaining cases.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn take_five_advanced(player: Player) -&amp;gt; Player {
    match player {
        Player::Alive { life } if life &amp;gt; 5 =&amp;gt; Player::Alive { life: (life - 5) },
        Player::KnockedOut {
            life,
            turns_to_wait,
        } if life &amp;gt; 5 =&amp;gt; Player::KnockedOut {
            life: (life - 5),
            turns_to_wait,
        },
        _ =&amp;gt; Player::Dead,
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The match statement must be exhaustive – it needs to cover all the possible values. If you fail to cover some of the options, the program won’t compile.&lt;/p&gt;

&lt;p&gt;For example, if we didn’t use the underscore at the end of the statement, we would have two states that are not covered: &lt;code&gt;Alive&lt;/code&gt; and &lt;code&gt;KnockedOut&lt;/code&gt; with less than 5 life points. The compiler can detect this and reject the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//error[E0004]: non-exhaustive patterns: `Alive { .. }` and `KnockedOut { .. }` not covered

fn take_five_advanced(player: Player) -&amp;gt; Player {
    match player {
        Player::Alive { life } if life &amp;gt; 5 =&amp;gt; Player::Alive { life: (life - 5) },
        Player::KnockedOut {
            life,
            turns_to_wait,
        } if life &amp;gt; 5 =&amp;gt; Player::KnockedOut {
            life: (life - 5),
            turns_to_wait,
        },
        Player::Dead =&amp;gt; Player::Dead,
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Enum methods and traits
&lt;/h2&gt;

&lt;p&gt;Like structs, enums allow for the creation of associated methods and the implementation of traits. They are a powerful tool for clearing up your code and reducing boilerplate.&lt;/p&gt;

&lt;h3&gt;
  
  
  Defining methods for enums
&lt;/h3&gt;

&lt;p&gt;Take a look at the negation function that we implemented earlier.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn neg(value: Bool) -&amp;gt; Bool {
  match value {
    Bool::True =&amp;gt; Bool::False,
    Bool::False =&amp;gt; Bool::True,
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It would be better to have it be a method so that we can access it via dot-notation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let is_true = Bool::True;
let not_true = is_true.neg();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To do that, we need to create an implementation block for Bool. In it, we use the &lt;code&gt;self&lt;/code&gt; keyword to refer to the &lt;code&gt;Bool&lt;/code&gt; value at hand. &lt;code&gt;Self&lt;/code&gt; stands for the type we’re writing the implementation for.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl Bool {
  fn neg(self) -&amp;gt; Self {
    match self {
      Self::True =&amp;gt; Self::False,
      Self::False =&amp;gt; Self::True,
    }
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Defining traits for enums
&lt;/h3&gt;

&lt;p&gt;Like structs, enums can also have &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html"&gt;traits&lt;/a&gt; – Rust’s version of interfaces that enable common functionality among types.&lt;/p&gt;

&lt;p&gt;You can derive common traits such as &lt;a href="https://doc.rust-lang.org/std/fmt/trait.Debug.html"&gt;&lt;code&gt;Debug&lt;/code&gt;&lt;/a&gt;, &lt;a href="https://doc.rust-lang.org/std/clone/trait.Clone.html"&gt;&lt;code&gt;Clone&lt;/code&gt;&lt;/a&gt;, and &lt;a href="https://doc.rust-lang.org/std/cmp/trait.Eq.html"&gt;&lt;code&gt;Eq&lt;/code&gt;&lt;/a&gt; using the &lt;a href="https://doc.rust-lang.org/reference/attributes/derive.html"&gt;&lt;code&gt;derive&lt;/code&gt;&lt;/a&gt; attribute.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(Debug, Eq, PartialEq)]
enum Bool {
  True,
  False,
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example, after deriving &lt;code&gt;Debug&lt;/code&gt; and &lt;code&gt;PartialEq&lt;/code&gt;, we can now print and compare values of &lt;code&gt;Bool&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;let is_true = Bool::True;
let is_false = Bool::False;
println!("{:?}", is_true); // Prints “True”. 
let are_same = is_true == is_false; // false 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s also possible to create your own custom traits and implementations. For more info on this, you can read the &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html"&gt;trait section&lt;/a&gt; of the Rust book.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;Option&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; enums
&lt;/h2&gt;

&lt;p&gt;Two enums you will frequently encounter in Rust are &lt;a href="https://doc.rust-lang.org/std/option/enum.Option.html"&gt;&lt;code&gt;Option&lt;/code&gt;&lt;/a&gt;, Rust’s safe alternative to &lt;code&gt;null&lt;/code&gt;, and &lt;a href="https://doc.rust-lang.org/std/result/"&gt;&lt;code&gt;Result&lt;/code&gt;&lt;/a&gt;, Rust’s safe alternative to exceptions.&lt;/p&gt;

&lt;p&gt;Where can they be used? Well, sometimes a function is not able to return a result for a given input. As a simple example, you cannot divide a number by 0.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let impossible = 4 / 0;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In fact, Rust doesn’t let you compile a line of code that divides by zero. But you can still do it in multiple other ways.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
  println!("Choose what to divide 4 with!");
  let mut input = String::new();
  std::io::stdin().read_line(&amp;amp;mut input).unwrap();
  let divisor: i32 = input.trim().parse().unwrap();

  let result = 4 / divisor;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But what if we don’t want the program to crash whenever we encounter a division by zero? We can instead make the function return the &lt;code&gt;Option&lt;/code&gt; type and handle the problem further down the code.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Option&lt;/code&gt; has two variants: &lt;code&gt;None&lt;/code&gt; or &lt;code&gt;Some&lt;/code&gt;. The first represents a lack of output – something you would commonly use &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;nil&lt;/code&gt; for. &lt;code&gt;Some&lt;/code&gt; can wrap any type and signifies that the function has successfully returned a value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub enum Option&amp;lt;T&amp;gt; {
    None,
    Some(T),
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example, we can wrap division in &lt;code&gt;Option&lt;/code&gt; so it doesn’t panic when we divide by 0.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn safe_division(a: i32, b: i32) -&amp;gt; (Option&amp;lt;i32&amp;gt;) {
    match b {
        0 =&amp;gt; None,
        _ =&amp;gt; Some(a / b),
    }
}

let possible = safe_division(4, 0); // None

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Result&lt;/code&gt; is similar, but it returns the error encountered instead of returning &lt;code&gt;None&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;enum Result&amp;lt;T, E&amp;gt; {
   Ok(T),
   Err(E),
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s how &lt;code&gt;safe_division&lt;/code&gt; looks with &lt;code&gt;Result&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;#[derive (Debug, Clone)]
struct DivideByZero; // custom error type

fn safe_division_result(a: i32, b: i32) -&amp;gt; (Result&amp;lt;i32, DivideByZero&amp;gt;) {
    match b {
        0 =&amp;gt; Err(DivideByZero),
        _ =&amp;gt; Ok(a / b),
    }
}

let also_possible = safe_division_result(4, 0); // Err(DivideByZero)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we created a custom error type for the error. It’s possible to use strings to denote errors, but it’s not recommended.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;Option&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; methods
&lt;/h3&gt;

&lt;p&gt;Both of these enums are useful, but they tend to complicate the code.&lt;/p&gt;

&lt;p&gt;Here are some commonly used methods that will make working with them easier. They work on both &lt;code&gt;Option&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; types.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;code&gt;unwrap&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;The straightforward way to get the value inside an &lt;code&gt;Option&lt;/code&gt; or a &lt;code&gt;Result&lt;/code&gt; is to call &lt;code&gt;unwrap&lt;/code&gt; on it.&lt;/p&gt;

&lt;p&gt;This method has a big downside, though. Calling it on a &lt;code&gt;None&lt;/code&gt; or &lt;code&gt;Error&lt;/code&gt; will panic the program, defeating the purpose of error handling.&lt;/p&gt;

&lt;p&gt;let some = safe_division(6, 3); // Some(2) let none = safe_division(4, 0); // None&lt;/p&gt;

&lt;p&gt;let two = some.unwrap(); // 2 let oops = none.unwrap(); // thread ‘main’ panicked at ‘called &lt;code&gt;Option::unwrap()&lt;/code&gt; on a &lt;code&gt;None&lt;/code&gt; value’&lt;/p&gt;

&lt;p&gt;Therefore, its use is generally discouraged. It can come in handy when you’re writing prototypes, using Rust for simple scripts, or trying out libraries.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;code&gt;unwrap_or_else&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;A safe way to unwrap values is to use the &lt;code&gt;unwrap_or_else&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;It takes a closure (anonymous function) as an argument. If it runs into &lt;code&gt;None&lt;/code&gt; or &lt;code&gt;Err&lt;/code&gt;, it uses this closure to compute a value to use instead of panicking.&lt;/p&gt;

&lt;p&gt;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;let two = Some(2).unwrap_or_else(|| {0}); // 2
let safe = None.unwrap_or_else(|| {0}); // 0

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are two more unwrap variants that you can use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;unwrap_or&lt;/code&gt;, which lets you provide a value directly. The difference between it and &lt;code&gt;unwrap_or_else&lt;/code&gt; is that it calculates the default value anytime you run the function, while &lt;code&gt;unwrap_or_else&lt;/code&gt; calculates it only when necessary.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;unwrap_or_default&lt;/code&gt;, which provides a default value instead of panicking if the type has a &lt;code&gt;Default&lt;/code&gt; trait implemented.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;code&gt;?&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;The &lt;a href="https://doc.rust-lang.org/rust-by-example/std/result/question_mark.html"&gt;question mark (try)&lt;/a&gt; operator is a way to get values out of &lt;code&gt;Option&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; without handling the &lt;code&gt;None&lt;/code&gt; case.&lt;/p&gt;

&lt;p&gt;You can write it at the end of any function call that returns &lt;code&gt;Option&lt;/code&gt; or &lt;code&gt;Result&lt;/code&gt; that &lt;em&gt;is inside&lt;/em&gt; a function block that returns &lt;code&gt;Option&lt;/code&gt; or &lt;code&gt;Result&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If it encounters a success state, it will extract the value and proceed with the function. If it encounters a fail state (&lt;code&gt;None&lt;/code&gt; or &lt;code&gt;Err&lt;/code&gt; of some sort), it will short-circuit the function and return the result.&lt;/p&gt;

&lt;p&gt;For &lt;code&gt;Option&lt;/code&gt;, it is approximately equivalent to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;match expr {
    Some(x) =&amp;gt; x,
    None =&amp;gt; return None,
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s look at an example: a function that performs safe division twice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn safe_division_twice(a: i32, b: i32, c: i32) -&amp;gt; Option&amp;lt;i32&amp;gt; {
    let result = safe_division(a, b)?;
    safe_division(result, c)
}

let one = safe_division_twice(4, 2, 2); // Some(1)
let oops = safe_division_twice(4, 0, 2); // None

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It can be very useful when chaining multiple functions that use one of these enums. The alternative of &lt;code&gt;safe_division_twice&lt;/code&gt; with &lt;code&gt;match&lt;/code&gt; is quite wordy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn safe_division_twice(a: i32, b: i32, c: i32) -&amp;gt; Option&amp;lt;i32&amp;gt; {
    match safe_division(a, b) {
        Some(x) =&amp;gt; safe_division(x, c),
        None =&amp;gt; None,
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it would become even worse when we need to chain more than two of these functions: each operation requires its own nested match statement.&lt;/p&gt;

&lt;h1&gt;
  
  
  How a &lt;code&gt;safe_division_thrice&lt;/code&gt; function looks with &lt;code&gt;match&lt;/code&gt; vs. &lt;code&gt;?&lt;/code&gt;
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;With pattern matching&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn safe_division_thrice(a: i32, b: i32, c: i32, d: i32) -&amp;gt; Option&amp;lt;i32&amp;gt; {
    match safe_division(a, b) {
        Some(x) =&amp;gt; match safe_division(x, c) {
            Some(y) =&amp;gt; safe_division(y, d),
            None =&amp;gt; None,
        },
        None =&amp;gt; None,
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;With the question mark operator&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn safe_division_thrice(a: i32, b: i32, c: i32, d: i32) -&amp;gt; Option&amp;lt;i32&amp;gt; {
    let first = safe_division(a, b)?;
    let second = safe_division(first, c)?;
    safe_division(second, d)
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  &lt;code&gt;and_then&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;Another way to chain these enums without writing deep pattern matching statements is the &lt;a href="https://doc.rust-lang.org/rust-by-example/error/option_unwrap/and_then.html"&gt;&lt;code&gt;and_then&lt;/code&gt;&lt;/a&gt; combinator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let one = safe_division(4, 2)
    .and_then(|x| safe_division(x, 2));

let oops = safe_division(4, 0)
    .and_then(|x| safe_division(x, 2));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It extracts the wrapped value and then applies the function provided as its argument to it. In case the value is &lt;code&gt;None&lt;/code&gt; or &lt;code&gt;Error&lt;/code&gt;, it will short circuit the function and return that value.&lt;/p&gt;

&lt;p&gt;In our case, it will extract the result of the first function. Then, it will take that result and pass it to the anonymous function we provided, which is the same as safe_division, but with the second argument already provided.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we covered the basics of enums in Rust. We looked at what they are and how they can be useful. We also looked at pattern matching, a powerful tool that can be used with enums. We also briefly touched two common enums – &lt;code&gt;Option&lt;/code&gt; and &lt;code&gt;Result&lt;/code&gt; – and the methods that you can use to handle them.&lt;/p&gt;

&lt;p&gt;If you would like to read more beginner-friendly articles about Rust, be sure to follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt; or subscribe to our newsletter via the form below.&lt;/p&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Get Started with Rust: Structs</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 16 Aug 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/get-started-with-rust-structs-4h33</link>
      <guid>https://dev.to/serokell/get-started-with-rust-structs-4h33</guid>
      <description>&lt;h1&gt;
  
  
  Get Started With Rust: Structs
&lt;/h1&gt;

&lt;p&gt;In almost any programming language, you can create data structures – like classes or records – that pack a group of things together. Rust is no exception to this with structs.&lt;/p&gt;

&lt;p&gt;This article will show you how to use structs in Rust.&lt;/p&gt;

&lt;p&gt;By the end of this article, you’ll know:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;how to define and instantiate a struct;&lt;/li&gt;
&lt;li&gt;how to derive a trait for a struct;&lt;/li&gt;
&lt;li&gt;what are struct methods, and how to use them.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All the code from this post is available &lt;a href="https://gist.github.com/sancho20021/d6faa25ef319db2442cdfbb0aef6b9a0"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a struct in Rust?
&lt;/h2&gt;

&lt;p&gt;In Rust, a struct is a custom data type that holds multiple related values.&lt;/p&gt;

&lt;p&gt;Let’s jump straight into our first example and define &lt;code&gt;Point&lt;/code&gt; – a wrapper for two coordinates.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// [1] [2]
struct Point {
// [3] [4]
    x: i32,
    y: i32,
}

// We
// [1]: tell Rust that we want to define a new struct
// [2]: named "Point"
// [3]: that contains two fields with names "x" and "y",
// [4]: both of type "i32".

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Tuple structs
&lt;/h3&gt;

&lt;p&gt;You can use a tuple struct to group multiple values together without naming them.&lt;/p&gt;

&lt;p&gt;Tuple structs are defined 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;// [1] [2] [3]
struct Point(i32, i32);

// [1]: Struct name.
// [2]: First component / field of type i32.
// [3]: Second component of type i32.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  How to create an instance of a struct?
&lt;/h3&gt;

&lt;p&gt;Here are the structs that we defined previously.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Ordinary struct
struct Point {
    x: i32,
    y: i32,
}

// Tuple struct
struct PointTuple(i32, i32);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now create instances of these structs – objects of type &lt;code&gt;Point&lt;/code&gt; and &lt;code&gt;PointTuple&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;// [1]
let p_named = Point {
// [2] [3]
    x: 13,
    y: 37,
};

// [1]: Struct name.
// [2]: Field name.
// [3]: Field value.

// [1] [2] [3]
let p_unnamed = PointTuple(13, 37);

// [1]: Struct name.
// [2], [3]: Field values.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, the initialization syntax is pretty straightforward. It’s like defining a JSON object where keys are replaced by field names.&lt;/p&gt;

&lt;p&gt;Two things to keep in mind:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;All fields must have values. There are no default parameters in Rust.&lt;/li&gt;
&lt;li&gt;The order of field-value pairs doesn’t matter. You can write &lt;code&gt;let p_strange_order = Point { y: 37, x: 13 };&lt;/code&gt; if you wish to.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How to access struct fields?
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Getting a value
&lt;/h4&gt;

&lt;p&gt;You can get the value of a field by querying it via dot notation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = p_named.x;
let y = p_named.y;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One may wonder: what’s the syntax to get the value of a specific field of a tuple struct? Fortunately, Rust has chosen the simplest way possible, by indexing tuple components starting from zero.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = p_unnamed.0;
let y = p_unnamed.1;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Setting a value
&lt;/h4&gt;

&lt;p&gt;It’s possible to change the value of a field using dot notation, but the struct variable &lt;strong&gt;must be defined as mutable&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mut p = PointTuple(1, 2);
// ^^^
p.0 = 1000;
assert_eq!(p.0, 1000);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unlike some other languages, Rust doesn’t allow to mark a specific field of a struct as mutable or immutable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Struct {
    mutable: mut i32,
// ^^^
// Expected type, found keyword `mut`.
    immutable: bool,
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have an immutable binding to a struct, you cannot change any of its fields. If you have a mutable binding, you can set whichever field you want.&lt;/p&gt;

&lt;h3&gt;
  
  
  Reducing boilerplate
&lt;/h3&gt;

&lt;p&gt;Two features reduce boilerplate code while initializing struct fields:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;struct update syntax&lt;/li&gt;
&lt;li&gt;field init shorthand&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To illustrate them, we first need to define a new struct and create an instance of it using the usual syntax.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Bicycle {
    brand: String,
    kind: String,
    size: u16,
    suspension: bool,
}

let b1 = Bicycle {
    brand: String::from("Brand A"),
    kind: String::from("Mtb"),
    size: 56,
    suspension: true,
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Struct update syntax
&lt;/h4&gt;

&lt;p&gt;It often happens that you want to copy an instance of a struct and modify some (but not all) of its values. Imagine that a different bicycle brand manufactures a model with identical parameters, and we need to create an instance of that model.&lt;/p&gt;

&lt;p&gt;We can move all values manually:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let b2 = Bicycle {
    brand: String::from("Other brand"),
    kind: b1.kind,
    size: b1.size,
    suspension: b1.suspension,
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But this method involves too much code. &lt;strong&gt;Struct update syntax&lt;/strong&gt; can help:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let b2 = Bicycle {
    brand: String::from("Other brand"),
    ..b1
// ^^ struct update syntax
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;..b1&lt;/code&gt; tells Rust that we want to move the remaining &lt;code&gt;b2&lt;/code&gt;’s fields from &lt;code&gt;b1&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Field init shorthand
&lt;/h4&gt;

&lt;p&gt;You can omit the field name in &lt;code&gt;field: value&lt;/code&gt; initialization syntax if the value is a variable (or function argument) with a name that matches the field.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn new_bicycle(brand: String, kind: String) -&amp;gt; Bicycle {
    Bicycle {
        brand,
// ^^^ instead of "brand: brand"
        kind,
// ^^^ instead of "kind: kind"
        size: 54,
        suspension: false,
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Traits
&lt;/h2&gt;

&lt;p&gt;Okay, let’s try to do something with our struct. For example, print it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p = Point { x: 0, y: 1 };
println!("{}", p);
// ^^^
// Compile error

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Suddenly, the compiler says &lt;code&gt;"Point" doesn't implement "std::fmt::Display"&lt;/code&gt; and suggests that we use &lt;code&gt;{:?}&lt;/code&gt; instead of &lt;code&gt;{}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Ok, why not?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p = Point { x: 0, y: 1 };
println!("{:?}", p);
// ^^^
// Compile error

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, that doesn’t help. We still get the error message: &lt;code&gt;"Point" doesn't implement "Debug"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;But we also get a helpful note:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;note: add `#[derive(Debug)]` to `Point` or manually `impl Debug for Point`

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reason for this error is that both &lt;code&gt;Debug&lt;/code&gt; and &lt;code&gt;std::fmt::Display&lt;/code&gt; are &lt;strong&gt;traits&lt;/strong&gt;. And we need to implement them for &lt;code&gt;Point&lt;/code&gt; to print out the struct.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a trait?
&lt;/h3&gt;

&lt;p&gt;A trait is similar to an interface in Java or a typeclass in Haskell. It defines certain functionality that we might expect from a given type.&lt;/p&gt;

&lt;p&gt;Usually, traits declare a list of methods that can be called on the types that implement this trait.&lt;/p&gt;

&lt;p&gt;Here’s a list of commonly-used traits from the standard library:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://doc.rust-lang.org/std/fmt/trait.Debug.html"&gt;&lt;code&gt;Debug&lt;/code&gt;&lt;/a&gt;. Used to format (and print) a value using &lt;code&gt;{:?}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://doc.rust-lang.org/std/clone/trait.Clone.html"&gt;&lt;code&gt;Clone&lt;/code&gt;&lt;/a&gt;. Used to get a duplicate of a value.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://doc.rust-lang.org/std/cmp/trait.Eq.html"&gt;&lt;code&gt;Eq&lt;/code&gt;&lt;/a&gt;. Used to compare values for equality.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In our example, &lt;code&gt;Point&lt;/code&gt; needs an implementation of the &lt;code&gt;Debug&lt;/code&gt; trait because it’s required by the &lt;code&gt;println!()&lt;/code&gt; macro.&lt;/p&gt;

&lt;p&gt;There are two ways to implement a trait.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Derive&lt;/strong&gt; the implementation. The compiler is capable of providing basic implementations for a fixed list of traits via the &lt;code&gt;#[derive]&lt;/code&gt; macro.&lt;/li&gt;
&lt;li&gt;Manually write the implementation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s start with the first option. We need to add &lt;code&gt;#[derive]&lt;/code&gt; before the definition of &lt;code&gt;Point&lt;/code&gt; and list the traits we want to derive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(Debug, PartialEq, Eq)]
struct Point {
    x: i32,
    y: i32,
}

let p = Point { x: 0, y: 1 };
println!("{:?}", p);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the compiler doesn’t complain, so let’s run our program.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; cargo run
Point { x: 0, y: 1 }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We didn’t write anything related to formatting &lt;code&gt;Point&lt;/code&gt; ourselves, but we already have a decent-looking output. Neat!&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;code&gt;Eq&lt;/code&gt; and &lt;code&gt;PartialEq&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;You may have noticed that we also derived the &lt;code&gt;Eq&lt;/code&gt; and &lt;code&gt;PartialEq&lt;/code&gt; traits.&lt;/p&gt;

&lt;p&gt;Because of that, we can compare two &lt;code&gt;Point&lt;/code&gt;s for equality:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let a = Point { x: 25, y: 50 };
let b = Point { x: 100, y: 100 };
let c = Point { x: 25, y: 50 };

assert!(a == c);
assert!(a != b);
assert!(b != c);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Manually implementing traits
&lt;/h3&gt;

&lt;p&gt;Trait deriving has its disadvantages.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Only a &lt;a href="https://doc.rust-lang.org/book/appendix-03-derivable-traits.html"&gt;small number of traits&lt;/a&gt; are derivable. Though, &lt;a href="https://doc.rust-lang.org/stable/book/ch19-06-macros.html"&gt;procedural macros&lt;/a&gt; allow for creation of custom &lt;code&gt;derive&lt;/code&gt; attributes.&lt;/li&gt;
&lt;li&gt;Sometimes the derived implementation doesn’t match your needs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s why it’s possible to implement a trait by yourself.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementing &lt;code&gt;Display&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;When we tried to print a &lt;code&gt;Point&lt;/code&gt; instance using &lt;code&gt;"{}"&lt;/code&gt;, the compiler said that &lt;code&gt;Point&lt;/code&gt; doesn’t implement &lt;code&gt;std::fmt::Display&lt;/code&gt;. This trait is similar to &lt;code&gt;std::fmt::Debug&lt;/code&gt; but it has a few differences:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It must be implemented manually.&lt;/li&gt;
&lt;li&gt;It should format values in a prettier way, without containing any unnecessary information.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can think of the &lt;code&gt;Debug&lt;/code&gt; and the &lt;code&gt;Display&lt;/code&gt; as the formatters for programmers and users, respectively.&lt;/p&gt;

&lt;p&gt;Let’s add a manual implementation of &lt;code&gt;Display&lt;/code&gt;. In the brackets, we have to define every function that is declared in the &lt;a href="https://doc.rust-lang.org/std/fmt/trait.Display.html"&gt;trait&lt;/a&gt;. In our case, there is only one — &lt;code&gt;fmt&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;impl std::fmt::Display for Point {
    fn fmt(&amp;amp;self, f: &amp;amp;mut std::fmt::Formatter&amp;lt;'_&amp;gt;) -&amp;gt; std::fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can print our &lt;code&gt;Point&lt;/code&gt; struct both for developers and users.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p = Point::new(0, 1);

assert_eq!(format!("{:?}", p), "Point { x: 0, y: 0 }");
assert_eq!(format!("{}", p), "(0, 0)");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Struct methods
&lt;/h2&gt;

&lt;p&gt;Just like in Java or C++, you can define &lt;strong&gt;methods&lt;/strong&gt; that are associated with a particular type. This is done in an &lt;code&gt;impl&lt;/code&gt; block.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl Point {
    // Method that can't modify the struct instance
    fn has_same_x(&amp;amp;self, other: &amp;amp;Self) -&amp;gt; bool {
        self.x == other.x
    }

    // Method that can modify the struct instance
    fn shift_right(&amp;amp;mut self, dx: i32) {
        self.x += dx;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can call these methods via dot notation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Mutable binding
let mut point = Point { x: 25, y: 25 };
assert!(!point.has_same_x(&amp;amp;Point { x: 30, y: 25 }));

// Calling a method that changes the object state
point.shift_right(3);
assert_eq!(point.x, 28);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Methods can mutate the struct instance they are associated with, but this requires &lt;code&gt;&amp;amp;mut self&lt;/code&gt; as the first argument. This way, they can be called only via mutable binding.&lt;/p&gt;

&lt;h3&gt;
  
  
  Self
&lt;/h3&gt;

&lt;p&gt;You may have noticed that methods have &lt;code&gt;self&lt;/code&gt; as their first argument. It represents the instance of the struct the method is being called on, similar to how it’s done in Python. Some syntax sugar is involved here. Let’s desugar it in two steps.&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;th&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;&lt;code&gt;fn has_same_x(&amp;amp;self, other: &amp;amp;Self)&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;fn shift_right(&amp;amp;mut self, dx: i32)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;&lt;code&gt;fn has_same_x(self: &amp;amp;Self, other: &amp;amp;Self)&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;fn shift_right(self: &amp;amp;mut Self, dx: i32)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;&lt;code&gt;fn has_same_x(self: &amp;amp;Point, other: &amp;amp;Point)&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;fn shift_right(self: &amp;amp;mut Point, dx: i32)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Don’t confuse &lt;code&gt;self&lt;/code&gt; with &lt;code&gt;Self&lt;/code&gt;. The latter is an alias for the type of the &lt;code&gt;impl&lt;/code&gt; block. In our case, it’s &lt;code&gt;Point&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Associated functions
&lt;/h3&gt;

&lt;p&gt;You can also use the &lt;code&gt;impl&lt;/code&gt; block to define functions that don’t take an instance of &lt;code&gt;Self&lt;/code&gt;, like static functions in Java. They are commonly used for constructing new instances of the type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl Point {
    // Associated function that is not a method
    fn new(x: i32, y: i32) -&amp;gt; Point {
        Point { x, y }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can call these functions by using a double semicolon (&lt;code&gt;::&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;let point = Point::new(1, 2);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Why use methods instead of regular functions?
&lt;/h3&gt;

&lt;p&gt;Methods are quite useful for making your code better. Let’s look at some examples.&lt;/p&gt;

&lt;h4&gt;
  
  
  Nice-looking dot notation
&lt;/h4&gt;

&lt;p&gt;To call methods of a type, we use dot notation.&lt;/p&gt;

&lt;p&gt;Besides beautiful syntax, dot notation provides an additional property — autoreferencing — which means you can write &lt;code&gt;point.shift_right(3);&lt;/code&gt; instead of &lt;code&gt;(&amp;amp;mut point).shift_right(3);&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Functions don’t have this advantage, you always have to reference:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;shift_right(&amp;amp;mut point, 3);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Code organization
&lt;/h4&gt;

&lt;p&gt;All methods are placed inside one or multiple &lt;code&gt;impl&lt;/code&gt; blocks. This implies two things.&lt;/p&gt;

&lt;p&gt;First, you don’t have to import methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use my_module::MyStruct;

...
let s = MyStruct::new();
s.do_stuff();
s.do_other_stuff();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without methods, it would look 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;use my_module::{MyStruct, do_stuff, do_other_stuff}; // ugly

...
let s = MyStruct::new();
do_stuff(&amp;amp;s);
do_other_stuff(&amp;amp;s);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Second, methods are namespaced: you don’t have name collisions across types.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_rectangle.area()
my_circle.area()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without methods, you would need to write something 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;rectangle_area(my_rectangle)
circle_area(my_circle)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Methods vs. traits
&lt;/h2&gt;

&lt;p&gt;Methods and traits are somewhat similar, so beginners can mix them up.&lt;/p&gt;

&lt;p&gt;The general rule for when to use which is simple for beginners:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If you are implementing a common functionality for which a trait exists (converting to string, comparison, etc.), try to implement that trait.&lt;/li&gt;
&lt;li&gt;If you are doing something specific to your application, probably use methods in regular &lt;code&gt;impl&lt;/code&gt; blocks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A method can be invoked only on the type it is defined for. Traits, on the other hand, overcome this limitation, as they are usually meant to be implemented by multiple different types.&lt;/p&gt;

&lt;p&gt;So traits allow certain functions to be generalized. These functions don’t take just one type, but a set of types that is constrained by a trait.&lt;/p&gt;

&lt;p&gt;We have already seen such examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;println!("{:?}", ...)&lt;/code&gt; doesn’t care what kind of an object we want to print as long as it implements the &lt;code&gt;Debug&lt;/code&gt; trait.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;assert_eq!(...)&lt;/code&gt; allows to compare objects of any type as long as they implement &lt;code&gt;PartialEq&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we covered the basics of structs in Rust. We explored the ways of defining, initializing, and adding implementation blocks to both structs and tuple structs. We also looked at traits and how to derive or implement them.&lt;/p&gt;

&lt;p&gt;Structs are not the only way to create custom types. Rust also has &lt;a href="https://doc.rust-lang.org/book/ch06-00-enums.html"&gt;enums&lt;/a&gt;. While we did not cover them in this blog post, concepts as methods, traits, and deriving can be applied to them in a similar way.&lt;/p&gt;

&lt;p&gt;If you would like to read more beginner-friendly articles about Rust, be sure to follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt; or subscribe to our newsletter via the form below.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Kinds and Higher-Kinded Types in Haskell</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 02 Aug 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/kinds-and-higher-kinded-types-in-haskell-338j</link>
      <guid>https://dev.to/serokell/kinds-and-higher-kinded-types-in-haskell-338j</guid>
      <description>&lt;p&gt;One of the more frequent comments that Haskell developers make about other programming languages is that they lack something called higher-kinded types.&lt;/p&gt;

&lt;p&gt;Which leads to a communication problem. Since those programming languages don’t have a way to express either kinds or HKTs, it is hard for non-Haskell developers to understand what they are missing out on.&lt;/p&gt;

&lt;p&gt;In the end, the words of the Haskell developer are dismissed as mad ravings, and everybody moves on.&lt;/p&gt;

&lt;p&gt;But once you start working with Haskell, it makes it very intuitive for you to understand both kinds and higher-kinded types.&lt;/p&gt;

&lt;p&gt;In this article, I will introduce you to the concept of kinds. Then, we’ll use our newfound knowledge to understand what are higher-kinded types and what makes them useful.&lt;/p&gt;

&lt;h2&gt;
  
  
  What’s the type of a type?
&lt;/h2&gt;

&lt;p&gt;In one sentence, kinds are to types what types are to values.&lt;/p&gt;

&lt;p&gt;We can imagine a universe of values, populated by values like &lt;code&gt;"hello"&lt;/code&gt;, &lt;code&gt;True&lt;/code&gt;, &lt;code&gt;[1, 2, 3]&lt;/code&gt;. And we can imagine a universe of types governing those values, with types such as &lt;code&gt;String&lt;/code&gt;, &lt;code&gt;Bool&lt;/code&gt;, and &lt;code&gt;[Int]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;But in Haskell, we have the third universe governing types, which is populated by kinds.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*
* -&amp;gt; *
* -&amp;gt; * -&amp;gt; *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For now, the most important thing about them is that they show the arity of a type (if we think of that type as a function).&lt;/p&gt;

&lt;p&gt;You can read &lt;code&gt;*&lt;/code&gt; as &lt;code&gt;Type&lt;/code&gt;. In fact, a commonly used GHC extension called &lt;code&gt;NoStarIsType&lt;/code&gt; disables the use of &lt;code&gt;*&lt;/code&gt; in favor of &lt;code&gt;Type&lt;/code&gt;. But since GHC still uses &lt;code&gt;*&lt;/code&gt; by default, I’ll use that in the article.&lt;/p&gt;

&lt;p&gt;To see the kind signature of a type, you can use the &lt;code&gt;:k&lt;/code&gt; command in GHCi.&lt;/p&gt;

&lt;p&gt;Let’s look at some examples.&lt;/p&gt;

&lt;p&gt;All concrete types, such as &lt;code&gt;String&lt;/code&gt;, &lt;code&gt;Bool&lt;/code&gt;, and &lt;code&gt;[Int]&lt;/code&gt; have the kind of &lt;code&gt;*&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;&amp;gt; :k String
String :: *
&amp;gt; :k Bool
Bool :: *
&amp;gt; :k [Int]
[Int] :: *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To have a more complex kind, you need a polymorphic type – a type with type variables in its definition. In other languages, type variables are also called generics.&lt;/p&gt;

&lt;p&gt;For example, look at how &lt;code&gt;Maybe&lt;/code&gt; (Haskell’s optional type) is defined in Haskell.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Maybe a = Nothing | Just a

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Maybe&lt;/code&gt; takes a type variable – &lt;code&gt;a&lt;/code&gt; – and returns a type – &lt;code&gt;Maybe a&lt;/code&gt; – that might contain an item of &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Hence, it has the kind of &lt;code&gt;* -&amp;gt; *&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;&amp;gt; :k Maybe
Maybe :: * -&amp;gt; *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Maybe&lt;/code&gt; by itself is a type-level function, a type constructor. As such, there are no actual values of type &lt;code&gt;Maybe&lt;/code&gt; – there are only values of types like &lt;code&gt;Maybe Int&lt;/code&gt;, &lt;code&gt;Maybe String&lt;/code&gt;, etc. We can say that &lt;code&gt;Maybe&lt;/code&gt; is &lt;em&gt;uninhabited&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Once you provide a type to &lt;code&gt;Maybe&lt;/code&gt;, it will return a concrete type that contains values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; :k Maybe Bool
Maybe Bool :: *
&amp;gt; :k Maybe String
Maybe String :: *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To have a kind of &lt;code&gt;* -&amp;gt; * -&amp;gt; *&lt;/code&gt;, you need to have two type variables.&lt;/p&gt;

&lt;p&gt;A classic example of this is &lt;code&gt;Either&lt;/code&gt; (Haskell’s result type).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Either a b = Left a | Right b

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It takes two types – &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; – and returns a concrete type.&lt;/p&gt;

&lt;p&gt;It can be applied with zero, one, or two arguments. Its kind signature varies accordingly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; :k Either
Either :: * -&amp;gt; * -&amp;gt; *
&amp;gt; :k Either String
Either String :: * -&amp;gt; *
&amp;gt; :k Either String Int
Either String Int :: *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Most programming languages support these kinds of types – the most common examples of these are list and array types.&lt;/p&gt;

&lt;p&gt;But if concrete types are like values and polymorphic types are like functions, can we have something akin to higher-order functions on types?&lt;/p&gt;

&lt;p&gt;In other words, can we have a kind like &lt;code&gt;(* -&amp;gt; *) -&amp;gt; * -&amp;gt; *&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;Turns out, yes. In Haskell, it’s kinda easy.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are higher-kinded types in Haskell?
&lt;/h2&gt;

&lt;p&gt;One of the things that separates Haskell from most programming languages is the existence of higher-kinded types.&lt;/p&gt;

&lt;p&gt;Higher-kinded types are types with kind signatures that have parenthesis somewhere on the left side, like this: &lt;code&gt;(* -&amp;gt; *) -&amp;gt; * -&amp;gt; *&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This means that they are types that take a type like &lt;code&gt;Maybe&lt;/code&gt; as an argument. In other words, they abstract over polymorphic types.&lt;/p&gt;

&lt;p&gt;A common example is a type for any collection.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Collection f a = Collection (f a) deriving (Show)


&amp;gt; :k Collection
Collection :: (* -&amp;gt; *) -&amp;gt; * -&amp;gt; *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This type takes a wrapper &lt;code&gt;f&lt;/code&gt; (such as &lt;code&gt;[]&lt;/code&gt;) and a concrete type &lt;code&gt;a&lt;/code&gt; such as &lt;code&gt;Int&lt;/code&gt; and returns a collection of &lt;code&gt;f a&lt;/code&gt; (such as &lt;code&gt;Collection [] Int&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;a :: Collection [] Int
a = Collection [1,2,3]

b :: Collection [] String
b = Collection ["call", "me", "ishmael"]

c :: Collection Maybe String
c = Collection (Just "whale")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Types like this one cannot be created in most programming languages like Java, TypeScript, or Rust without resorting to dark magic.&lt;/p&gt;

&lt;h1&gt;
  
  
  Example of a (failed) HKT attempt in C#.
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface ISingleton&amp;lt;out T&amp;gt;
{
T&amp;lt;A&amp;gt; One&amp;lt;A&amp;gt;(A x);
}

class ListSingleton : ISingleton&amp;lt;List&amp;gt;
{
public List&amp;lt;A&amp;gt; One&amp;lt;A&amp;gt;(A x) =&amp;gt; new List&amp;lt;A&amp;gt;(new A[]{x});
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following code returns three compilation errors, out of which the first – &lt;code&gt;The type parameter 'T' cannot be used with type arguments&lt;/code&gt; – is the compiler explicitly forbidding HKTs.&lt;/p&gt;

&lt;p&gt;You can also see a TypeScript example of an unimplementable &lt;code&gt;Collection&lt;/code&gt; &lt;a href="https://serokell.io/blog/typescript-for-haskellers#hkts"&gt;in our article about functional TypeScript&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;Of course, we cannot really write a lot of functions for this data type because it is too generic. To make it more useful, we can add some constraints, such as the outer type (&lt;code&gt;f&lt;/code&gt;) being a functor.&lt;/p&gt;

&lt;p&gt;But what is a functor?&lt;/p&gt;

&lt;h3&gt;
  
  
  HKTs and functors
&lt;/h3&gt;

&lt;p&gt;In Haskell, HKTs is the realm of typeclasses like &lt;code&gt;Functor&lt;/code&gt; and &lt;code&gt;Monad&lt;/code&gt;. In this article, we’ll cover only &lt;code&gt;Functor&lt;/code&gt; since it’s simpler. But most things written here apply to &lt;code&gt;Monad&lt;/code&gt; as well.&lt;/p&gt;

&lt;p&gt;Let’s look at what GHCi can tell us about &lt;code&gt;Functor&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;&amp;gt; :info Functor
type Functor :: (* -&amp;gt; *) -&amp;gt; Constraint
class Functor f where
  fmap :: (a -&amp;gt; b) -&amp;gt; f a -&amp;gt; f b
  (&amp;lt;$) :: a -&amp;gt; f b -&amp;gt; f a

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you’re not familiar with Haskell, this might look a little confusing. Let’s try to untangle it.&lt;/p&gt;

&lt;p&gt;Functor in Haskell is a &lt;a href="https://serokell.io/blog/haskell-typeclasses"&gt;typeclass&lt;/a&gt;, which is something that bears resemblance to Rust traits, or if you squint hard, Java interfaces. Typeclasses define a set of common methods that can be shared across types.&lt;/p&gt;

&lt;p&gt;The kind signature of &lt;code&gt;Functor&lt;/code&gt; is &lt;code&gt;(* -&amp;gt; *) -&amp;gt; Constraint&lt;/code&gt;, which means that it takes a type constructor like &lt;code&gt;Maybe&lt;/code&gt; and returns something of a &lt;code&gt;Constraint&lt;/code&gt; kind.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Constraint kind&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While &lt;code&gt;*&lt;/code&gt; is the most common kind that you will find in basic Haskell without extensions, it’s not the only one.&lt;/p&gt;

&lt;p&gt;While data types are of kinds like &lt;code&gt;*&lt;/code&gt; or &lt;code&gt;* -&amp;gt; *&lt;/code&gt;, typeclasses are of a kind like &lt;code&gt;* -&amp;gt; Constraint&lt;/code&gt; or &lt;code&gt;(* -&amp;gt; *) -&amp;gt; Constraint&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Constraint&lt;/code&gt; is the kind of class constraints – it covers anything that can appear on the left side of the arrow when defining a type.&lt;/p&gt;

&lt;p&gt;For example, if we want to define a polymorphic plus function in Haskell, we need to add a constraint of &lt;code&gt;Num&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;-- {1}
plus :: Num a =&amp;gt; a -&amp;gt; a -&amp;gt; a
plus a b = a + b
-- {1}: Num constraint on the type of a in the signature.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It comes from the &lt;code&gt;Num&lt;/code&gt; typeclass, whose kind is &lt;code&gt;* -&amp;gt; Constraint&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In general, kinds with names are something you will run into much more when starting to work with extensions like &lt;code&gt;DataKinds&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;The main method of &lt;code&gt;Functor&lt;/code&gt; is &lt;code&gt;fmap&lt;/code&gt;, which is a &lt;code&gt;map&lt;/code&gt; that works for multiple types of wrappers. Below are some examples of its usage.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;fmap&lt;/code&gt; with &lt;code&gt;[]&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;&amp;gt; fmap (+3) [1, 2, 3]
[4,5,6]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;fmap&lt;/code&gt; with &lt;code&gt;Maybe&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;&amp;gt; fmap (+3) (Just 1)
Just 4

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;fmap&lt;/code&gt; with &lt;code&gt;Either&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;&amp;gt; fmap (+3) (Right 5)
Right 8
&amp;gt; fmap (+3) (Left "fatal Err0r")
Left "fatal Err0r"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want more information about the typeclass, you can read our article on &lt;a href="https://serokell.io/blog/whats-that-typeclass-functor"&gt;functors&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In general, since types with the kind of &lt;code&gt;* -&amp;gt; *&lt;/code&gt; don’t have any values, you can’t really work with them in most programming languages.&lt;/p&gt;

&lt;p&gt;But in Haskell, we can take a type with such a kind and create a &lt;code&gt;Functor&lt;/code&gt; instance for it. For example, our own data type &lt;code&gt;Optional&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;data Optional a = Some a | None deriving (Show)

instance Functor Optional where
  fmap f (Some a) = Some (f a)
  fmap f None = None

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once we have the instance, we can use the &lt;code&gt;Functor&lt;/code&gt; methods for this 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;&amp;gt; fmap (+3) (Some 4)
Some 7

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Functor instance restrictions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Note that you can only define a &lt;code&gt;Functor&lt;/code&gt; instance for a type of a kind &lt;code&gt;* -&amp;gt; *&lt;/code&gt;. So it has to be &lt;code&gt;Optional&lt;/code&gt;, not &lt;code&gt;Optional Int&lt;/code&gt; or &lt;code&gt;Optional String&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Types with the kind of &lt;code&gt;* -&amp;gt; * -&amp;gt; *&lt;/code&gt; like &lt;code&gt;Either&lt;/code&gt;or &lt;code&gt;(,)&lt;/code&gt;(the tuple type) cannot have &lt;code&gt;Functor&lt;/code&gt; instances without being applied up to the correct kind. For example, you can have a functor instance for &lt;code&gt;Either a&lt;/code&gt;, but not &lt;code&gt;Either&lt;/code&gt; or &lt;code&gt;Either a b&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;instance Functor (Either a) where
    fmap _ (Left x) = Left x
    fmap f (Right y) = Right (f y)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And because partial application happens from the left, &lt;code&gt;fmap&lt;/code&gt; maps only the &lt;code&gt;Right&lt;/code&gt; element of &lt;code&gt;Either&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;Now that we are somewhat familiar with &lt;code&gt;Functor&lt;/code&gt;, we can use it as a constraint for the &lt;code&gt;Collection&lt;/code&gt; data type. We’ll define a &lt;code&gt;cfmap&lt;/code&gt; function on collections whose wrappers are functors.&lt;/p&gt;

&lt;p&gt;It takes a function and a &lt;code&gt;Collection&lt;/code&gt; that has a functor wrapper, and returns a &lt;code&gt;Collection&lt;/code&gt; with the same functor wrapper but with the function applied to the value inside of it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cfmap :: Functor f =&amp;gt; (a -&amp;gt; b) -&amp;gt; Collection f a -&amp;gt; Collection f b
cfmap fun (Collection a) = Collection (fmap fun a)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s how this method works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; cfmap (&amp;lt;&amp;gt; "!") (Collection ["call", "me", "ishmael"])
Collection ["call!","me!","ishmael!"]

&amp;gt; cfmap (+3) (Collection [1, 2, 3])
Collection [4,5,6]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Of course, the definition is awfully similar to the &lt;code&gt;fmap&lt;/code&gt; itself. So we could just make &lt;code&gt;Collection&lt;/code&gt; a &lt;code&gt;Functor&lt;/code&gt; instead.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;instance Functor f =&amp;gt; Functor (Collection f) where
  fmap fun (Collection a) = Collection (fmap fun a)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This enables us to use &lt;code&gt;fmap&lt;/code&gt;for collections that have a &lt;code&gt;Functor&lt;/code&gt; wrapper.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; fmap (&amp;lt;&amp;gt; "!") (Collection ["call", "me", "ishmael"])
Collection ["call!","me!","ishmael!"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Quite cool.&lt;/p&gt;

&lt;p&gt;And this concludes our journey into higher-kinded types in Haskell. 🏞️&lt;/p&gt;

&lt;p&gt;To sum up, here’s a table with the differences between concrete types, simple polymorphic types, and higher-kinded types.&lt;/p&gt;

&lt;p&gt;| | Concrete types | Polymorphic types | Higher-kinded types |&lt;br&gt;
| Example kind signature | &lt;code&gt;*&lt;/code&gt; | &lt;code&gt;* -&amp;gt; *&lt;/code&gt; | &lt;code&gt;(* -&amp;gt; *) -&amp;gt; *&lt;/code&gt; |&lt;br&gt;
| Example data type | &lt;code&gt;Int&lt;/code&gt; | &lt;code&gt;Maybe a&lt;/code&gt; | &lt;code&gt;Collection f a&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;(Real-life examples from base include &lt;a href="https://hackage.haskell.org/package/base-4.16.1.0/docs/Data-Monoid.html#g:5"&gt;alternative&lt;/a&gt; and &lt;a href="https://hackage.haskell.org/package/base-4.16.1.0/docs/Data-Monoid.html#g:6"&gt;applicative&lt;/a&gt; wrappers from &lt;a href="https://hackage.haskell.org/package/base-4.16.1.0/docs/Data-Monoid.html"&gt;Data.Monoid&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;|&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of higher-kinded types
&lt;/h2&gt;

&lt;p&gt;So why would a language need to support higher-kinded types?&lt;/p&gt;

&lt;p&gt;If you ask a Haskeller, it is, of course, to be able to easily define something similar to the &lt;code&gt;Functor&lt;/code&gt; and &lt;code&gt;Monad&lt;/code&gt; typeclasses.&lt;/p&gt;

&lt;p&gt;These typeclasses are very beneficial for those that know how to use them. Abstracting over a bunch of similar behaviors can lead to very elegant code.&lt;/p&gt;

&lt;p&gt;And, additionally, if HKTs are available naturally, there’s a smaller chance that someone will create an FP library that’s unreadable for 99% of the language users. 🙃&lt;/p&gt;

&lt;p&gt;At the same time, plenty of programming languages choose to skip HKTs. &lt;a href="https://serokell.io/blog/rust-guide"&gt;Rust&lt;/a&gt;, for example, is somewhat inspired by FP languages like Haskell, but it lacks higher-kinded types at the moment. People love it nonetheless.&lt;/p&gt;

&lt;p&gt;So, it’s a complex tradeoff at the very least. Thankfully, it is one mostly resolved by language designers and not us mere mortals.&lt;/p&gt;

&lt;p&gt;All in all, if you write code in a language that enables you to write HKTs (like Haskell), you should, of course, make use of the power. They are not that complex but help quite a lot.&lt;/p&gt;

&lt;p&gt;But if you want to use them in a language where they are not natural to use (for example, via an FP library like &lt;a href="https://github.com/gcanti/fp-ts"&gt;fp-ts&lt;/a&gt;), be sure that everyone involved is OK with that beforehand.&lt;/p&gt;

&lt;h2&gt;
  
  
  Further reading
&lt;/h2&gt;

&lt;p&gt;This article covered a wide variety of topics in a piecemeal fashion. We looked at kinds, higher-kinded types, and the &lt;code&gt;Functor&lt;/code&gt; typeclass. While I tried to give all the necessary information, each of these topics deserves an article of its own.&lt;/p&gt;

&lt;p&gt;To learn more about kinds in Haskell, I suggest this &lt;a href="https://diogocastro.com/blog/2018/10/17/haskells-kind-system-a-primer/"&gt;awesome article&lt;/a&gt; by Diogo Castro.&lt;/p&gt;

&lt;p&gt;And if you want to read more about Haskell typeclasses like &lt;code&gt;Functor&lt;/code&gt;, we have a series called &lt;a href="https://serokell.io/blog/what's-that-typeclass"&gt;What’s That Typeclass&lt;/a&gt; that covers them.&lt;/p&gt;

&lt;p&gt;To read more articles like these, follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt; or subscribe to the Serokell newsletter via the form below.&lt;/p&gt;

</description>
      <category>haskell</category>
    </item>
    <item>
      <title>What's That Typeclass: Functor</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 26 Jul 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/whats-that-typeclass-functor-533h</link>
      <guid>https://dev.to/serokell/whats-that-typeclass-functor-533h</guid>
      <description>&lt;p&gt;You might already know the &lt;code&gt;map&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;map :: (a -&amp;gt; b) -&amp;gt; [a] -&amp;gt; [b]
map _ [] = []
map f (x:xs) = f x : map f xs


&amp;gt; map (\x -&amp;gt; x + 1) [1, 2, 3]
[2, 3, 4]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It takes a function of type &lt;code&gt;a -&amp;gt; b&lt;/code&gt; and applies it to each element of a list. The elements change, but the data type storing them (&lt;code&gt;[]&lt;/code&gt;) remains the same. In this article, we’ll call such a data type with another type inside it a &lt;em&gt;context&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Transforming values inside fixed contexts is common in programming.&lt;/p&gt;

&lt;p&gt;For example, the optional data type (&lt;a href="https://serokell.io/blog/algebraic-data-types-in-haskell#maybe"&gt;&lt;code&gt;Maybe&lt;/code&gt;&lt;/a&gt;) provides a context of a possibly failed computation. It can also be “mapped” by trying to apply a function to the wrapped value without changing the context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;map' :: (a -&amp;gt; b) -&amp;gt; Maybe a -&amp;gt; Maybe b

map' f (Just x) = Just (f x)
map' f Nothing = Nothing


&amp;gt; map' (\x -&amp;gt; x + 1) (Just 1)
Just 2
&amp;gt; map' (\x -&amp;gt; x + 1) Nothing
Nothing

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This article will introduce you to Functor – a typeclass that unifies these kinds of transformations and provides common functionality for them.&lt;/p&gt;

&lt;p&gt;After reading this article, you will know:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;what Functor is in Haskell;&lt;/li&gt;
&lt;li&gt;how to define and use your own Functor instances;&lt;/li&gt;
&lt;li&gt;why and where Functors are useful.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We’ll also provide a set of exercises to consolidate your knowledge.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to generalize &lt;code&gt;map&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Look at the type signature of &lt;code&gt;map&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;map :: (a -&amp;gt; b) -&amp;gt; [a] -&amp;gt; [b]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It takes a function &lt;code&gt;a -&amp;gt; b&lt;/code&gt;. Then, it uses that function to change the contents of a list.&lt;/p&gt;

&lt;p&gt;Now, look at the type of &lt;code&gt;map'&lt;/code&gt;. It uses the same type of function – &lt;code&gt;a -&amp;gt; b&lt;/code&gt; – to change the contents of &lt;code&gt;Maybe&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;map' :: (a -&amp;gt; b) -&amp;gt; Maybe a -&amp;gt; Maybe b

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The type signatures are kind of similar!&lt;/p&gt;

&lt;p&gt;Could we have a more general function that works for many different contexts? Absolutely. It’s Haskell, after all.&lt;br&gt;
&lt;/p&gt;

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

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s how it works. &lt;code&gt;fmap&lt;/code&gt; takes an &lt;code&gt;a -&amp;gt; b&lt;/code&gt; function and an &lt;code&gt;f a&lt;/code&gt; data type (&lt;code&gt;a&lt;/code&gt; wrapped in any context &lt;code&gt;f&lt;/code&gt;). The function is applied to what’s inside the context, and a value of type &lt;code&gt;b&lt;/code&gt; wrapped in &lt;code&gt;f&lt;/code&gt; is returned. The value can change, but the context remains the same.&lt;/p&gt;

&lt;p&gt;Let’s look at a few examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Apply `reverse :: String -&amp;gt; String`
-- to a list of `String`s
-- to get a list of `String`s.
&amp;gt; fmap reverse ["abc", "def", "ghi"]
["cba","fed","ihg"]
&amp;gt; fmap reverse []
[]

-- Apply `show :: Int -&amp;gt; String`
-- to a list of `Int`s
-- to get a list of `String`s.
&amp;gt; fmap show [1..3]
["1","2","3"]
&amp;gt; fmap show []
[]

-- Apply `(+1) :: Int -&amp;gt; Int` 
-- to `Maybe Int`
-- to get `Maybe Int`.
&amp;gt; fmap (+1) $ Just 1
Just 2
&amp;gt; fmap (+1) Nothing
Nothing

-- Apply `(&amp;gt; 0) :: Int -&amp;gt; Bool` 
-- to `Maybe Int`
-- to get `Maybe Bool`.
&amp;gt; fmap (&amp;gt; 0) $ Just (-1)
Just False
&amp;gt; fmap (&amp;gt; 0) $ Just 1
Just True
&amp;gt; fmap (&amp;gt; 0) Nothing
Nothing

-- Apply `chr :: Int -&amp;gt; Char`
-- to a pair `(a, Int)`
-- to get a pair `(a, Char)`.
-- Note that only the second value is mapped.
&amp;gt; fmap chr (65,65)
(65,'A')
&amp;gt; fmap chr ('a',97)
('a','a')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you may have guessed, &lt;code&gt;map&lt;/code&gt; is just a synonym of &lt;code&gt;fmap&lt;/code&gt; for lists. But it can do much more. With &lt;code&gt;fmap&lt;/code&gt;, we can do actions inside data types like &lt;code&gt;[]&lt;/code&gt;, &lt;code&gt;Maybe&lt;/code&gt;, &lt;code&gt;Either a&lt;/code&gt;, &lt;code&gt;((,) a)&lt;/code&gt;, and others.&lt;/p&gt;

&lt;p&gt;Of course, we cannot provide an implementation of &lt;code&gt;fmap&lt;/code&gt; that works for all contexts. Instead, to use it on a data type, that type needs to have an instance of the Functor typeclass. As we’ll see, Functor is the thing that provides the implementation.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Functor typeclass
&lt;/h2&gt;

&lt;p&gt;What’s the Functor typeclass? Let’s ask GHCi.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; :info Functor
type Functor :: (* -&amp;gt; *) -&amp;gt; Constraint
class Functor f where
  fmap :: (a -&amp;gt; b) -&amp;gt; f a -&amp;gt; f b
  (&amp;lt;$) :: a -&amp;gt; f b -&amp;gt; f a
  {-# MINIMAL fmap #-}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Functor in Haskell is a &lt;a href="https://serokell.io/blog/haskell-typeclasses"&gt;typeclass&lt;/a&gt; that provides two methods – &lt;code&gt;fmap&lt;/code&gt; and &lt;code&gt;(&amp;lt;$)&lt;/code&gt; – for structure-preserving transformations.&lt;/p&gt;

&lt;p&gt;To implement a Functor instance for a data type, you need to provide a type-specific implementation of &lt;code&gt;fmap&lt;/code&gt; – the function we already covered.&lt;/p&gt;

&lt;p&gt;For most common data types, instances of Functor are already implemented. For your own data types, you’ll need to define them yourself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Option a = Some a | None

instance Functor Option where
  fmap f (Some a) = Some (f a)
  fmap f None = None

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We’ll cover how to do this in more detail later.&lt;/p&gt;

&lt;h3&gt;
  
  
  What can be a functor?
&lt;/h3&gt;

&lt;p&gt;There’s two things that limit what you can implement a Functor instance for: the kind signature of Functor and its laws.&lt;/p&gt;

&lt;h4&gt;
  
  
  Kind signature of Functor
&lt;/h4&gt;

&lt;p&gt;The &lt;a href="https://wiki.haskell.org/Kind"&gt;kind&lt;/a&gt; of Functor is &lt;code&gt;(* -&amp;gt; *) -&amp;gt; Constraint&lt;/code&gt;, which means that we can implement Functor for types whose kind is &lt;code&gt;* -&amp;gt; *&lt;/code&gt;. In other words, we can implement Functor for types that have one unapplied type variable.&lt;/p&gt;

&lt;p&gt;For example, &lt;code&gt;Maybe&lt;/code&gt; and &lt;code&gt;[]&lt;/code&gt; take one type variable. Hence their kind is &lt;code&gt;* -&amp;gt; *&lt;/code&gt;, and there’s a straightforward Functor implementation for them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; :kind Maybe
Maybe :: * -&amp;gt; *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Int&lt;/code&gt; has no type variables, and its kind is &lt;code&gt;*&lt;/code&gt;, so you cannot create a &lt;code&gt;Functor&lt;/code&gt; instance for it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; :kind Int
Int :: *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Either&lt;/code&gt; takes two type variables, so it’s kind is &lt;code&gt;* -&amp;gt; * -&amp;gt; *&lt;/code&gt;. But if we apply it once, we can make the kind be &lt;code&gt;* -&amp;gt; *&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;&amp;gt; :kind Either
Either :: * -&amp;gt; * -&amp;gt; *
&amp;gt; :kind Either String
Either String :: * -&amp;gt; *

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Therefore, there is a valid Functor instance for an applied &lt;code&gt;Either&lt;/code&gt; – &lt;code&gt;instance Functor Either a&lt;/code&gt;, where &lt;code&gt;a&lt;/code&gt; signifies any variable that could be applied.&lt;/p&gt;

&lt;h4&gt;
  
  
  Functor laws
&lt;/h4&gt;

&lt;p&gt;Some of Haskell typeclasses have laws – conditions that instances have to meet. Usually, these laws come from the math concept of the same name.&lt;/p&gt;

&lt;p&gt;A functor is a &lt;a href="https://en.wikipedia.org/w/index.php?title=Functor&amp;amp;oldid=1093605134"&gt;mapping&lt;/a&gt; in category theory. Hence, we need &lt;code&gt;fmap&lt;/code&gt; to adhere to the following laws.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Identity&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Composition&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You may wonder why you should follow these laws. The answer is simple – if the instance doesn’t meet these conditions, the typeclass’ methods won’t work as expected. You might run into unpredictable behaviour and confuse people that work with your code as well.&lt;/p&gt;

&lt;p&gt;Laws aren’t enforced by the compiler, hence you need to ensure their correctness yourself. It may be a bit difficult at the beginning, but after a couple of instances, it will start to feel natural.&lt;/p&gt;

&lt;p&gt;There is a tool that can verify whether an instance follows laws – &lt;a href="https://hackage.haskell.org/package/QuickCheck"&gt;QuickCheck&lt;/a&gt;. It checks properties by random testing. You can provide it a property the code needs to satisfy (a typeclass law, in our case), which is then checked on a large number of randomly generated values. You may look at the “Checking the laws” section of &lt;a href="https://mmhaskell.com/blog/2017/3/13/obey-the-type-laws"&gt;this article&lt;/a&gt; as an illustration.&lt;/p&gt;

&lt;h3&gt;
  
  
  The &lt;code&gt;(&amp;lt;$)&lt;/code&gt; operator
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;fmap&lt;/code&gt; is all you need to define a &lt;code&gt;Functor&lt;/code&gt; instance. However, the &lt;code&gt;(&amp;lt;$)&lt;/code&gt; operator is worth looking at too.&lt;/p&gt;

&lt;p&gt;Here’s the type signature of &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;(&amp;lt;$) :: a -&amp;gt; f b -&amp;gt; f a

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The operator takes a value of type &lt;code&gt;a&lt;/code&gt;, a value of type &lt;code&gt;b&lt;/code&gt; packed in a functor &lt;code&gt;f&lt;/code&gt; – &lt;code&gt;f b&lt;/code&gt; – and produces a functor &lt;code&gt;f a&lt;/code&gt;. Basically, the operator packs the first argument’s value in the context of the second argument, throwing away the second value.&lt;/p&gt;

&lt;p&gt;Now, a little exercise. Let’s try to guess the definition of &lt;code&gt;(&amp;lt;$)&lt;/code&gt; by using the provided description and the following examples.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- replace an `Int` value
-- inside `Maybe Int`
-- with a `String`
&amp;gt; "abc" &amp;lt;$ Just 123
Just "abc"
&amp;gt; "abc" &amp;lt;$ Nothing
Nothing

-- replace each element
-- of the list `[Int]`
-- with an `Int`
&amp;gt; 1 &amp;lt;$ []
[]
&amp;gt; 1 &amp;lt;$ [0]
[1]
&amp;gt; 1 &amp;lt;$ [1..5]
[1,1,1,1,1]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pay close attention to the list examples. &lt;code&gt;y &amp;lt;$ [x1, x2, x3]&lt;/code&gt; results in &lt;code&gt;[y, y, y]&lt;/code&gt; not &lt;code&gt;[y]&lt;/code&gt; since the list has many values inside and not one. Each element of the list is transformed instead of the value being wrapped in &lt;code&gt;[]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So, what do you think is the default definition of &lt;code&gt;(&amp;lt;$)&lt;/code&gt;?&lt;/p&gt;

&lt;h1&gt;
  
  
  The definition of &lt;code&gt;(&amp;lt;$)&lt;/code&gt;.
&lt;/h1&gt;

&lt;p&gt;Exactly! &lt;code&gt;(&amp;lt;$)&lt;/code&gt; just runs &lt;code&gt;fmap&lt;/code&gt; with &lt;code&gt;const&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x &amp;lt;$ f = fmap (const x) f

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Now that we’ve seen the basic components of Functor, it’s time to create our own instance of this typeclass!&lt;/p&gt;

&lt;h2&gt;
  
  
  How to implement a Functor instance
&lt;/h2&gt;

&lt;p&gt;Let’s see how you can implement your own instance of Functor. We’ll use the &lt;a href="https://hackage.haskell.org/package/base-4.16.1.0/docs/Data-List-NonEmpty.html#t:NonEmpty"&gt;&lt;code&gt;NonEmpty&lt;/code&gt;&lt;/a&gt; data type as an example.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NonEmpty'&lt;/code&gt; represents a list with at least one element. It has two components: a must-have head &lt;code&gt;a&lt;/code&gt; and a tail &lt;code&gt;[a]&lt;/code&gt;, which might be empty.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data NonEmpty' a = NonEmpty'
  { neHead :: a
  , neTail :: [a]
  }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To define the Functor instance, we need to implement &lt;code&gt;fmap&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We define it by pattern matching on the head and the tail of the non-empty list. Applying &lt;code&gt;f&lt;/code&gt; to the head &lt;code&gt;x&lt;/code&gt; takes care of it, but what about the tail?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; to be able to write the type signature of &lt;code&gt;fmap&lt;/code&gt; in an instance definition, you need to use the &lt;a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html#extension-InstanceSigs"&gt;&lt;code&gt;InstanceSigs&lt;/code&gt;&lt;/a&gt; extension.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;instance Functor NonEmpty' where
  fmap :: (a -&amp;gt; b) -&amp;gt; NonEmpty' a -&amp;gt; NonEmpty' b
  fmap f (NonEmpty' x xs) = NonEmpty' (f x) ??

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The tail is a regular list. And &lt;code&gt;fmap&lt;/code&gt; for lists is already defined, so we can just use that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;instance Functor NonEmpty' where
  fmap :: (a -&amp;gt; b) -&amp;gt; NonEmpty' a -&amp;gt; NonEmpty' b
  fmap f (NonEmpty' x xs) = NonEmpty' (f x) (fmap f xs)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, let’s explore the implementation to understand the mechanics of &lt;code&gt;fmap&lt;/code&gt; better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;instance Functor [] where
  fmap :: (a -&amp;gt; b) -&amp;gt; [a] -&amp;gt; [b]
  fmap f x:xs = f x : fmap f xs
  fmap _ [] = []

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In fact, it follows the same principle – splitting a list on head and tail and calling the function recursively. On each iteration, we apply &lt;code&gt;f&lt;/code&gt; to the head and call &lt;code&gt;fmap&lt;/code&gt; with the tail of the list. In the end, we need to cover the empty-list case – “fmapping” an empty list gives an empty list.&lt;/p&gt;

&lt;p&gt;And it’s done! You’ve just seen how to define an instance of Functor. If you wish to practice more, the &lt;a href="https://serokell.io/blog/whats-that-typeclass-functor#exercises"&gt;exercise section&lt;/a&gt; has an additional implementation exercise for you to try.&lt;/p&gt;

&lt;h2&gt;
  
  
  Functor is not always a container
&lt;/h2&gt;

&lt;p&gt;There is one noteworthy fact about Functor – it’s not always a container. The laws of Functor permit some rather wild implementations. For example, functions are functors too!&lt;/p&gt;

&lt;p&gt;But is there any data type that corresponds to functions? The answer is yes. It’s &lt;code&gt;(-&amp;gt;)&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;&amp;gt; :info (-&amp;gt;)
type (-&amp;gt;) :: * -&amp;gt; * -&amp;gt; *
data (-&amp;gt;) a b

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;(-&amp;gt;)&lt;/code&gt; is parametrized with two types – &lt;code&gt;(-&amp;gt;) a b&lt;/code&gt;. In other words, it is &lt;code&gt;a -&amp;gt; b&lt;/code&gt; – a function with one argument.&lt;/p&gt;

&lt;p&gt;We know that Functor can only be implemented for types with the &lt;code&gt;* -&amp;gt; *&lt;/code&gt; kind. Unfortunately, the kind of &lt;code&gt;(-&amp;gt;)&lt;/code&gt; is &lt;code&gt;* -&amp;gt; * -&amp;gt; *&lt;/code&gt;. It doesn’t satisfy the Functor instance in this form because a Functor can only have one type argument.&lt;/p&gt;

&lt;p&gt;Hence, it’s required to apply it once, as we do with &lt;code&gt;Either a&lt;/code&gt; or &lt;code&gt;((,) a)&lt;/code&gt;. In the &lt;code&gt;(-&amp;gt;)&lt;/code&gt; case, it means providing the function argument’s type – &lt;code&gt;(-&amp;gt;) a&lt;/code&gt; or &lt;code&gt;a -&amp;gt;&lt;/code&gt; (the latter is not valid syntax in Haskell, though).&lt;/p&gt;

&lt;p&gt;For example, functions with the following type signatures have Functor instances:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Int -&amp;gt; a
String -&amp;gt; a
(Char, Int) -&amp;gt; a
[Int] -&amp;gt; a

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we’ve found out what functions can be functors and what data they match. The next question is – what does it mean to &lt;code&gt;fmap&lt;/code&gt; a function? Intuitively, it’s about changing the function, i.e., the action it performs. But what is the fixed context here?&lt;/p&gt;

&lt;p&gt;Let’s construct the type definition of &lt;code&gt;fmap&lt;/code&gt; for a one-argument function. For an arbitrary Functor &lt;code&gt;f&lt;/code&gt;, &lt;code&gt;fmap&lt;/code&gt; is:&lt;br&gt;
&lt;/p&gt;

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

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The type of our data is &lt;code&gt;(-&amp;gt;) c&lt;/code&gt;. Therefore, we need to replace &lt;code&gt;f t&lt;/code&gt; by &lt;code&gt;(-&amp;gt;) c t&lt;/code&gt; or &lt;code&gt;c -&amp;gt; t&lt;/code&gt;. Consequently, the type signature is:&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; (c -&amp;gt; a) -&amp;gt; (c -&amp;gt; b)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can see that the fixed context corresponds to the type of function’s argument &lt;code&gt;c&lt;/code&gt;. And the value being modified is the function’s return type – we go from &lt;code&gt;a&lt;/code&gt; to &lt;code&gt;b&lt;/code&gt; with the help of the &lt;code&gt;a -&amp;gt; b&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;All in all, &lt;code&gt;fmap&lt;/code&gt; for functions transforms what the function returns while keeping the input unchanged! Does that look familiar to you?&lt;/p&gt;

&lt;h1&gt;
  
  
  Which Haskell function or operator can produce a &lt;code&gt;c -&amp;gt; b&lt;/code&gt; function from &lt;code&gt;a -&amp;gt; b&lt;/code&gt; and &lt;code&gt;c -&amp;gt; a&lt;/code&gt;?
&lt;/h1&gt;

&lt;p&gt;Function composition:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; :t (.)
(.) :: (a -&amp;gt; b) -&amp;gt; (c -&amp;gt; a) -&amp;gt; c -&amp;gt; b

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that&lt;/p&gt;

&lt;p&gt;&lt;code&gt;(a -&amp;gt; b) -&amp;gt; (c -&amp;gt; a) -&amp;gt; c -&amp;gt; b&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;is exactly the same as&lt;/p&gt;

&lt;p&gt;&lt;code&gt;(a -&amp;gt; b) -&amp;gt; (c -&amp;gt; a) -&amp;gt; (c -&amp;gt; b)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;since &lt;code&gt;-&amp;gt;&lt;/code&gt; in Haskell is right-associative.&lt;/p&gt;




&lt;p&gt;Cool! &lt;code&gt;fmap&lt;/code&gt; for Functor is just the composition of functions.&lt;/p&gt;

&lt;p&gt;Here’s the &lt;code&gt;((-&amp;gt;) a)&lt;/code&gt; instance implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;instance Functor ((-&amp;gt;) a) where
  fmap = (.)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In conclusion, let’s make sure &lt;code&gt;fmap&lt;/code&gt; is &lt;code&gt;(.)&lt;/code&gt; for one-argument function &lt;code&gt;a -&amp;gt; b&lt;/code&gt; with the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- fmap :: (Int -&amp;gt; Int) -&amp;gt; (Int -&amp;gt; Int) -&amp;gt; Int -&amp;gt; Int
&amp;gt; fmap (+1) (*2) 2
5
&amp;gt; (+1) . (*2) $ 2
5

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s uncommon to consider a function a Functor in Haskell. In fact, it’s more of a fancy case. However, you’ll not be puzzled when you come across this magical and strange usage of &lt;code&gt;fmap&lt;/code&gt; in the future!&lt;/p&gt;

&lt;h2&gt;
  
  
  Why is Functor useful?
&lt;/h2&gt;

&lt;p&gt;In general, Functor is not an extraordinary typeclass. Its methods are easy to grasp and to implement.&lt;/p&gt;

&lt;p&gt;Nevertheless, a Haskell project can hardly do without a couple of Functor instances. It enables one to do transformations on the wrapped type without knowing anything about the wrapper, and that’s very beneficial.&lt;/p&gt;

&lt;p&gt;Moreover, Functor is a solid basis and the predecessor of the Applicative typeclass, which further leads to Monad. The latter is a famous and widely used typeclass in Haskell. Understanding it will give you a considerably greater command of the language.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we have covered the Functor typeclass: what it is, where it can be used, and how to implement your own instances of Functor. It’s a part of the &lt;a href="https://serokell.io/blog/what's-that-typeclass"&gt;What’s That Typeclass&lt;/a&gt; series, where we introduce readers to commonly used Haskell typeclasses.&lt;/p&gt;

&lt;p&gt;If you want to read more articles from Serokell, be sure to follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt; or subscribe to the newsletter via the form below.&lt;/p&gt;

&lt;p&gt;And finally, if you see anything that’s wrong with the article or if there’s something you don’t understand, you’re welcome to submit an issue in our &lt;a href="https://github.com/serokell/blog-posts"&gt;GitHub repo&lt;/a&gt; – we’d appreciate that greatly!&lt;/p&gt;

&lt;h2&gt;
  
  
  Exercises
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Implement Functor for &lt;a href="https://en.wikipedia.org/w/index.php?title=Binary_search_tree&amp;amp;oldid=1053783914"&gt;binary search trees&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Implement &lt;code&gt;(&amp;lt;$)&lt;/code&gt; for &lt;code&gt;Maybe a&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Implement a function that converts strings to upper case (&lt;code&gt;toUpperString :: String -&amp;gt; String&lt;/code&gt;) without using &lt;a href="https://hackage.haskell.org/package/base-4.16.1.0/docs/Data-Char.html#v:toUpper"&gt;toUpper&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Prove that the &lt;code&gt;instance Functor ((-&amp;gt;) a)&lt;/code&gt; we discussed previously follows the identity and composition laws.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>haskell</category>
      <category>functional</category>
    </item>
    <item>
      <title>Universal and Existential Quantification in Haskell</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 19 Jul 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/universal-and-existential-quantification-in-haskell-1g0h</link>
      <guid>https://dev.to/serokell/universal-and-existential-quantification-in-haskell-1g0h</guid>
      <description>&lt;p&gt;In logic, there are two common quantifiers: the universal quantifier and the existential quantifier. You might recognize them as ∀ (for all) and ∃ (there exists).&lt;/p&gt;

&lt;p&gt;They are relevant to Haskellers as well, since both universal and existential quantification are possible in Haskell.&lt;/p&gt;

&lt;p&gt;In this article, we’ll cover both types of quantification.&lt;/p&gt;

&lt;p&gt;You’ll learn how to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Make universal quantification explicit with &lt;code&gt;ExplicitForAll&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Create a heterogeneous list with existential data types.&lt;/li&gt;
&lt;li&gt;Use existentially quantified type variables to make instantiation happen at the definition site.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Universal quantification
&lt;/h2&gt;

&lt;p&gt;In Haskell, all type variables are universally quantified by default. It just happens implicitly.&lt;/p&gt;

&lt;p&gt;As an example, look at the &lt;code&gt;id&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;id :: a -&amp;gt; a

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can think of it as “for all types aaa, this function takes a value of that type and returns a value of the same type”.&lt;/p&gt;

&lt;p&gt;With the &lt;a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/explicit_forall.html"&gt;&lt;code&gt;ExplicitForAll&lt;/code&gt;&lt;/a&gt; extension, we can write that down explicitly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{-# LANGUAGE ExplicitForAll #-}

id :: forall a. a -&amp;gt; a

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The syntax is simple – at the beginning of a function or instance declaration, before any constraints or arguments are used, we use the &lt;code&gt;forall&lt;/code&gt; quantifier to introduce all type variables that we’ll use later.&lt;/p&gt;

&lt;p&gt;Here, we introduce four variables: &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt;, &lt;code&gt;c&lt;/code&gt;, and &lt;code&gt;m&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;func :: forall a b c m. a -&amp;gt; b -&amp;gt; m c -- OK, it compiles

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All type variables that you introduce in your type signature should belong to exactly one &lt;code&gt;forall&lt;/code&gt;. No more, no less.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func :: forall a b c. a -&amp;gt; b -&amp;gt; m c -- Error, type variable `m` is not introduced

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Of course, we can also add constraints. For example, we might want to specify that the &lt;code&gt;m&lt;/code&gt; variable needs an instance of the &lt;code&gt;Monad&lt;/code&gt; typeclass.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func :: forall a b c m. Monad m =&amp;gt; a -&amp;gt; b -&amp;gt; m c

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So far, it might not seem very useful. Nothing changes when we add the quantifier because it’s already there (although implicit). On its own, &lt;code&gt;ExplicitForAll&lt;/code&gt; doesn’t do a lot.&lt;/p&gt;

&lt;p&gt;However, making the quantification explicit allows us to do some new things. You frequently need it to work with other extensions. Some of them will work better, and some of them just won’t work at all without the &lt;code&gt;forall&lt;/code&gt; quantifier. :)&lt;/p&gt;

&lt;h3&gt;
  
  
  Practical use cases of universal quantification
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Reordering type variables
&lt;/h4&gt;

&lt;p&gt;With &lt;code&gt;ExplicitForAll&lt;/code&gt;, you can change the order that type variables appear in the &lt;code&gt;forall&lt;/code&gt; quantifier.&lt;/p&gt;

&lt;p&gt;Why is that useful? Let’s imagine you want to define a function with 10 type variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;veryLongFunction :: a -&amp;gt; b -&amp;gt; c -&amp;gt; d -&amp;gt; e -&amp;gt; f -&amp;gt; g -&amp;gt; h -&amp;gt; i -&amp;gt; j
veryLongFunction = ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(Yes, there are &lt;a href="https://hackage.haskell.org/package/leancheck-0.9.10/docs/Test-LeanCheck-Utils-TypeBinding.html#v:-45--62--62--62--62--62--62--62--62--62--62--62--62-:"&gt;real-life examples&lt;/a&gt; of such functions.)&lt;/p&gt;

&lt;p&gt;And when you use it, you want to instantiate the last type variable explicitly.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Instantiation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before we proceed, a quick note on the &lt;em&gt;instantiation&lt;/em&gt; of type variables – the process of &lt;em&gt;plugging in&lt;/em&gt; a type to replace a type variable.&lt;/p&gt;

&lt;p&gt;You can either let GHC do instantiation implicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fst :: forall a b. (a, b) -&amp;gt; a
fst (x, _) = x

pair :: (Int, String)
pair = (1, "a")

-- The argument of `fst` is of type `(Int, String)`,
-- so GHC infers how to instantiate its type variables:
-- a=Int, b=String.
x = fst pair

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or you can do it explicitly with the &lt;a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/type_applications.html"&gt;&lt;code&gt;TypeApplications&lt;/code&gt;&lt;/a&gt; extension:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{-# LANGUAGE TypeApplications #-}

-- Explicitly instantiate fst's first type variable to Int
-- and the second type variable to String.
x = fst @Int @String pair

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;TypeApplications&lt;/code&gt; assigns types to type variables in the order they appear in the (implicit or explicit) &lt;code&gt;forall&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Explicit instantiation with &lt;code&gt;TypeApplications&lt;/code&gt; is often used to give GHC a hand when it’s having trouble inferring a type or simply to make code more readable.&lt;/p&gt;




&lt;p&gt;Now, without an explicit &lt;code&gt;forall&lt;/code&gt;, you would write something 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;veryLongFunction :: a -&amp;gt; b -&amp;gt; c -&amp;gt; d -&amp;gt; e -&amp;gt; f -&amp;gt; g -&amp;gt; h -&amp;gt; i -&amp;gt; j
veryLongFunction = ...

func = veryLongFunction @_ @_ @_ @_ @_ @_ @_ @_ @_ @Integer ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Quite long, right? However, this can be simplified with an explicit &lt;code&gt;forall&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;veryLongFunction :: forall j a b c d e f g h i. a -&amp;gt; b -&amp;gt; c -&amp;gt; d -&amp;gt; e -&amp;gt; f -&amp;gt; g -&amp;gt; h -&amp;gt; i -&amp;gt; j
veryLongFunction = ...

func = veryLongFunction @Integer ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since &lt;code&gt;j&lt;/code&gt; is the first type variable in the declaration of &lt;code&gt;veryLongFunction&lt;/code&gt;, you can explicitly instantiate only &lt;code&gt;j&lt;/code&gt; and omit the others.&lt;/p&gt;

&lt;h3&gt;
  
  
  Supporting &lt;code&gt;ScopedTypeVariables&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;A common extension that needs &lt;code&gt;ExplicitForAll&lt;/code&gt; is &lt;a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/scoped_type_variables.html#"&gt;&lt;code&gt;ScopedTypeVariables&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The code below may seem reasonable, but it will not compile.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;example :: a -&amp;gt; [a] -&amp;gt; [a]
example x rest = pair ++ rest
  where
    pair :: [a]
    pair = [x, x]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It seems reasonable because it &lt;em&gt;looks&lt;/em&gt; like both functions are referring to the same type variable &lt;code&gt;a&lt;/code&gt;. However, GHC is actually inserting an implicit &lt;code&gt;forall&lt;/code&gt; in both functions. In other words, each function has its own type variable &lt;code&gt;a&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;example :: forall a. a -&amp;gt; [a] -&amp;gt; [a]
example x rest = pair ++ rest
  where
    pair :: forall a. [a]
    pair = [x, x]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can rename one of those type variables to make the issue even more obvious:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;example :: forall a. a -&amp;gt; [a] -&amp;gt; [a]
example x rest = pair ++ rest
  where
    pair :: forall b. [b]
    pair = [x, x]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it’s clear that &lt;code&gt;pair&lt;/code&gt; is a polymorphic function that promises to return a list of any type &lt;code&gt;b&lt;/code&gt;, but its implementation actually returns a list of type &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;What we &lt;em&gt;meant&lt;/em&gt; to say was that &lt;code&gt;pair&lt;/code&gt; should be a monomorphic function that return a list of the type &lt;code&gt;a&lt;/code&gt; declared in &lt;code&gt;example&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To fix this, we can enable the &lt;code&gt;ScopedTypeVariables&lt;/code&gt; extension. With this, the type variables declared in an explicit &lt;code&gt;forall&lt;/code&gt; will be scoped over any accompanying definitions, like &lt;code&gt;pair&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;{-# LANGUAGE ScopedTypeVariables #-}

example :: forall a. a -&amp;gt; [a] -&amp;gt; [a]
example x rest = pair ++ rest
  where
    pair :: [a]
    pair = [x, x]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above are just two of many examples where &lt;code&gt;ExplicitForAll&lt;/code&gt; is useful. Other extensions that benefit from the usage of &lt;code&gt;ExplicitForAll&lt;/code&gt; are &lt;code&gt;LiberalTypeSynonyms&lt;/code&gt;, &lt;code&gt;RankNTypes&lt;/code&gt;, and many more.&lt;/p&gt;

&lt;h2&gt;
  
  
  Existential quantification
&lt;/h2&gt;

&lt;p&gt;As said earlier, besides universal quantification, Haskell also supports existential quantification. This too can be done with the &lt;code&gt;forall&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;You can do it this way because these two constructions – &lt;code&gt;(exists x. p x) -&amp;gt; q&lt;/code&gt; and &lt;code&gt;forall x. (p x -&amp;gt; q)&lt;/code&gt; – are equivalent in terms of first-order predicate logic. For a theoretical proof of this statement, you can check this &lt;a href="https://stackoverflow.com/questions/10753073/whats-the-theoretical-basis-for-existential-types?rq=1"&gt;thread&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In this section, we’ll look at existential quantification in data types and function signatures.&lt;/p&gt;

&lt;h3&gt;
  
  
  Existential quantification in data types
&lt;/h3&gt;

&lt;p&gt;First, to declare existentially quantified data types, you need to enable either the &lt;a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/existential_quantification.html"&gt;&lt;code&gt;ExistentialQuantification&lt;/code&gt;&lt;/a&gt; or the &lt;a href="https://downloads.haskell.org/~ghc/6.4/docs/html/users_guide/gadt.html"&gt;&lt;code&gt;GADTs&lt;/code&gt;&lt;/a&gt; extension.&lt;/p&gt;

&lt;p&gt;A classic motivating example are heterogeneous lists. Haskell’s &lt;code&gt;[]&lt;/code&gt; type represents a homogeneous list: a list whose elements are all of the same type. You can’t have a list where the first element is an &lt;code&gt;Int&lt;/code&gt; and the second is a &lt;code&gt;String&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;However, you can emulate a heterogeneous list by wrapping all the elements in an existential type.&lt;/p&gt;

&lt;p&gt;You can define an existential type by using &lt;code&gt;forall&lt;/code&gt; on the left side of the constructor name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Elem = forall a. MkElem a

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This effectively “hides” the element’s type &lt;code&gt;a&lt;/code&gt; inside the &lt;code&gt;MkElem&lt;/code&gt; constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multitypedList :: [Elem]
multitypedList = [MkElem "a", MkElem 1, MkElem (Just 5)]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not very useful, though. When we pattern match on &lt;code&gt;MkElem&lt;/code&gt;, the type of the inner value is not known at compile time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useElem :: Elem -&amp;gt; Int
useElem (MkElem (x :: Int)) = x + 1
                 ^^^^^^^^
-- • Couldn't match expected type ‘a’ with actual type ‘Int’

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There’s nothing we can do with it, not even print it to stdout.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;printElem :: Elem -&amp;gt; IO ()
printElem (MkElem x) =
  print x
  ^^^^^^^
-- • No instance for (Show a) arising from a use of ‘print’
-- Possible fix:
-- add (Show a) to the context of the data constructor ‘MkElem’

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GHC kindly suggests adding a &lt;code&gt;Show&lt;/code&gt; constraint to the &lt;code&gt;MkElem&lt;/code&gt; constructor. Now, when we match on &lt;code&gt;MkElem&lt;/code&gt;, the &lt;code&gt;Show&lt;/code&gt; instance is brought into scope, and we can print our values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Elem = forall a. (Show a) =&amp;gt; MkElem a

multitypedList :: [Elem]
multitypedList = [MkElem "a", MkElem 1, MkElem (Just 5)]

printElem :: Elem -&amp;gt; IO ()
printElem (MkElem x) =
  -- We can use `print` here because we have a `Show a` instance in scope.
  print x

main :: IO ()
main = forM_ multitypedList printElem

λ&amp;gt; "a"
λ&amp;gt; 1
λ&amp;gt; Just 5

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that, since the type variable &lt;code&gt;a&lt;/code&gt; is “hidden” inside the &lt;code&gt;MkElem&lt;/code&gt; constructor, you can only use the constraints declared in the constructor. You can’t constrain it any further.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;allEqual :: Eq ??? =&amp;gt; [Elem] -&amp;gt; Bool -- There is no type variable that you can add a constraint to.
allEqual = ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another useful example of hiding type variables is the &lt;code&gt;SomeException&lt;/code&gt; wrapper.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data SomeException = forall e. Exception e =&amp;gt; SomeException e

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All exceptions, upon being thrown, are wrapped in &lt;code&gt;SomeException&lt;/code&gt;. If you want to catch all thrown exceptions, you can use &lt;code&gt;catchAll&lt;/code&gt; to catch a &lt;code&gt;SomeException&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When you pattern match on the &lt;code&gt;SomeException&lt;/code&gt; constructor, its &lt;code&gt;Exception&lt;/code&gt; instance is brought into scope.&lt;code&gt;Exception&lt;/code&gt; &lt;a href="https://hackage.haskell.org/package/base/docs/Control-Exception.html#t:Exception"&gt;implies &lt;code&gt;Typeable&lt;/code&gt; and &lt;code&gt;Show&lt;/code&gt;&lt;/a&gt;, so those instances are also brought into scope.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exceptionHandler :: SomeException -&amp;gt; IO ()
exceptionHandler (SomeException (ex :: e)) =
  -- The following instances are in scope here:
  -- `Exception e`, `Typeable e`, `Show e`
  ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These three instances are all the information we have about &lt;code&gt;ex&lt;/code&gt; at compile time. Luckily, the &lt;code&gt;Typeable&lt;/code&gt; instance we have in scope lets us perform a&lt;a href="https://hackage.haskell.org/package/base/docs/Data-Typeable.html#v:cast"&gt;runtime cast&lt;/a&gt;, and that’s exactly what functions like &lt;code&gt;catch&lt;/code&gt; and &lt;code&gt;fromException&lt;/code&gt; do under the hood.&lt;/p&gt;

&lt;h3&gt;
  
  
  Existential quantification in function signatures
&lt;/h3&gt;

&lt;p&gt;Type variables of a function can also be existentially quantified.&lt;/p&gt;

&lt;p&gt;Before proceeding further, let’s first have a look at higher-rank types.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Higher-rank types&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By default, Haskell98 supports rank-0 and rank-1 types.&lt;/p&gt;

&lt;p&gt;Rank-0 types are just monomorphic types (also called monotypes), i.e. they don’t have any type variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;f :: Int -&amp;gt; Int

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rank-1 types have a &lt;code&gt;forall&lt;/code&gt; that does not appear to the left of any arrow. The type variables bound by that &lt;code&gt;forall&lt;/code&gt; are universally quantified.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;f :: forall a. a -&amp;gt; a

-- Keep in mind that the `-&amp;gt;` operator has precedence over `.`
-- so this is equivalent to:
f :: forall a. (a -&amp;gt; a)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By enabling the &lt;a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/rank_polymorphism.html"&gt;&lt;code&gt;RankNTypes&lt;/code&gt;&lt;/a&gt; extension, we unlock &lt;em&gt;higher-rank&lt;/em&gt; types. Just like higher-order functions take other functions as arguments, higher-rank types take lower-rank types as arguments.&lt;/p&gt;

&lt;p&gt;Rank-2 types take a type of rank 1 (but no higher) as an argument. In other words, they may have a &lt;code&gt;forall&lt;/code&gt; that appears to the left of one arrow. The type variables bound by that &lt;code&gt;forall&lt;/code&gt; are &lt;em&gt;existentially&lt;/em&gt; quantified.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;f :: (forall a. (a -&amp;gt; a)) -&amp;gt; Int

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similarly, rank-3 types take a type of rank 2 (but no higher) as an argument. The &lt;code&gt;forall&lt;/code&gt; appears to the left of two arrows.&lt;/p&gt;

&lt;p&gt;Here, &lt;code&gt;a&lt;/code&gt; is universally quantified.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;f :: ((forall a. (a -&amp;gt; a)) -&amp;gt; Int) -&amp;gt; Int

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In general:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A rank-n type is a function whose highest rank argument is n-1.&lt;/li&gt;
&lt;li&gt;A type variable is universally quantified if it’s bound by a forall appearing to the left of an even number of arrows.&lt;/li&gt;
&lt;li&gt;A type variable is existentially quantified if it’s bound by a forall appearing to the left of an odd number of arrows.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here’s another example for good measure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;f :: forall a. a -&amp;gt; (forall b. Show b =&amp;gt; b -&amp;gt; IO ()) -&amp;gt; IO ()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;f&lt;/code&gt; is a rank-2 type with two type variables: a universal type variable &lt;code&gt;a&lt;/code&gt; and an existential type variable &lt;code&gt;b&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;But what does it &lt;em&gt;mean&lt;/em&gt; for a type variable to be existentially quantified?&lt;/p&gt;

&lt;p&gt;In short: whereas universally quantified type variables are instantiated at the “use site” (i.e. the &lt;em&gt;user&lt;/em&gt; of the function has to choose which type they want that type variable to be), existentially quantified type variables are instantiated at the “definition site” (where the function is defined). In other words, the function’s definition is free to choose how to instantiate the type variable; but the user of the function is not.&lt;/p&gt;

&lt;p&gt;Let’s look at a real-life example. Imagine a function that prints logs while calculating some result. You may want to write logs to the console or to some file. In order to abstract over where the logs are written to, you pass a logging function as an argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func :: _ -&amp;gt; IO ()
func log = do
  username &amp;lt;- getUsername
  log username

  userCount &amp;lt;- getUserCount
  log userCount

getUsername :: IO String
getUsername = undefined

getUserCount :: IO Int
getUserCount = undefined

main :: IO ()
main = do
  -- log to the console
  func print

  -- log to a logfile
  func (appendFile "logfile.log" . show)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What type should the &lt;code&gt;log&lt;/code&gt; function have? Since it logs both &lt;code&gt;String&lt;/code&gt; and &lt;code&gt;Int&lt;/code&gt;, one might think that adding a function with signature &lt;code&gt;a -&amp;gt; IO&lt;/code&gt; and a constraint &lt;code&gt;Show a&lt;/code&gt; would be enough to implement it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;log :: Show a =&amp;gt; a -&amp;gt; IO ()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, if we try this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func :: Show a =&amp;gt; (a -&amp;gt; IO ()) -&amp;gt; IO ()
func log = ...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will see this compiler error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  log username
      ^^^^^^^^
Couldn't match expected type `a` with actual type `String`...

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We get this error because:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;func&lt;/code&gt;’s type variable &lt;code&gt;a&lt;/code&gt; is universally quantified, therefore it can only be instantiated at the use site.&lt;/li&gt;
&lt;li&gt;We’re trying to instantiate it at &lt;code&gt;func&lt;/code&gt;’s definition site (&lt;code&gt;log username&lt;/code&gt; is trying to instantiate the type variable &lt;code&gt;a&lt;/code&gt; with &lt;code&gt;String&lt;/code&gt; and &lt;code&gt;log userCount&lt;/code&gt; is trying to instantiate the type variable &lt;code&gt;b&lt;/code&gt; with &lt;code&gt;Int&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because we want &lt;code&gt;a&lt;/code&gt; to be instantiated at &lt;code&gt;func&lt;/code&gt;’s definition site (rather than its use site), we need &lt;code&gt;a&lt;/code&gt; to be existentially quantified instead.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{-# LANGUAGE RankNTypes #-}

func :: (forall a. Show a =&amp;gt; a -&amp;gt; IO ()) -&amp;gt; IO ()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the compiler knows that no matter which function we pass to &lt;code&gt;func&lt;/code&gt;, it must work for &lt;em&gt;any&lt;/em&gt; type &lt;code&gt;a&lt;/code&gt;, and &lt;code&gt;func&lt;/code&gt;’s definition will be responsible for instantiating it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func :: (forall a. Show a =&amp;gt; a -&amp;gt; IO ()) -&amp;gt; IO ()
func log = do
  username &amp;lt;- getUsername
  log @String username

  userCount &amp;lt;- getUserCount
  log @Int userCount

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that type applications aren’t strictly necessary here, the compiler is smart enough to infer the right types, but they do help with readability.&lt;/p&gt;

&lt;h3&gt;
  
  
  Connection between existential types and existentially quantified variables
&lt;/h3&gt;

&lt;p&gt;Lastly, we should point out that existential types are isomorphic to functions with existentially quantified variables (i.e. they’re equivalent), hence their name.&lt;/p&gt;

&lt;p&gt;For example, the &lt;code&gt;Elem&lt;/code&gt; type we saw earlier is equivalent to the following &lt;a href="https://en.wikibooks.org/wiki/Haskell/Continuation_passing_style"&gt;CPS&lt;/a&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Elem = forall a. Show a =&amp;gt; MkElem a

type Elem' = forall r. (forall a. Show a =&amp;gt; a -&amp;gt; r) -&amp;gt; r

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And we can prove this isomorphism:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;elemToElem' :: Elem -&amp;gt; Elem'
elemToElem' (MkElem a) f = f a

elem'ToElem :: Elem' -&amp;gt; Elem
elem'ToElem f = f (\a -&amp;gt; MkElem a)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;We have taken a look at universal and existential quantification in Haskell. With a few extensions and the &lt;code&gt;forall&lt;/code&gt; keyword, quantification allows you to further expand the rich type system of the language and to express ideas that were previously impossible.&lt;/p&gt;

&lt;p&gt;For more Haskell tutorials, you can check out our &lt;a href="https://serokell.io/blog/haskell"&gt;Haskell&lt;/a&gt; section or follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you see any issues with the text of the blog or need some help understanding it, you’re welcome to submit an issue in blog’s &lt;a href="https://github.com/serokell/blog-posts"&gt;GitHub repo&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>haskell</category>
    </item>
    <item>
      <title>Functional Futures: Carp with Erik Svedäng</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Thu, 14 Jul 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/functional-futures-carp-with-erik-svedang-4lb9</link>
      <guid>https://dev.to/serokell/functional-futures-carp-with-erik-svedang-4lb9</guid>
      <description>&lt;p&gt;In this month’s episode of Functional Futures, our guest is Erik Svedäng, a game designer who has created many board and video games. Among them is &lt;a href="http://elseheartbreak.com/"&gt;Else Heart.Break()&lt;/a&gt;, a puzzle video game with its own programming language. He is also the creator of &lt;a href="https://github.com/carp-lang/Carp"&gt;Carp&lt;/a&gt;, a statically-typed lisp for real-time applications.&lt;/p&gt;

&lt;p&gt;In the episode, we talk about game design, game development, and how Carp enables developers to build performant games while keeping true to functional programming idioms.&lt;/p&gt;

&lt;p&gt;As always, you can check out the episode on our &lt;a href="https://youtu.be/7qPClP3ssXk"&gt;YouTube channel&lt;/a&gt; or listen to the audio version on our &lt;a href="https://anchor.fm/functionalfutures/episodes/Carp-with-Erik-Svedang-e1l7iso"&gt;podcast page&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Highlights from the episode
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Game design
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; We invite a lot of programming language designers to our podcast. And we usually jump straight into the goals of their programming language and some specifics of the runtime, etc. But with you, we’ll obviously start with games, because this is, as far as I can tell, your passion. And I think that in the case of Carp, your language, it’s kind of impossible not to start by talking about games. I hear a lot of stuff like “oh, games are so silly” or “why do adult humans play games”. Why are games so important to you?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Oh, big question. Well, I think most humans actually do play games. Even people who say they never play games actually prefer or like to play some games on their phone, and they like to play games with their friends, and so on. So it seems to me like only very boring, busy people never play games. And it’s just a part of life, I think, to enjoy games, especially with others.&lt;/p&gt;

&lt;p&gt;So yeah, for me, it’s just one aspect of a full life. Like, you have to have food, you have to enjoy music, and you have to play some games sometimes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; That’s a good description. And when you were talking about it, I thought that maybe even some day-to-day activities that people don’t recognize as games have features of games, where people think about those as games without realizing that those are games.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Sure, yeah, I think that happens a lot. Like, crossword puzzles or game shows on TV, and so on – that’s a very old-fashioned way of streaming.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; A very, I think, important thing to consider when we’re kind of thinking and talking about games is – what are the buckets into which we distribute games. And you know, in my humble opinion, I think the way that a particular game designer spreads the games into these buckets informs the games that this designer makes. How do you divide different games, such as, for example, Sims, Dungeons &amp;amp; Dragons, Magic: The Gathering, and others?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Well, that seems like a long-winded way to get me to define what a game is, which, as an academic of games – that’s a whole complete podcast.&lt;/p&gt;

&lt;p&gt;When I create games, I don’t think too much about these pockets. My games have usually fallen into two piles. One is very hardcore versus games, kind of like new versions of chess and Go, but maybe for iPad and for the digital medium. So those are very much like hardcore game mechanics games.&lt;/p&gt;

&lt;p&gt;And then, on the other hand, I’ve also worked a fair bit with storytelling in games. And I think those games usually can’t use game mechanics in the same way. It’s hard to force too many game mechanics on that kind of game, where the story is actually what you want to focus on.&lt;/p&gt;

&lt;p&gt;So, for example, in Else Heart.Break(), which is one of these story games, despite the puzzles in the programming – if you fail to solve the game or the puzzles, you actually still get to experience a story, it’s just a story about this programmer who is not very good, and it still becomes a fun story. I think, for storytelling, failure is usually a big part of it, stories are about people who have problems. Maybe they succeed in the end, but still, tragedy is a big part of good storytelling.&lt;/p&gt;

&lt;p&gt;I think that’s maybe one of the big divides between games: should the game be about winning or about losing. So yeah, I think that’s one way to divide up games.&lt;/p&gt;

&lt;p&gt;But on the other hand, there is so much technology and systems thinking, and so on that overlaps between these two things, so you could just as well put them into the same bucket and say that it’s just games or whatever.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Does it mean that, for example, when you’re making a, let’s say, computer “versus” game or a board “versus” game, do you think about them in the same way?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; I think I used to think about them completely differently or more differently, but I also feel like the more I’ve played board games and thought about this, I feel like board game and social play, and word play, and all kinds of play can really or could really inform video games in a lot of ways.&lt;/p&gt;

&lt;p&gt;I mean, let’s take something like Among Us, which is kind of a social party game converted to a video game, and it got a really big effect out of that. That’s maybe a good example of the kind of thing you can’t really get to – like, it’s obviously inspired by board games, and so on.&lt;/p&gt;

&lt;p&gt;The more I learn and think about game design, I’ve realized it’s all the same, actually, in the end. It’s systems that we interact with, and what’s really important is what happens in our head when we play and what we experience, actually.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; I wonder how many of our viewers and listeners currently think “well, what is game design, even?” Because, on one hand, it’s a very, very old profession, right? We already mentioned chess and Go in passing, but it’s not like people who were inventing chess were professional game designers, right, it was very much an incremental process that spanned perhaps like hundreds or thousands of years. I mean, we have a documented history of chess rules evolving even over the past three centuries or something.&lt;/p&gt;

&lt;p&gt;But recently, game design, at least as far as I know it’s fairly recently, has started to be recognized as a proper profession and with research elements to it. So you can go to university to study game design, but I think that there’s still this kind of veil of mystery around it. So if you could lift it a little bit and then talk a little bit about what it means to be a game designer, it would be really nice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Sure. I’ve mainly worked as a game designer on my own or with a very small group of friends, so I don’t know much about how it is to be a game designer at a triple-A game studio, actually. It’s probably fun, but it’s very few people who get to command thousands of people to make these huge titles.&lt;/p&gt;

&lt;p&gt;But, I mean, usually the game designer is the person who has an idea for what would be a fun game, so they are kind of the person with a vision, a bit like a director for a game, and they try to get this vision through the process of drawing art and programming the game if it’s a video game. And yeah, they’re usually also very much in charge, of course, of testing the game, especially in the early stages, like playtesting with people and seeing what is fun, and they, of course, play the game themselves a lot and change the rules of the game. So yeah, the person who comes up with the rules and the theme, and so on for the game.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; You mentioned that game designers work a lot on playtesting. So what are the actual further stages in game design before you can, you know, present your black and white prototype or beautiful prototype to your friends and start to test it?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Well, I mean, the most common place for game ideas to die is when you just try to make it work the first time, I would say. Someone has a great idea in their head and they think about the game, and then, when they sit down and start to try to put it to paper or to code or whatever, it just falls apart and it doesn’t feel as much fun as it felt when you thought about it. Because when you thought about it in your head, it was all alive, in a way, but then you have to make it so concrete when you make it on your own, or actually make it.&lt;/p&gt;

&lt;p&gt;So yeah, that’s the first playtest, and it’s not even a playtest, it’s just the first obstacle to get over. But if you can get over that and if you can get through – usually, I try to just simulate the game versus myself to spare anyone the pain of having to play through the game, but if it feels like I actually have to make interesting decisions on my own (let’s say this is a board game), then I’ll bring it to my girlfriend or a friend or something and start playing it, and usually it changes a lot from there.&lt;/p&gt;

&lt;p&gt;And then you just keep doing that and making, hopefully, smaller and smaller changes, until it’s something that actually works. And by that point, maybe you have started adding art and so on, and then you’re actually kind of recreating that magic that you had in your head from the beginning. But there is a long stretch there where it’s just not that cool.&lt;/p&gt;

&lt;p&gt;But if there was something to your initial idea, I mean, that’s kind of the trick – to have this kind of seed or core vision that you can have to remember that feeling that you wanted to create in people at the beginning. If you can use that to get to the end point where that actually happens, that’s very cool and satisfying, and then you probably have something good by that point.&lt;/p&gt;

&lt;h3&gt;
  
  
  Game development
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Approaching the language that you made that is game oriented, can you tell us a little bit about how you approach programming games? Does it mimic the design stages? Do you have a method? Like, you have an idea for a game, you kind of have outlined its rules, let’s say, and what do you do then? Are there certain steps, like, I don’t know, I’ll take Unity, I’ll encode my gameplay loop, etc.?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Yeah, I mean, I’ve been jumping around a lot when it comes to technology. I guess, Unity is the thing I’ve used the most. A lot of game developers have the same story, it’s like the go-to tool. Creating my own language is, of course, a way to get away from that. My latest project, I used C for that one as a way to not have to use Unity.&lt;/p&gt;

&lt;p&gt;But no matter what you do, when you make video games, what you usually want to do is to get something up on the screen. And if there is a game about moving around something, which it often is, you want to be able to move that thing with your controls. And the interesting thing about that is as soon as you have that on the screen, since you made this happen, you usually get stuck for hours.&lt;/p&gt;

&lt;p&gt;Anyone who has programmed a game knows this. Like, it could just be a square that you move around with your gamepad, and it’s so much fun to move it around. So yeah, I guess, the professional part of me is like “yeah, yeah, so then don’t do that for five hours” but maybe I do. But yeah, you just want to get to a point where you can start feeling if there is some kind of magic to your idea.&lt;/p&gt;

&lt;p&gt;Usually, with video games, there is a lot more extra stuff and reusing of tried and true game mechanics. For example, maybe you are creating a platforming game where you jump, and even if you have a lot of interesting ideas around the jumping part, it’s gonna work, if it doesn’t work, it’s because you did something wrong, it’s not like this is a broken way to control a character.&lt;/p&gt;

&lt;p&gt;While if you create your own kind of game system from scratch for a board game, it could very well be that it’s not working at all. So it’s a bit different in that sense. But yeah, you just want to get to the unknowns quickly to see if you can get those working, and if your programming skills are good enough to make it happen, whatever it is that you want to happen.&lt;/p&gt;

&lt;h3&gt;
  
  
  Carp
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Basically, as far as I understand, you’re kind of going through the boring parts, and then you get to this open-ended thing where you actually code your game, and then, you know, you hope that you don’t crumble under like technical debt, third-party dependencies, and stuff like this. Where does Carp come into this? From what I understand from our interview so far, you kind of created it out of frustration with state of the art, one could say. Is it fair?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Sure. I’ve spent a lot of time, basically the last 10 years or so, trying to come up with a way to write games using functional languages. I did a lot of research on programming languages when I was making the language for Else Heart.Break(), and that got me, of course, into a lot of theory and books, and information about all these functional languages, and they really spoke to me, especially Lisp and Haskell.&lt;/p&gt;

&lt;p&gt;And at the time Clojure was kind of newish, and I learned a lot of Clojure, and that was my favorite language for a while. And I really wanted to make games with it. It felt like the perfect system for creating games, with the live reload and all of that, but I realized that it had a lot of problems for making a sizable game.&lt;/p&gt;

&lt;p&gt;I mean, Else Heart.Break() is not super optimized, but to create something of that size in Clojure, it would kill the computer, it would die, probably. It’s just really hard to handle the kind of data throughput and garbage collector nonsense that you have to deal with in that kind of language. But at the same time, I, like many people, had seen the light, I had seen how nice these kinds of languages could be and it just felt really boring to go back to writing games in C# and just be fine with that.&lt;/p&gt;

&lt;p&gt;So that’s when I started thinking about if I could make a kind of a Lisp that I could actually use for my future games. That was the vision and goal, which I’m still working towards. I have not yet made an actual finished game with Carp, so it’s still just a distant goal but one that I’m still working towards.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Do you have some demos of squares moving around out there already?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Sure, I mean, I’ve made Game Jam games and so on with it, but I realized that to create a big game with it, it would have to be even more stable and even faster as a compiler. Like, I can’t spend years working on something and then get stuck because my language is not good enough. Even though I think the runtime characteristics of the language would be fine for most things I want to do. But there is also just the whole tooling and especially compilation speed, which becomes a big factor when you make an actual big game or big project.&lt;/p&gt;

&lt;p&gt;So that’s where I’m right now with the project. I’m taking a very good look at how to create a new version of Carp that has much better compilation speed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; And the main features of Carp, aside from it being a Lisp, are that it’s borrow-checked and well-typed, right?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Yeah, exactly. The type system is kind of an ML, very basic, standard, sum types, product types, that kind of stuff. And yeah, it’s using borrow checking, very Rust-inspired but still has a kind of different feel from Rust, it’s not trying to be as detailed as Rust, it’s trying to be a bit slower but more ergonomic.&lt;/p&gt;

&lt;p&gt;Rust is obviously a very huge influence for a lot of programming language designers nowadays, and especially people who want to make languages for games and so on. And yeah, I think it’s just kind of interesting – Rust has made their decisions, but there are many little choices you can make different from them. And I think it’s cool to see different languages trying out variations on the core idea of a fine type system.&lt;/p&gt;

&lt;p&gt;So yeah, it feels like Rust really started a kind of revolution there with lots of languages experimenting with those ideas.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Do I understand correctly that the biggest problem, for example, with using Clojure for programming games would be that you have a lot of stuff going on all the time and since it has a garbage collector, you kind of want to make sure that you don’t hiccup between the frames, or something like that? But how does Unity solve it? Do they have some sort of a custom runtime or is NET just so much better?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; I mean there are many factors there. Unity is written in C++, I think, like the core, so it’s actually not C# all the way. That’s just in the user space. So that’s one answer. The other big answer, of course, is mutability. Like, it’s really relying on mutability, so if you just have a thousand objects in the scene and you move them slightly, you actually create no garbage at all, while if you do that in Clojure, for each frame you would create garbage for basically the whole world each frame, which is a big difference. And yeah, I guess those are the main differences, then also C# and .NET is very good for some kinds of memory usages, but so is JVM, of course.&lt;/p&gt;

&lt;p&gt;But yeah, I think with all those things together, you get a pretty nice system. But people still run into problems with the garbage collector in Unity, so it just becomes a problem later in production. Like, you can get away with it for a long time, but if you don’t think about it, eventually you’ll have to start thinking about it, and at that point it’s not very fun.&lt;/p&gt;

&lt;p&gt;Carp tries to be more upfront about that whole thing. Like, you would have to think about memory in the beginning of your project, but not that much in the end, while C# is the other way around.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; That’s very interesting. I assume you actually have a way to store mutable state of the world in Carp?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Yeah, it’s actually completely free in that sense, exactly like Rust, you can mutate anywhere. It’s not like Haskell where you have to mark things at all. If some algorithm or function would benefit from some kind of mutability, you can just do that wherever you are.&lt;/p&gt;

&lt;p&gt;But the main tools people should reach for when they write a program in Carp are supposed to be functional in nature, so there are maps and filters, and so on, and those are supposed to be how you do the bulk of the work, but you can always go in and mutate if you want to. At least in the current design.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Let’s say I want to make a very big tic-tac-toe or a Game of Life, something that can be unbounded, that can grow. How would you do that in Carp?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; The way I prefer to do it is to write it very much like you would write in Clojure with immutability (like, it looks immutable). So you would maybe have some kind of reduction over the state over time. So you’re actually not storing the state like in a mutable variable or something, you’re just passing it around and around in a recursive function, basically, from the outside. And all your functions look immutable – they take the state and return the state, but since they have the borrow checker rules ingrained in them, they can do internal mutation if that’s faster. And they know that no one else is sharing that state, so it’s completely safe to do so.&lt;/p&gt;

&lt;p&gt;Usually, that’s the kind of code I’ve been trying to make work. You basically take something that would run in Clojure and you run it in Carp instead, and instead of getting killed by GC, it never allocates after the first frame, basically.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; By the way, when I asked you how do you develop a game and you said “well, you want to get something on the screen as soon as possible” – with Carp, I can attest that it’s like really, really quick. It’s almost like I remembered in school when we had the Pascal language and you had like a graph module, you could write like &lt;code&gt;use graph&lt;/code&gt; and draw straight away.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Yeah. I guess most languages could be like that. I just ship the compiler with some graphics bindings to STL. It’s not important that it’s STL, it’s just like it feels good for this kind of project and this kind of language to have something out of the box. It’s not the only thing you can use, but it’s something that everyone will have access to, so if you want to do something quickly or you want to do a tool or something, you know it’s built-in and it’s there. I think that makes a big difference compared to most other languages where you have to go to the package manager and find those bindings.&lt;/p&gt;

&lt;p&gt;I mean, maybe in the future we’ll have to remove it, but I think that has been very good for people to just try out the examples and try out the language. Because it’s supposed to be used for that kind of stuff, it’s good to have it built in. I’m happy you had this experience, that was exactly what I wanted: like, just download the compiler and paste in some simple example code, and actually get graphics on the screen, and not just text.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; What does Carp compile to?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Right now, it compiles to C. The compiler is written in Haskell and compiles or emits C code, and then you use some C compiler on your system to compile it. In my new secret version of the compiler, which is going to be much faster, it’s using LLVM straight up instead of C.&lt;/p&gt;

&lt;p&gt;And if I get that to work out, it’s gonna be much much faster. Since it’s a Lisp, it does a lot of cool stuff with the dynamic runtime to get the language to work, but that is also hard to get fast enough in Haskell. At least for me, it’s hard to write a very efficient interpreter. So the idea there is to use LLVM editing to get a much faster dynamic runtime so that compilation is faster.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; How do you see Carp used in the ideal world? Let’s say you have infinite resources. Like, you can hire the best engineers from Facebook to work on Carp. How would you develop it, and to what goal – how would engineers use the ideal Carp?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Erik:&lt;/strong&gt; Well, I just want to have a decently fast compiler that handles what the language is right now. If you download the compiler right now, it’s a bit buggy but it works. And so I think that system would suit me very well, just no bugs and decently fast compile times is all I’m really asking for.&lt;/p&gt;

&lt;p&gt;My idea was to make it pretty small and easy to learn language, so it’s not supposed to have that much more. The cool thing when you have macros and so on is that you can create so much yourself if something is missing, and that’s been really fun – to see people. For example, one of the coolest things that the community did with the language was to create a derive functionality, which the language did not have, where you could derive different interfaces for types, and that was just all built with macros.&lt;/p&gt;

&lt;p&gt;Yeah, it doesn’t need to be much more than what it is right now, it just has to be done in a more efficient way. And I think now we have learned a lot from creating this current version of the compiler, so I think a rewrite of sorts will be pretty beneficial, in that sense. Since we know so much more about how to create this kind of language.&lt;/p&gt;

&lt;p&gt;But yeah, I don’t need all Facebook engineers to make this happen, it shouldn’t be like the biggest project ever, I think. And I mean, when it comes to reaching out, I think, there is this very particular kind of person who likes both Lisp and game development. There is definitely a crew of people who enjoy both of these things, but it’s never going to be the mainstream. It’s like a niche thing.&lt;/p&gt;

&lt;p&gt;But I think it would be fun if people in that niche got to try it out, and that it worked very well, and they could use it for their projects. So yeah, just trying to fill the needs of the gamedev Lisp programmer, that’s my only goal.&lt;/p&gt;




&lt;p&gt;Thanks to Erik for being a guest on our podcast! 🙏&lt;/p&gt;

&lt;p&gt;If you would like to learn more about Erik and his work, you can visit his &lt;a href="https://www.eriksvedang.com/"&gt;website&lt;/a&gt;. To learn about Carp, you can visit its &lt;a href="https://github.com/carp-lang/Carp"&gt;GitHub page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you want to hear more from us, be sure to subscribe to Functional Futures either on &lt;a href="https://www.youtube.com/c/Serokell"&gt;YouTube&lt;/a&gt; or your favorite podcasting platform.&lt;/p&gt;

</description>
      <category>gamedev</category>
      <category>haskell</category>
      <category>lisp</category>
    </item>
    <item>
      <title>Haskell in Production: Channable</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 28 Jun 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/haskell-in-production-channable-g2i</link>
      <guid>https://dev.to/serokell/haskell-in-production-channable-g2i</guid>
      <description>&lt;p&gt;In our &lt;a href="https://serokell.io/blog/haskell-in-production"&gt;Haskell in Production&lt;/a&gt; series, we interview developers from companies that use Haskell for real-world tasks. We cover benefits, downsides, common pitfalls, and tips for new Haskellers.&lt;/p&gt;

&lt;p&gt;Our today’s guest is Fabian Thorand, who is a team lead at &lt;a href="https://www.channable.com/"&gt;Channable&lt;/a&gt;. Read further to learn where Channable uses Haskell, why they chose it, and what they like and don’t like about it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Interview with Fabian Thorand
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Could you tell us a little bit about Channable and your role there?
&lt;/h3&gt;

&lt;p&gt;Channable offers a channel management platform through which webshops can publish their products (or other offers like job postings or vacation deals) to a wide variety of marketplaces, ad platforms, or price comparison sites. The product information can be tweaked through user-defined rules following a simple “IF … THEN … (ELSE …)” structure (e.g. reducing prices during a sales period or removing products with missing information before sending them to a third-party platform).&lt;/p&gt;

&lt;p&gt;I joined Channable about 4,5 years ago as a backend developer in the infrastructure team, where we work on the core applications powering the Channable tool. About a year ago, the team was split into two subteams due to our continuous growth, and I became the team lead of one of them.&lt;/p&gt;

&lt;h3&gt;
  
  
  Where in your stack do you use Haskell?
&lt;/h3&gt;

&lt;p&gt;We use Haskell for a variety of backend services. The biggest one by far is our data processing system, which powers the import from our customers, manages the data storage, and applies the user-defined rules to the data before streaming it to other components in our backend which handle the actual connections to the third-party platforms.&lt;/p&gt;

&lt;p&gt;Another big project is our job-scheduling system for running a set of jobs with dependencies between them in the right order on a cluster of worker machines (think of “downloading data from the client system” or “exporting products to a third-party system”).&lt;/p&gt;

&lt;p&gt;The third major part of our infrastructure using Haskell is an API gateway that handles routing (to our various backend services) and provides a common implementation for authentication, authorization, rate-limiting, etc. so that the backend services don’t have to concern themselves with that.&lt;/p&gt;

&lt;p&gt;Last but not least, there are a few smaller utilities that we have open-sourced, such as &lt;code&gt;vaultenv&lt;/code&gt; (fetching secrets from Hashicorp Vault and providing them via environment variables to a program) and &lt;code&gt;icepeak&lt;/code&gt; (a JSON document store with support for push notifications via websockets).&lt;/p&gt;

&lt;h3&gt;
  
  
  Why did you decide to choose Haskell?
&lt;/h3&gt;

&lt;p&gt;Haskell was first introduced as an experiment rewriting a component that was hitting the limits of what was possible in Python and the existing architecture (the full story is on our &lt;a href="https://www.channable.com/tech/how-we-secretly-introduced-haskell-and-got-away-with-it"&gt;tech blog&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;We needed a language that would complement Python well. A language that would compile to fast code while providing safety rails through its strong type system and still being high productivity. Given that we also already had several people enthusiastic about functional programming, Haskell was the natural choice.&lt;/p&gt;

&lt;p&gt;Since that project turned out to be very successful (and is still in use today – being continually developed since then), Haskell was also chosen for another greenfield project that was started shortly after, our API gateway.&lt;/p&gt;

&lt;p&gt;When I joined Channable, Haskell was thus already in use for these two projects. At the time, we were also running into scaling and operational troubles with our existing feed processing application (written in Scala using Apache Spark), and so Haskell was chosen once more for its replacement. More details about that rewrite can be found &lt;a href="https://www.channable.com/tech/why-we-decided-to-go-for-the-big-rewrite"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Are there any specific qualities of Haskell that made you decide in its favor?
&lt;/h3&gt;

&lt;p&gt;The main selling point is Haskell’s strong type system. It eliminates many types of runtime errors that we regularly see crop up in our Python code base (though it has gotten better since we use types in Python as well – via &lt;code&gt;mypy&lt;/code&gt;). Additionally, it makes refactoring existing code a breeze: one can be sure that almost all required changes are caught by the compiler.&lt;/p&gt;

&lt;p&gt;Another advantage is the focus on immutable (and persistent) data structures, allowing for cleaner designs and better testability and concurrency.&lt;/p&gt;

&lt;p&gt;An underappreciated advantage of Haskell is also its great runtime system. It makes it very easy to add both concurrency and parallelism to your programs using lightweight threads. Something that is usually a lot harder to do in other programming languages if you didn’t design for it from the start.&lt;/p&gt;

&lt;h3&gt;
  
  
  Are there any libraries that you found very useful in the development process and would like to feature?
&lt;/h3&gt;

&lt;p&gt;First of all, there is &lt;code&gt;conduit&lt;/code&gt; which we use for stream processing. In our experience it has been both fast and easy to use. The only downside is that code using it is quite prone to space leaks. Well-typed has a very informative &lt;a href="https://www.well-typed.com/blog/2016/09/sharing-conduit/"&gt;blog post&lt;/a&gt; on that topic.&lt;/p&gt;

&lt;p&gt;Besides that, we use the excellent &lt;code&gt;warp&lt;/code&gt; server for both internal and external HTTP-based interfaces. In some projects, we used it directly, in others through an additional layer like &lt;code&gt;scotty&lt;/code&gt; or &lt;code&gt;servant&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And last but not least, there is &lt;code&gt;ghc-compact&lt;/code&gt;, which has helped us tremendously to get good performance even when working with large datasets. Though it might not really qualify as a library since it’s shipped with GHC and just wraps a feature of the GHC runtime system.&lt;/p&gt;

&lt;h3&gt;
  
  
  What kind of effect system do you use: RIO, mtl, fused-effects, Polysemy, or something else?
&lt;/h3&gt;

&lt;p&gt;Some of the older projects use mtl-style MonadXYZ classes and corresponding deep monad transformer stacks. Those turned out to be quite unwieldy to work with for various reasons.&lt;/p&gt;

&lt;p&gt;Firstly, for M monad (transformer) types in your stack and N classes, you need about N * M instance declarations, which adds a lot of noise to the codebase. Additionally, deep monad stacks hurt performance quite a bit, so whenever we have performance critical code, we just use plain IO.&lt;/p&gt;

&lt;p&gt;A secondary issue is that some monad transformer combinations look tempting at first glance, but turn out to be a bad idea in practice, like the (in)famous “ExceptT over IO”: not only is it incurring a performance penalty due to the repeated packing and unpacking of the inner Either, but it also makes the code more complex instead of simpler, as there are now two failure paths to consider (with different handling functions), since IO can always potentially throw an exception.&lt;/p&gt;

&lt;p&gt;For those reasons, our newer projects usually use some form of &lt;code&gt;ReaderT IO&lt;/code&gt; (or just IO-functions with explicit function arguments for dependencies). Occasionally, we also use free monads in places where there is a well-defined “language” of operations that we might want to mock in tests.&lt;/p&gt;

&lt;h3&gt;
  
  
  Did you run into any downsides of Haskell while developing the project? If so, could you describe those?
&lt;/h3&gt;

&lt;p&gt;One big downside of Haskell that is noticeable in the daily development workflow is the lack of tooling. Fortunately, at least the “IDE” side of it improved quite a bit with the &lt;code&gt;haskell-language-server&lt;/code&gt; project, which was a game-changer in terms of development convenience.&lt;/p&gt;

&lt;p&gt;The remaining areas that are still lacking compared to other languages are debugging (&lt;code&gt;Debug.Trace&lt;/code&gt;-debugging is often the only viable approach) and profiling. The latter probably deserves some explanation as GHC does come with built-in profiling capabilities. Unfortunately, those are very intrusive and sometimes drastically change the performance and allocation behavior of the generated code. External profilers that don’t require special builds (except for debugging info) like &lt;code&gt;perf&lt;/code&gt; don’t work with Haskell code. On the upside, we did have good experiences with the eventlog-based profiling, which has a lower overhead than a full-blown profiling build.&lt;/p&gt;

&lt;p&gt;In terms of the language itself, by far our biggest issue was its GC which is performing really badly when having large heaps (upwards of several gigabytes) without taking precautions like using compact regions (see &lt;a href="https://www.channable.com/tech/lessons-in-managing-haskell-memory"&gt;our blog&lt;/a&gt; for more details). With heaps growing even to the 100+GB region, we also encountered some quadratic runtime algorithms in the memory allocator of the RTS – and even compact regions didn’t help then. We &lt;a href="https://gitlab.haskell.org/ghc/ghc/-/issues/19897"&gt;documented that particular bug&lt;/a&gt; and have since provided a fix for it as well.&lt;/p&gt;

&lt;p&gt;While there are a few tuning parameters, there is nothing that would alleviate these particular problems without requiring invasive code changes.&lt;/p&gt;

&lt;h3&gt;
  
  
  How easy is it to hire Haskell engineers for the team? Do you do any in-house training programs to get non-Haskell engineers up to speed with Haskell?
&lt;/h3&gt;

&lt;p&gt;So far we didn’t have trouble finding Haskell engineers to fill our vacancies. That can probably partially be attributed to the fact that our headquarter is located in Utrecht – since Utrecht University has a strong Haskell-focused track in the Computing Science Master’s programme.&lt;/p&gt;

&lt;p&gt;We have no explicit in-house training program, but we have hired and successfully onboarded people of varying Haskell skill levels – and an important part of the culture at Channable is to grow and learn.&lt;/p&gt;

&lt;h3&gt;
  
  
  As an aside, you also use Nix, which seems like a popular choice for Haskell projects nowadays. How did you decide to use it, and how was your experience using these two technologies together?
&lt;/h3&gt;

&lt;p&gt;Some colleagues were using Nix for their side projects or running NixOS on their personal machines. At the time, we also had some trouble with our existing build and deployment infrastructure and were searching for solutions, and it turned out that Nix fit the bill perfectly.&lt;/p&gt;

&lt;p&gt;We started by using Nix just as a convenient manner to bring various development tools into scope (such as &lt;code&gt;stack&lt;/code&gt;), but not yet using it for building our code (so &lt;code&gt;stack&lt;/code&gt; – while installed via &lt;code&gt;nix&lt;/code&gt; – was not run in Nix-mode yet at that time). That way, we already prevented some of the issues, like having incompatible stack versions installed across developer machines.&lt;/p&gt;

&lt;p&gt;The next step was then to port some of our build pipelines, starting with the Haskell projects. The main advantages were the pre-built Nix cache for Haskell packages (no more rebuilding the entire stackage snapshot with every minor upgrade) and the reproducibility of the builds.&lt;/p&gt;

&lt;p&gt;The full story can be found on our &lt;a href="https://www.channable.com/tech/nix-is-the-ultimate-devops-toolkit"&gt;tech blog&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Your &lt;a href="https://www.channable.com/tech"&gt;tech blog&lt;/a&gt; posts mention languages like the aforementioned Nix and Idris, working with which is definitely on some people’s bucket lists. Is experimenting with technologies common in Channable? If so, what benefits do you see in this?
&lt;/h3&gt;

&lt;p&gt;We have a regular Hackathon day in the development department where people can just try out ideas they have, or investigate new technologies that look interesting. The tool written in Idris is &lt;code&gt;dbcritic&lt;/code&gt; and was the product of one of those days.&lt;/p&gt;

&lt;p&gt;Having this room for experimentation is definitely an important part of the engineering culture at Channable. There are a few things that people came up with during those Hackathons that are now regularly used – either in our production software, as a productivity tool, or as part of the CI pipeline.&lt;/p&gt;

&lt;p&gt;We probably wouldn’t use Idris for any larger project, but since this particular program solves a concrete problem we had and was easy enough to package as it was, we decided to adopt it in our CI workflow.&lt;/p&gt;

&lt;h3&gt;
  
  
  What tips would you give for a new Haskell team starting a project in an area similar to yours?
&lt;/h3&gt;

&lt;p&gt;My first recommendation would be to keep things simple. Haskell provides a lot of language-level complexity at your fingertips (just enable a few language extensions), but one needs to carefully consider if that complexity is worth the cost. Both in terms of syntactic overhead, but also in terms of increasing the burden for onboarding future colleagues&lt;/p&gt;

&lt;p&gt;The other is more specific, but if you plan to work with large amounts of data (that isn’t just plain bytes), be sure to take into account Haskell’s GC from the start. When working with a large heap, there &lt;em&gt;will&lt;/em&gt; be GC troubles. The only mitigation (while still being able to work with regular Haskell data structures) are compact regions. As using those has an impact on the overall architectural and algorithmic design, rewriting an existing program to use them might not be straightforward.&lt;/p&gt;

&lt;h3&gt;
  
  
  Where can people learn more about Channable?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;About what we do on the technical side: &lt;a href="https://www.channable.com/tech/"&gt;https://www.channable.com/tech/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;About the company in general: &lt;a href="https://www.channable.com/"&gt;https://www.channable.com/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;About our open-source projects: &lt;a href="https://github.com/channable/"&gt;https://github.com/channable/&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Hope you enjoyed our interview with Fabian!&lt;/p&gt;

&lt;p&gt;To read more interviews with companies that use Haskell to solve real-world problems, head to our &lt;a href="https://serokell.io/blog/interviews"&gt;interview&lt;/a&gt; section. Also, be sure to follow us on &lt;a href="https://twitter.com/serokell"&gt;Twitter&lt;/a&gt; or subscribe to our mailing list (via form below) to get updates whenever we release new articles.&lt;/p&gt;

</description>
      <category>haskell</category>
    </item>
    <item>
      <title>Functional Futures: Grain with Oscar Spencer</title>
      <dc:creator>Serokell</dc:creator>
      <pubDate>Tue, 21 Jun 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/serokell/functional-futures-grain-with-oscar-spencer-14m7</link>
      <guid>https://dev.to/serokell/functional-futures-grain-with-oscar-spencer-14m7</guid>
      <description>&lt;p&gt;In this month’s episode of Functional Futures, our guest is Oscar Spencer – a co-author of a functional programming language called Grain that compiles to WebAssembly.&lt;/p&gt;

&lt;p&gt;Listen to the episode to learn more about Grain, WebAssembly, and how to sell functional programming to developers.&lt;/p&gt;

&lt;p&gt;You can check out the full episode on our &lt;a href="https://www.youtube.com/watch?v=Fcc5Gr8dKKg"&gt;YouTube channel&lt;/a&gt; or listen to the &lt;a href="https://anchor.fm/functionalfutures/episodes/Grain-with-Oscar-Spencer-e1k83r2"&gt;audio version&lt;/a&gt; on our podcast page.&lt;/p&gt;

&lt;p&gt;Below, you can find some of the highlights of the episode, edited for clarity.&lt;/p&gt;

&lt;h2&gt;
  
  
  Highlights from our conversation with Oscar Spencer
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Learning WASM
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Hello, Oscar, was my introduction fair?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Hello! Yeah, I think your introduction was pretty fair, that’s pretty much me in a nutshell – just sort of sitting around doing WebAssembly all day – all day, every day.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Right, and you’ve been doing it for a while, right? You started Grain a long time ago, back then like it was 2017, right?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Yep, 2017.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; So were you a WASM guru already then and decided that you should make a language, or how did that go?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; No, I wasn’t really a WASM guru, I don’t think too many people were back then other than, you know, the folks at Mozilla. I think it was right when WebAssembly had just got turned on by default in all the major browsers, and I was a huge front-end person back then. And so I got really excited by the idea of: “Hey, wait, can we run languages that aren’t JavaScript in the browser? I absolutely want to give this a shot.”&lt;/p&gt;

&lt;p&gt;At the time, I’d actually just completed a compilers course, and I thought it’d be really interesting if I put something together with a buddy of mine that targeted WebAssembly. And then, you know, we did that – I’ll never forget the shock on our faces when we managed to bind a DOM event from inside of WebAssembly, that was absolutely amazing. I think we both jumped out of our chairs with excitement of: “Hey, we clicked the button, and WebAssembly happened!”&lt;/p&gt;

&lt;p&gt;So that was really exciting, and it’s crazy to think that that was back in 2017. In a way, I feel like I grew up with WebAssembly, so I’ve just been here for the ride all along, learning as I go, and I mean, it’s been great.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; A lot of people these days are basically more or less in the position like you were five years ago while working on Grain. How did you learn the concepts of the WASM virtual machine and how it’s executed? Did you just read the specification like 20 times and then it clicked? Or how was the process of learning for you?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Funny enough, we had a lot of help. The Grain compiler initially targeted x86. I don’t want to call it boring, but for these days it was maybe a little bit boring in that sense. And so we had the official WebAssembly spec online that everyone could read. However, there was an actual reference implementation of WebAssembly written in OCaml.&lt;/p&gt;

&lt;p&gt;That felt like a little bit of a cheat code for us because it didn’t take too much for us to figure it out. All we did was we just downloaded this WASM library from OPAM and then we just changed that as our target. We were like: “Hey, we’re gonna swap out most of these instructions with WebAssembly ones.” Doing stuff like register allocation was super easy because in WebAssembly we have unlimited registers, so it’s actually not too bad to get started, especially if you’re an OCaml nerd like we were and still are. We had a pretty easy time of it. So, yeah, definitely a little bit of a cheat code in the beginning.&lt;/p&gt;

&lt;p&gt;But after that it’s supposed to just be, you know, reading specs, chatting with folks. There’s so many lovely people who are happy to help you understand anything that’s going on in the community. You just gotta reach out and say hi, and folks are more than happy to help you out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; What is kind of the place to go for a beginner to to ask questions about WASM and its peculiarities?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; There is an official &lt;a href="https://discord.com/invite/jwCC7jS"&gt;WebAssembly Discord&lt;/a&gt; that folks can join, and people chat about everything WebAssembly in there, things that you might not even imagine people are doing with WebAssembly – folks are chatting about it in there.&lt;/p&gt;

&lt;p&gt;I think it’s good to join these circles, but also the specific circles for the actual languages and frameworks you want to use. In those circles you can get a lot more specific. Folks are going to have a little bit better answers for “how do I do this exact thing in Rust?” or “how do I do this exact thing in Grain?”.&lt;/p&gt;

&lt;p&gt;And folks are gonna be able to get you really good answers because, like you said, WebAssembly is still pretty new. It’s not easy to figure out exactly, for example, once you’ve managed to produce a WebAssembly module, how do you actually go deploy that and run it in production, right? There are tools out there that can make it easier for you, there are folks who are running WebAssembly in Kubernetes and getting really crazy with it, but the way that you’re gonna find out about these things right now is through that personal chatting with folks, mostly on different discords.&lt;/p&gt;

&lt;p&gt;We are gonna get to the point where we’ve got all the tooling in place and it’s super easy and everything’s well documented, but we’re still not quite there yet as a community. But we’re rapidly getting there.&lt;/p&gt;

&lt;h3&gt;
  
  
  Grain
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Can you tell us a little bit about your vision for Grain? If I had to do an elevator speech for Grain, I would say it happens to be the Golang of WASM. Is that a fair analogy?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Yeah, sort of, in a way. I think my long-term vision for Grain is to be that easy entry point for people into WebAssembly with the very sly plan in the background of letting functional programming take over the future.&lt;/p&gt;

&lt;p&gt;The whole point is to have this language that’s extremely approachable. And, I think, this is a concept that I have really picked up while looking at the React framework, looking at ReasonML, languages like this. You can take some pretty “advanced functional concepts”, but if you present them in a way that folks say, “Hey, actually, yeah, this makes a lot of sense, I’m not getting bugs in my code,” when you’re able to tell those stories about how &lt;a href="http://Messenger.com"&gt;Messenger.com&lt;/a&gt; went from 10 bug reports a day to 10 bug reports a year after switching to ReasonML, when you’re able to tell these stories – that gets people really excited. And so we’re trying to do a lot of that with Grain. We can give you all of this type safety, we can give you all these functional features where you’re going to be able to write really good production code, but it’s not scary, it’s approachable.&lt;/p&gt;

&lt;p&gt;We’re breaking a couple rules in Grain. Like, we have &lt;code&gt;let mut&lt;/code&gt;, we have mutable bindings by default, that probably scares some people, but we want to have these places where folks can come in and really feel like they’re at home, feel like they’re writing a language that they’re super comfortable in, and that they just really feel good about. I mean, along the way it’s going to be teaching them functional concepts and […] just exposing people to these things and getting them excited about it.&lt;/p&gt;

&lt;p&gt;So that’s a lot of where we want to go with Grain – just providing a rock-solid developer experience, just having folks feel really good writing whatever programs they want. Basically being that 90 percent. So 90 percent of the programs you want to write, you can write them in Grain, and the other 10 percent of WebAssembly you need to write, you can write it in Rust. That’s sort of where we’re aiming as far as how high of a level of a language we want to be.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; To clarify one point here: I’ve seen a lot of comparisons between Grain and Elm as well. My personal experience with Elm is that it’s roughly 80-20, but stuff that’s 20 is really borderline impossible. Like, you have to go through such hoops to get that 20 percent of use cases that 80 percent don’t cover, that it almost makes me personally question if I should even go for it in the first place. How do you go about creating escape hatches for people who know what they’re doing and that really need this escape hatch?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; That’s something that we’ve been toying with. We want to make sure folks are able to do things in Grain that we don’t necessarily endorse, and so we have a couple features to do this. One of those, for example, is an attribute you can put on functions called unsafe, and it’s an attribute that allows you to say: “Hey, I’m just going to drop down and write low-level WebAssembly right here, right now.” This is not something that I want 99 percent of users to do, however, we’re going to make sure that it’s possible. For one, it made things a little bit easier for us. The entire runtime for Grain is written in Grain, and we probably wouldn’t have been able to do that without being able to write some bare WebAssembly stuff. But it’s providing escape hatches like this in the language where folks can do things, especially when it comes to, for example, binding to a WebAssembly host. Right now, doing that – it’s some low level code, and that’s not something that I expect every user do, and we’re working on projects like [inaudible] that allow you to automatically generate Grain code to bind to these interfaces, so you don’t have to do that sort of stuff.&lt;/p&gt;

&lt;p&gt;But yeah, we want to make sure that we have these things in Grain so folks can go wherever they want. And I’ll even add on to that. One of the big exciting things about WebAssembly is the &lt;a href="https://github.com/WebAssembly/component-model"&gt;WebAssembly Component Model&lt;/a&gt; where we want to be able to mix languages, we want to be able to pull in components from all over the place.&lt;/p&gt;

&lt;p&gt;So sure, maybe you don’t want to write that cryptography library in Grain, but that’s okay, you can pull in Rust’s amazing performant cryptography library, be really happy with it, and integrate it into your Grain code. Are we there right this second? No, but we can actually get there.&lt;/p&gt;

&lt;p&gt;And I and I’m telling you, if someone came into the Grain discord and said, “Hey, I’m trying to statically link to this Rust binary,” I’d say “Okay, let’s make it happen,” because that’s something that we can actually make happen if folks are asking for it now. But this is definitely where WebAssembly is going in the future, and we’ll have these different ways for you to get that last 10 percent that you might not have wanted to write in Grain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; That’s really cool and very very pleasant to hear! You mentioned bindings to host platforms. As far as I understand these are the kind of capabilities that are provided by the host, for example, the file system would be one such binding or like &lt;code&gt;localStorage&lt;/code&gt; in a browser.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Yeah, exactly. WebAssembly code runs in a sandbox, so it’s completely sealed off walls, with absolutely zero way to speak to the outside world at all. And this is how WebAssembly gets to be secure by default.&lt;/p&gt;

&lt;p&gt;The way that we start adding on new capabilities (because maybe you do want to talk to a file or you do want to talk to the network, or something) is we add on these capabilities back via host functions. There is a set of host functions for common system calls – &lt;a href="https://wasi.dev/"&gt;WASI&lt;/a&gt;, the WebAssembly System Interface – which provides a standard way to interact with all of these different system calls on a system. So we have that, but, additionally, you can have your host provide whatever host functions you want to do all sorts of things.&lt;/p&gt;

&lt;p&gt;For example, there are a couple of game engines where they give you some host functions that say “here is the controller input” or “here is a buffer that you can write to for the graphics”. And that’s super cool, and there’s gonna be all sorts of different hosts providing all kinds of different host functions.&lt;/p&gt;

&lt;p&gt;Even at Suborbital, we want folks to be able to do things like talk to a database very easily, and, of course, we could let you go make a network connection and do all that fun stuff, or we can just give you a function that says “hey, I want to query this thing” and go from there. So that’s what host functions are about. Of course, folks need to be able to bind to those host functions, but they’re very low-level things. If you’ve ever written C bindings into a language, it’s sort of exactly that – you’re writing those sort of bindings to what these host functions look like. Like I said before, we are working a lot on automating a lot of this, so folks don’t have to do it themselves.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I think my long-term vision for Grain is to be that easy entry point for people into WebAssembly with the very sly plan in the background of letting functional programming take over the future.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Grain compiler
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; I briefly looked at the Grain repository and I saw that the compiler was written in the aforementioned ReasonML. You know, I don’t regularly see code written in ReasonML, and especially not one originating from 2017. Can you please talk a little bit about the language of choice first, and second, how do you get ReasonML to actually emit WASM because, as far as I understand, it’s kind of like dual-targeting language, it targets JavaScript and I think it targets x86.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Funny enough, back in 2017, the Grain compiler was just written in pure OCaml. The reason for OCaml is – you know, that ML part stands for “meta language” – it is the perfect language for writing a language. I will take that to my grave, no one can tell me otherwise. Developing the compiler in OCaml has been an absolute dream. If you want to tell me that OCaml is bad for all these other use cases, whatever, but for building a compiler, OCaml is fantastic.&lt;/p&gt;

&lt;p&gt;I’m not exactly sure when it happened, I think it was maybe 2019 or 2020 when we made the cut over to ReasonML and the hilarious reason for that is that there aren’t a lot of OCaml developers out there. They definitely exist, we’re here, we’re a community, but there’s not that many of them. And at this point, ReasonML had gotten more popular, probably quite a bit more popular than OCaml. It was a pretty easy switch – we could just run a tool to convert all the OCaml into ReasonML, and all of a sudden, we had a full community of people who might be interested in coming and contributing to the compiler, you know, open source is hard and we need as much help as we can get. And that’s sort of the origins of why we are in ReasonML. It’s just to have the still glorious OCaml programming to write our language.&lt;/p&gt;

&lt;p&gt;To your other point of how do we get ReasonML to emit WebAssembly – it’s not actually the ReasonML compiler doing that. The Grain compiler just ends up being this regular binary, but the actual WebAssembly emitting happens via a project called &lt;a href="https://github.com/WebAssembly/binaryen"&gt;Binaryen&lt;/a&gt;. Binaryen is a project that essentially gives you an IR to target just with WebAssembly instructions, and then it can serialize and deserialize modules for you. It’s very convenient and, of course, on top of that, it has loads and loads of optimizations.&lt;/p&gt;

&lt;p&gt;We could have used full LLVM for our back end, you know, Binaryen is the project that is behind LLVM as well, but we didn’t need that. We really knew that “Hey, we’re targeting WebAssembly, let’s just sort of skip all of the LLVM bits and let’s just go straight to Binaryen,” because we still get all the same WebAssembly optimizations that we’d get if we were going through LLVM. Not the LLVM IR ones – that can be pretty powerful, but we can handle that, that’s something that we can take care of ourselves.&lt;/p&gt;

&lt;p&gt;But yeah, we wrote some OCaml bindings to Binaryen, and that’s what we use to generate WebAssembly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; How do you make sure that these optimizations kind of make sense for your runtime, and did you need to make any adjustments in the process of using Binaryen?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Just to clarify, we do have a full suite of optimizations as a part of the Grain compiler that we do run. You can sort of think of these optimizations as enabling Binaryen to do more optimizing. So it’s mostly saying: “Okay, we might have a bit of code that at the WebAssembly level Binaryen wouldn’t necessarily understand how to optimize, but it’s something that we totally understand how to optimize, and we can take care of that.”&lt;/p&gt;

&lt;p&gt;So we have a bunch of our own passes that we run, and then after that, we additionally can have those Binaryen optimizations. It’s a lot of sort of adapting our code to make sure we’re putting out WebAssembly modules that are easily optimizable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; From what I know about WASM so far is that WASM itself does not define a runtime. It’s up to the users of WASM spec to figure out how they actually want to run this bytecode. So, and this is where for me it gets kind of intellectually tricky to figure out, what do you mean when you say runtime?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Yeah, it is a tricky one. When I say runtime in Grain, I’m specifically referring to two things. The first thing is memory allocation and garbage collection – how do we actually manage all of this memory and everything we’re doing with all these objects that we’re allocating. That’s the first big piece. And that’s incredibly important.&lt;/p&gt;

&lt;p&gt;There is a whole WebAssembly proposal for garbage collection that’s in the works, which we are incredibly excited for. And I think it is going to be a major piece in getting modules across languages to link together. That’s the number one concern you have right now: you can have two website modules that do something, but to make them talk to each other, they’re just gonna be writing over each other’s memory.&lt;/p&gt;

&lt;p&gt;The second bit for the Grain runtime is all of the support infrastructure for things: like the &lt;code&gt;print&lt;/code&gt; function for things, like the &lt;code&gt;toString&lt;/code&gt; function, stuff like that. Sort of like the language support stuff that you expect to exist in the language, but that code has to actually exist somewhere, it’s not just given to us for free.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; In terms of Grain, I understand that you’ve made runtime yourself. Can you talk a little bit about its properties: is it strict, is it lazy, what’s your garbage collection collection strategy, etc.?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; So, one thing about WebAssembly is – some people feel that it’s kind of annoying, other people feel that it’s fine – the way you write WebAssembly is as though it’s running on a stack machine. So you push values onto the stack, you pop values off the stack, you have a good time. That’s all fine and dandy. But one of the things that WebAssembly does not allow you to do is inspect your stack. So there isn’t really a way to just see what values are in the stack, what values are live, so can I actually you know walk my stack and do some garbage collection, that’s not something you can do with WebAssembly today.&lt;/p&gt;

&lt;p&gt;The way folks have gotten around this is they’ve implemented their own stack and they just have the actual website code manipulate the stack that’s in memory. That’s one way to do it. For us, we chose to use the WebAssembly stack as intended, and so that gets rid of a whole class of garbage collection that we could potentially do. So instead we do reference counting garbage collection. We just keep track of how many references you have to this thing, and if it goes dead, then we reclaim that memory.&lt;/p&gt;

&lt;p&gt;That’s really all that happens there, it’s fairly simple. But it’s still a garbage collector, which means it is a pain to maintain, and so we’re always looking up to the WebAssembly spec gods and asking “please deliver sgc”. We will be so grateful when we no longer have to maintain this. Nothing hurts my soul more than a GC bug and just the hours and hours lost to debugging.&lt;/p&gt;

&lt;p&gt;In terms of language properties, we’re fairly strict, we evaluate things when you write it, it’s evaluated there, you don’t have to worry about if it is going to be lazy, is this happening later. Which, I think, might come as a disappointment to some people that might want to see lazy evaluation everywhere, but yeah, no, we’re pretty strict.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The reason for OCaml is – you know, that ML part stands for “meta language” – it is the perfect language for writing a language. I will take that to my grave, no one can tell me otherwise. Developing the compiler in OCaml has been an absolute dream. If you want to tell me that OCaml is bad for all these other use cases, whatever, but for building a compiler, OCaml is fantastic.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Keeping up with WASM spec
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; This actually brings me to the following question. Throughout this interview, you say a lot of phrases like “as of today, WASM has this property”. How do you cope with changes in the spec, because I assume that you want to be on the forefront at all times?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; I think that’s one of our biggest challenges right now. There are some runtimes that we support and that we want to support that are maybe a little bit behind the times in keeping their WebAssembly internal engine up to date to actually be able to run some of this stuff.&lt;/p&gt;

&lt;p&gt;And that’s a problem because we want to continue moving fast, we want to be using all the latest features and whatnot. So we have a handful of compiler flags to deal with this that turn off specific classes of instructions. For example, we have a flag that’s “no bulk memory”. It’s like hey, just don’t use bulk memory instructions. and go get some polyfills of these things. Which is kind of a little sad. We do want to be on the forefront of things.&lt;/p&gt;

&lt;p&gt;I will say, a lot of folks are pretty good at updating their runtimes. We probably will end up having just more flags to turn features on and off, but come the end of the year, I think we might get a little more strict, I might start just dropping old WebAssembly features. Because, yeah, WebAssembly is rapidly evolving, we’re seeing proposals land, things are happening.&lt;/p&gt;

&lt;p&gt;I think a really big one is tail calls, for example. We waited a long time for WebAssembly to have support for tail calls, and now we do. And if anyone ever opens an issue on Grain saying: “Hey, I wrote a tail-recursive function but it blew the stack,” I will not be happy to say the least, because this is a feature that exists in WebAssembly but not all runtimes support it, and so, by default we don’t have that flag turned on. And you do have to know to turn on that flag in certain runtimes.&lt;/p&gt;

&lt;p&gt;So yeah, I think it is kind of just going to come to the point where we’re just not going to support old features, we’re going to be expecting folks – you know, proposals that were marked finished a year ago, I think we can safely say “Hey, yeah, you need to go upgrade your engines if you want to continue using the language.”&lt;/p&gt;

&lt;p&gt;But, honestly, I think some of the old versions of Grain are pretty good too, it’s like they might be stuck on one version for a little while, but I think that’s okay.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; In terms of you personally like or your team, rather: you mentioned that there are features that are getting implemented for WASM, but are there breaking changes, do you need to do a lot of refactoring to accommodate those new features or breaking changes?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; I have to say, the WebAssembly team did an amazing job at making WebAssembly be in a position where it didn’t have to have a set of breaking changes. The binary format – the major version has not changed since launch, we’re still on version one of WebAssembly, so there’s no sort of random bytes that are going to just straight up crash the runtime other than new instructions that have been introduced.&lt;/p&gt;

&lt;p&gt;And so some runtimes, when they’re trying to load a module, might just say “oh, I don’t recognize that opcode, and I’m gonna die.” And you know, that’s okay, it happens. But in terms of all the tooling to prepare the WebAssembly, you know, all that stuff continues to work.&lt;/p&gt;

&lt;p&gt;So we haven’t had too much trouble in terms of breaking changes that’s like “Ugh, here they go again, breaking stuff,” it’s actually been quite pleasant. I think there’s a proposal right now for WebAssembly feature detection, if I’m not mistaken, to just make sure that “Hey, I know that this runtime is going to support these things,” and you can compile different versions of your modules depending on what features are available. That’ll be pretty nice when we can do stuff like that. As long as we’re able to support a couple flags that turn features on and off, then you know we’ll be okay.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I have to say, the WebAssembly team did an amazing job at making WebAssembly be in a position where it didn’t have to have a set of breaking changes. The binary format – the major version has not changed since launch, we’re still on version one of WebAssembly, so there’s no sort of random bytes that are going to just straight up crash the runtime other than new instructions that have been introduced.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Refactoring Grain
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; In terms of your early work, if we go a little bit back in history, did you hit the nail on the head from the first attempt?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Oh, absolutely not. [laughs]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; So, then, what was your experience with refactoring the compiler code or bits of runtime that you write, etc.?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; That experience there was sort of the journey of going from a toy language to like a real, actual, serious language. Because, yeah, in the beginning the code base was kind of just the result of a school project, and I don’t know about you, but I’m not really trying to ship code from a school project to production, right? So it was a lot of refactoring, rebuilding a lot of pieces from the ground up to make them production class.&lt;/p&gt;

&lt;p&gt;Ever since then, I’ve grown a ton as an engineer, other folks on the team have grown a ton as engineers in general, but also compiler engineers, which is understanding more concepts and things that we should be doing right as we’re developing.&lt;/p&gt;

&lt;p&gt;I think a lot of it was refactoring code that way, refactoring a lot of ideas we had in the language of just how we want to reason about things, really hitting, “Okay, where exactly do we want the language to go?” Because in the beginning, we didn’t necessarily know, we were just kind of having fun, and we saw an opportunity – if we put in a little bit of effort, a little bit of elbow grease, we can actually build something that people are gonna love to use and people will actually want to use.&lt;/p&gt;

&lt;p&gt;Because, fundamentally, a lot of the languages we have for WebAssembly right now are just super low-level, and that’s fine for some folks writing WebAssembly, they can deal with that. But the vast majority of people probably want to write a bunch of high-level code. And so it was a lot of how can we mold Grain to fit that bill more, how can we get Grain to a place where it’s super approachable for people to write code and run it, and where it runs reasonably fast. Is it gonna be as fast as a very serious Rust module? Maybe no, but most people probably don’t need that, given how fast WebAssembly is.&lt;/p&gt;

&lt;p&gt;So it’s a lot of just reworking a lot of the ideas of the language, and, of course, there’s a lot of code with that too. But yeah, the road to 1.0 is paved with many, many features and things we want to get done. A huge one that folks have been asking for is macros. We want to have macros in the language. That’s a big, hairy feature that hopefully we’ll get a chance to start working on soon.&lt;/p&gt;

&lt;h3&gt;
  
  
  OCaml / ReasonML
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Does OCaml or ReasonML, now, help you formulate your ideas better, or do you do whiteboard brainstorming and then kind of shove your idea into the type system? How does it go?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; It’s definitely a lot of both. But I have to say, my thinking has been so shaped by OCaml, it’s kind of ridiculous. I think the major thing that OCaml has done for me is it really makes me think about data first. Which is very different to a lot of other languages, where other times you’re maybe thinking about a model, you might be thinking about an object and things you can do to that object, but the thing that I love about OCaml (and this has definitely started making its way into Grain) is thinking about the data first.&lt;/p&gt;

&lt;p&gt;That means you’re thinking about the types first. The very first thing you’re thinking about is, okay, how am I gonna model this data, that’s like the very first step, and then we start thinking about transforming that data and moving that data around, and doing things to it.&lt;/p&gt;

&lt;p&gt;I think that’s a lot of how the Grain experience works out as well. There’s this particular goal that we want to achieve, it’s not “Hey, let’s just start writing code and hopefully we make it there.” No, it’s, like, “This is what we’re gonna achieve,” and it sort of builds itself out from there.&lt;/p&gt;

&lt;p&gt;I remember way back in school we had this thing called the design recipe, which essentially was thinking about your data, thinking about your transforms, and even thinking about your tests up front. […] And that’s a lot of what we do today, it’s really thinking about that end case first of what is the real problem that we’re trying to solve, modeling it from there, and then the very last step is “Okay, now we’ll implement it.”&lt;/p&gt;

&lt;p&gt;I definitely have been influenced a lot by this sort of idea.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; That’s really cool, and it’s great that these sorts of approaches also make their way into frontend as well with types these days.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Absolutely.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; For refactoring, I think type systems have obvious benefits. To name one, as you change a thing in one place, and then the compiler tells you what you missed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; Oh yeah, that’s the entire development process in the Grain compiler. It’s really funny, especially when I explain the Grain compiler code base to folks, I’m always telling them that it’s actually really simple, we’re literally just moving from IR to IR. So, essentially, you just go to the compilation step at the very end, and you make a code change and say, okay, I want this data to output this WebAssembly code. And then the compiler graciously guides you all the way back through every phase of the compiler, making sure you’re implementing, how to lex this, how to parse this, how to go to abstract normal form, how do we do all these different things.&lt;/p&gt;

&lt;p&gt;It’s really cool and that is the development experience I want everyone to have: make one small change, and then don’t try and guess, let’s not have engineers walking around being like: “Oh, should I change this thing in that file?” No, let’s have a tool that can tell me how to do it. That’s huge.&lt;/p&gt;

&lt;p&gt;And it’s funny because we have some of these features in Grain that people think are revolutionary. Like, with pattern matching, you forget a case and the compiler tells you “hey, you missed an edge case, and, by the way, here’s an example of the code that you missed.” People, who’ve never seen this before – it blows their mind – they’re like “whoa, that’s insane” and like “this is really how you avoid bugs”, and you’re like “yeah, it’s crazy, this has existed forever and it’s just not in the mainstream languages, but yeah, it’s here and you can avoid all sorts of classes of bugs.”&lt;/p&gt;

&lt;p&gt;That’s one of my favorite things about languages like OCaml – the fact that you write some code, and if it compiles, it’s correct. It may not do what you wanted it to do, but it’s definitely correct and is what you wrote. And that’s amazing to me and I think that’s kind of lovely, right, as you’re following all these compiler errors, usually, by the time you actually get the program to actually compile, it usually works “on the first try”. It’s not really your first try because you ran the compiler command like 12 times to get to this point, but by the time you get to that point, you’re usually done, and you can breathe a sigh of relief and say “ah I implemented this feature”, and submit your PR.&lt;/p&gt;

&lt;p&gt;And because you had to use these beautiful types and think about things, the PR comments are so lovely. It’s more just ideas of, like “oh, we could express this type this way” or “we can think about this this other way”, it’s none of the low-level – how I hated those discussions in JavaScript, just like: “Oh well, actually, with this function you got this edge case where when it’s null instead of zero… “. I hate those sorts of things, and so removing that entire class of discussions is just fantastic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; Do you have any problem convincing people that that’s good? The argument I hear particularly a lot is that untyped languages or uni-typed languages are like languages for rapid prototyping, and you can’t move as fast with the ML-like languages or Rust, or something like that. Do you have this sort of pushback, and if yes, then how do you kind of respond to it?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; I think a lot and I preach this you know to the team all the time: the biggest thing with Grain is really how we tell our story. It’s all about how we talk about the language. Which is why you don’t see me going around talking about how you do this really complex functional thing in Grain, you never hear me say those sorts of things. It’s all about “here’s how I can develop faster”, “here’s how I can build better programs”. And I think when you come with that mindset, a lot of people are a lot more open to it.&lt;/p&gt;

&lt;p&gt;Because when you tell folks that they have to write your programs a certain way, they’re immediately going to get really defensive and say “oh, but I don’t want to do it like that”. Versus, for example, on the types issue – I think this is an amazing one – in Grain, all types are inferred. So I can tell someone – especially people like JavaScript or TypeScript developers, who are like “oh, I really love TypeScript, but I got to write all these types” – well, actually, imagine that the compiler just knew exactly what you were thinking when you wrote the code.&lt;/p&gt;

&lt;p&gt;Like, when you wrote that plus sign on that variable, the compiler knew that that thing is a number, which means this argument is a number, which means, in all these functions where you use this, this thing is a number, and the compiler is gonna make sure you’re being consistent about it.&lt;/p&gt;

&lt;p&gt;And then someone might hit you with: “Oh, but the types aren’t in the code, I can’t see the types, so how do I know what types these things are?” But these days, having amazing editor support is huge. And with that, not only do we have like in VSCode, you’ve got your code lenses where every single statement is telling you: “hey, this is the type of this thing”, you can hover over literally any value, and it’s going to tell you what it is.&lt;/p&gt;

&lt;p&gt;You alleviate a lot of these concerns and you tell people, hey, you can write this exact same code, you don’t even have to think about the types, you can just write the code like you might in Python. You just write the code, you don’t think about it, you run it, and you’re done. The difference is the compiler will let you know, in our case, that, hey, you did something a little bit wrong, and just make sure you clarify this or fix this thing, so that way it’s obvious not only to other people reading the code, but also to you and the compiler.&lt;/p&gt;

&lt;p&gt;And then it’s actually pretty easy to get people on board with this. When you tell them that it’s just super magical and it’s gonna make sure you never make a mistake, they’re really excited by that. When you tell them that you can eliminate null pointer exceptions from your code entirely, it’s something you never need to worry about, they get excited by that.&lt;/p&gt;

&lt;p&gt;So I think it’s all about how we talk about these things and how we get people thinking about them. Because, yeah, then you’re gonna get less pushback. And I think a lot of people, as they’ve come to Grain, they’ve sort of seen that, like, “Oh, yeah, this is fine”, like, “I can write this code, I feel really comfortable, I can use this library, it’s not a huge deal”. And then, of course, the language slowly, sneakily starts adding more functional concepts on you, but that’s okay, you’re with open arms, you’re accepting how good it feels to write your programs and how confident you feel about your programs, and that they’re doing the right thing.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It’s really cool and that is the development experience I want everyone to have: make one small change, and then don’t try and guess, let’s not have engineers walking around being like: “Oh, should I change this thing in that file?” No, let’s have a tool that can tell me how to do it. That’s huge.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Questions from the audience
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; All right, we have a spicy one. What do you think is the best entry point right now for functional programmers to start working with WASM? Should I just learn Rust?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; What a spicy one. Okay, so there’s a couple of different ways you can look at this. Rust has enough functional features, I think, for your average functional person to be pretty happy. You got the strong borrow checker, it’s going to be telling you how to live your life, you’ve got pattern matching, all sorts of things, so you totally can learn Rust if you are just trying to do some functional programming.&lt;/p&gt;

&lt;p&gt;I think it really depends on the level at which you want to write the code. If you want to write super-duper low-level code, yeah, go ahead and pick up Rust, but if you’re looking for something a bit easier, a bit friendlier, yeah, I think it’s going to be pick up Grain.&lt;/p&gt;

&lt;p&gt;In terms of functional programming languages, right now those are going to be your really good options. However, there is a Haskell WebAssembly compiler called &lt;a href="https://github.com/tweag/asterius"&gt;Asterius&lt;/a&gt;, and so if you specifically are a Haskell person and you want Haskell, you can check out that project as well, and you’ll probably be pretty happy because it’s exactly Haskell.&lt;/p&gt;

&lt;p&gt;But yeah, I’m not going to tell people to not write Rust. Rust is an amazing language, it’s a fantastic freaking language, and even at work, when I get to write it, I’m pretty excited. But at the end of the day, it is pretty low level. Grain is like that just higher-level Rust friend. I thought someone on Twitter described Grain as being a child of JavaScript and Rust. I kind of agree with that, and I think that’s how a lot of people can think about it too in terms of, you know, getting into something functional, having enough of the features that you want.&lt;/p&gt;

&lt;p&gt;Some people just get a result type and they’re happy, that’s all they care about, but, like, there’s different levels to it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jonn:&lt;/strong&gt; I think we have one last question. “Oscar said that WebAssembly is used like 80 percent serverside. It’s kind of surprising. Could we get a brief elevator pitch for server side WebAssembly?”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oscar:&lt;/strong&gt; [laughs] Oh, you shouldn’t have asked me that. Yeah, so there’s so much you can do with WebAssembly on the server. So I think that thing we were talking about earlier, about WebAssembly being that write-once-run-anywhere language. Not to completely upset the JVM, but that’s sort of, in a way, what it’s doing right now.&lt;/p&gt;

&lt;p&gt;There is a WebAssembly runtime called &lt;a href="https://github.com/bytecodealliance/wasm-micro-runtime"&gt;WAMR&lt;/a&gt; – the WebAssembly Micro Runtime – that thing runs on literally anything. If you want to run WebAssembly on a Nintendo DS, you totally can, it’s like that level. And so you can actually get your WebAssembly code into all these places.&lt;/p&gt;

&lt;p&gt;So, with WebAssembly’s sandboxing capabilities and other things like that, all of a sudden a use case that we couldn’t really have before suddenly became known. You can run arbitrary code from people you don’t know safely, and that is kind of insane. That opens up a ton of opportunities.&lt;/p&gt;

&lt;p&gt;So what we do at Suborbital is we extend your SaaS applications, whatever kind of application you have, with this ability for your users to write functions that do things in your app. And previously that’s something that maybe you had to run some custom Docker container solution for, which was still probably a little bit unsafe, but now we can actually completely lock down that sandbox and say: “No, you are allowed to do this thing and this thing only, that’s it.”&lt;/p&gt;

&lt;p&gt;Being able to do that is actually kind of huge. There’s a lot of use cases like this, and then even going into replacing Docker containers of: “Hey, actually we don’t need these big hefty containers to do something. If I can have a WebAssembly module that does this one task, I can then go and link all these modules together and do all this work. I’m all set.”&lt;/p&gt;

&lt;p&gt;And that’s how we end up having a lot of WebAssembly happen on the server. And even going to edge computing as well. It’s like hey, how do I actually push compute out to my users? Shipping massive binaries and containers and deploying them all around the world is really cumbersome, but when I have a WebAssembly module that’s 100k, it’s actually very easy for me to be like “Okay, actually have this one module on a server in India and run it.” That’s actually like something that’s much easier to consider. It’s actually very serious. And I think that’s what makes us really excited about the capabilities of WebAssembly.&lt;/p&gt;

&lt;p&gt;Like, yeah, WebAssembly will be popular in the browser, don’t get me wrong, we are going to get there. I think the thing a lot of folks forget right now is that, fundamentally, JavaScript is kind of a good language. Even if it’s not what people want it to be, it has done extraordinary things and people have done extraordinary things with JavaScript. JavaScript’s really fast. Some people will write their program in Rust, be like: “I’m gonna write this thing in Rust and deploy in the browser.” And they find out that it’s not that much faster than the JavaScript version.&lt;/p&gt;

&lt;p&gt;And it’s because JavaScript engines are crazy, they can JIT code faster than you can believe. It’s really, really impressive. So yeah, just outside the browser, running in tiny places, running on servers at the edge – there are loads and loads of applications that we’re seeing for WebAssembly. I still dream of the day that some Grain code is running on a light bulb somewhere. I imagine that, you know, we will definitely get there.&lt;/p&gt;




&lt;p&gt;Big thanks to Oscar for being a guest on Functional Futures! 🙏&lt;/p&gt;

&lt;p&gt;To hear more from him, you can follow &lt;a href="https://twitter.com/oscar_spen"&gt;him&lt;/a&gt; or &lt;a href="https://twitter.com/grain_lang"&gt;the Grain language&lt;/a&gt; on Twitter. Additionally, you can check out Grain on &lt;a href="https://github.com/grain-lang/grain"&gt;GitHub&lt;/a&gt; or join their &lt;a href="https://discord.gg/fhn4n8FrxG"&gt;discord&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you want to hear more from us, be sure to subscribe to the Functional Futures podcast on your favorite podcast platform. 😉&lt;/p&gt;

</description>
      <category>webassembly</category>
      <category>functional</category>
      <category>rust</category>
      <category>ocaml</category>
    </item>
  </channel>
</rss>
