_______ __ _______ ___ .___ ___.
/ _____|| | | ____| / \ | \/ |
| | __ | | | |__ / ^ \ | \ / |
| | |_ | | | | __| / /_\ \ | |\/| |
| |__| | | `----.| |____ / _____ \ | | | |
\______| |_______||_______/__/ \__\ |__| |__|
___
| __|__ _ _
| _/ _ \ '_|
|_|\___/_|
![]()
_____ _ _
|_ _| _ _ __ ___ ___ __ _ _(_)_ __| |_
| || || | '_ \/ -_|_-</ _| '_| | '_ \ _|
|_| \_, | .__/\___/__/\__|_| |_| .__/\__|
|__/|_| |_|
___ _
| \ _____ _____| |___ _ __ ___ _ _ ___
| |) / -_) V / -_) / _ \ '_ \/ -_) '_(_-<
|___/\___|\_/\___|_\___/ .__/\___|_| /__/
|_|
1 / 23 Introduction ██ Who even is this guy? • Software Engineer @iHeart Here is me with me cat, Fritzy
• Keyboard and ergonomics enthusiast =3
• Die hard terminal fanboy • Loves typesystems and statically typed![]()
languages (Yes... Even Typescript) 2 / 23 What is Gleam? From gleam.run (https://gleam.run/):
▍ Gleam is a friendly language for building type-safe systems that scale!
██ Power of Functional Programming ██ Flexible Runtime
Gleam is a purely functional language. You can compile Gleam for one of two
Immutable data, powerful type system, targets:
simple syntax combine to give a developer experience that sparks joy. • Erlang
◦ Leveraging the power of the BEAM ██ Batteries Included VM, the Erlang target can make
use of the Open Telephony
Gleam comes with many great built in tools Protocol (or OTP) to handle
to handle all stages of development. massivly concurrent systems that
fail gracefully. • Language Server • Javascript
• Formatter ◦ For when you want to run your
• Editor Integrations Gleam code inside a browser, or
• Package Manager even interop with JS/TS packages.
The Gleam compiler will even ██ Helpful Error Messages generate Typescript type
definitions for your code. The Gleam compiler aims to assist you with any errors. Gone are the days of the cryptic 10 page long Typescript errors. 3 / 23
Functional Programming 101 ██ Declarative Design ██ Immutable Data
Functional languages are declarative. They Bindings in functional languages are
aim to describe what should happen, not immutable. This is just a fancy way of
necisarrily how that happens[1]. saying their data cannot change.
██ Composition and Higher Order Functions ██ Pure Functions
In a functional language, functions can Functions cannot have side effects[2].
take other functions as parameters. As Meaning for any given input a function
such, your logic is a series of will always return the same output.
compositions of functions, rather than lists of instructions. 1. There is definitely overlap here, especially in multi-paradigm languages, such as
Typescript. 2. Modern functional programs have mechanisms to interact with side effects but that's a little out of scope here. 4 / 23 Modules Gleam code is split into modules. Each module is comprised of functions, types, constants,
etc. Each module relates to a specific file in the src directory of a gleam project. For
instance, let's say you have file called world.gleam inside of a directory called hello/ in
your src directory.
When writing definitions you can use the
pub keyword to specify what you want to be // Will be available outside of this
available in other modules. Definitions module
not prefixed with pub are only available pub fn my_function() {
from within that module. todo
}
This would be similar to the following
Typescript // Only available within this module
fn module_function() {
todo
export function my_function() { }
//...
}
function module_function() {
//...
}
5 / 23 Imports To import a module you would use the import keyword inside of another module.
Gleam Typescript
import hello/world import world from "hello/world"
You can also alias your imports using the as keyword if you want to use a different name.
Gleam Typescript
import hello/world as wrld import wrld from "hello/world"
Alternatively you can import specific parts of a module using unqualified imports using the
.{name} syntax.
Gleam Typescript
import hello/world.{my_function} import {my_function} from "hello/world"
6 / 23
Values and Assignments In Gleam the concept of variables doesn't really exist, as values are immutable. However,
you can still assign values to identifiers for easy reuse within your functions: let a = 4
Identifiers in Gleam are written using snake_case. So where in Typescript it is entirely up
to the developers (And people seem to generally prefer camelCase or PascalCase), this name
convention is enforced by the Gleam compiler.
// Invalid, will get a compiler error
let helloWorld = "Hello, World!"
// Correct
let hello_world = "Hello, World!"
Like Typescript, type annotations are also optional in Gleam:
let a = "a"
// is the same as
let a: String = "a"
7 / 23 Functions Functions are the core of Gleam programs. You use the fn keyword to define a function in
Gleam. Unlike in Typescript, type annotations on function parameters are optional in Gleam.
This is because the type system is able to look at how the parameters are used to infer
their types. However, it is still considered good practice to include type parameters on functions. You use the -> syntax to specify a return type:
fn double(a: Int) -> Int {
a * 2
}
// Is the same as
fn double(a) {
a * 2
}
Another thing to notice is that Gleam uses implicit returns. Whatever the last expression in
a block is will be returned. Gleam also has anonymous functions. These are very helpful when you are passing a function
into another function as a value: higher_order_function(fn(x) {x + 1})
8 / 23 Pipelines and Function Captures One of the most powerful features of functional languages is the ability to create pipelines
of functions, where the output of the previous function becomes the input for the next. Gleam uses the |> operator for this. For example, if we wanted to create a pipeline that
used a double function into a sqrt function:
let doubled_sqrt = double(4) |> sqrt
// The same as sqrt(double(4))
When you combine this with function captures which allow you to take a function, give it
some arguments, and get back another function that takes a subset of arguments that you can call later. For instance, let's say we had a pow(num, power) function that raises a number
to a power. We could use a function capture to turn that into a cube function to reuse
later: let cube = pow(_, 3)
let two_cubed = cube(2) // Same as pow(2, 3)
let five_cubed = cube(5) // Same as pow(5, 3)
9 / 23 Flow Control Handling branching conditions is vital for software. In Typescript you would use features like if/else or switch statements. In Gleam you get a supercharged version of switch
statements called Pattern Matching. You use the case keyword to create a pattern match, and
inside you must handle all possible branches. fn is_a_or_z(str: String) -> Bool {
case str {
"a" | "z" -> True
_ -> False
}
}
In typescript this might look something like: function is_a_or_z(str: string): boolean {
if (str === "a" || str === "z") {
return true;
}
return false;
}
10 / 23 Recursion Gleam also doesn't include loops as there is no way to modify values to handle looping
conditions. As such we use recursion. This is simply a functional calling itself until a
base case is met. For instance if we wanted to loop through all the numbers from 0-5 and
print them in Typescript you might do: function printTilFive() {
for(let i = 0; i <= 5; i++) {
console.log(i)
}
}
In Gleam you would need to use recursion for this:
fn print_til_five(val: Int) -> Nil {
case val {
val if val <= 5 && val >= 0 -> {
echo val
print_til_five(val + 1)
}
_ -> Nil
}
}
11 / 23
Simple Types Gleam ships with a number of "simple" types. These include: • String
• Int
• Float
• Bool
This is pretty similar to Typescript, except that instead of a unified number type, our
numbers are split into the Int and Float types. This can be simplified down to whole numbers
vs rational numbers. Each of these primitive types also has their own module included in the standard library (or
stdlib). These give you all of the utility functions that might exist on the prototype for
the value, like in Typescript. import gleam/string let str = "the quick brown fox jumped
let str = "the quick brown fox jumped over the lazy dog"
over the lazy dog" let words = str.split(" ")
let words = str |> string.split(" ")
12 / 23 Type parameters --> Just like in Typescript, Gleam supports type parameters, aka generics. They are
specified using () after a type that accepts generics.
██ Typescript ▓▓▓ Gleam
type MyList<T> = T[] type MyList(T) = List(T)
Unlike in Typescript, the Gleam compiler is smart enough to know when a type in a function declaration is a type parameter without any special syntax ██ Typescript ▓▓▓ Gleam
function generic<T>(t: T) { fn generic(t: T) {
//... //...
} }
13 / 23 List Type Lists are basically Typescript arrays. They use a very similar syntax as well. However, in Gleam all elements of the list must be the same type and you cannot index into a List type
directly (since they are implemented with linked lists). ██ Typescript ▓▓▓ Gleam
let arr = ["a", "b", "c"] let arr = ["a", "b", "c"]
Due to Gleam's declarative nature, some things you may be used to with arrays aren't really possible, or aren't quite as straightforward. For instance, indexing into a List in Gleam
runs in O(n) time, because it has to traverse the linked list.
Another example is appending to the end of a list. This would require a full traversal of
the List, so it is recommended to prepend to the beginning of the list using the [item,
..list] syntax.
14 / 23 Tuple Type Tuples work similarly to tuples in Typescript, but they are their own data type in Gleam. In Typescript they are implemented using arrays. The Typescript compiler doesn't infer tuples very well (With the exception of using the const type assertion).
You can use #(...) to instantiate a tuple in Gleam. You can also destructure the contents of
a tuple similar to in Typescript. ██ Typescript ▓▓▓ Gleam
// type: string[] let tup = #("a", "b", "c")
let notTup = ["a", "b", "c"] // Destructure any number of
// type: [string, string, string] tuple members
let tup: [string, string, string] = ["a", "b", let #(a, _, c) = tup;
"c"];
// type: ["a", "b", "c"]
let constTup = ["a", "b", "c"] as const;
// Destructure any number of tuple members
let [a, _, c] = tup;
15 / 23 Dict Type Dicts (short for dictionary) are similar to objects, or more aptly the ES6 Map. They are a
hashmap of key:value pairs. Unlike in Typescript though, all the types in the Dict need to be the same type. Since Gleam uses {} to denote blocks of expressions, you can't use them to
instantiate a Dict.
██ Typescript ▓▓▓ Gleam
// type: {a: string; b: string} import gleam/dict
let obj = { let obj = dict.new()
"a": "letter a", |> dict.insert("a", "letter a")
"b": "letter b" |> dict.insert("b", "letter b")
}
// type Map<string, string>
let map = new Map(obj)
NOTE: Unlike the List or Tuple type, you need to import the Dict type from the stdlib to use
it. 16 / 23 Custom Types Custom types in Gleam look similar to enums in Typescript. However, the variants of the type
can also include additional fields, similar to properties on an object. This is especially nice when you're representing tagged unions. Lets say we have a Message type.
██ Typescript ▓▓▓ Gleam
enum MessageType { type Message {
Incoming Incoming(
Outgoing message: String,
} from: String
type Message = { ),
messageType: MessageType.Incoming; Outgoing(
from: string; message: String,
message: string; to: String
} | { )
messageType: MessageType.Outgoing; }
to: string;
message: string;
}
17 / 23 Option Type There is not really a concept of null or undefined in Gleam. So unlike in Typescript where
if you had an optional item you might use a type such as: let optionalString: string | undefined;
In Gleam you would use the Option type. This type has two variants:
▓▓▓ Gleam ██ Typescript
type Option(T) { type Option<T> = {
Some(T) _tag: "some";
None value: T;
} } | { _tag: "none" }
NOTE: You need to import the Option type from the stdlib to use it.
18 / 23 Result Type Handling errors is pretty different than many non-functional languages. Errors in Gleam are treated as values, not exceptions. This makes it much easier to handle them in a predictable
manner. Where in Typescript you may use the throw keyword, such as
() => {
throw new Error("Oh no!")
}
While this is pretty simple the big downside is that you lose type safety. With Gleam you would use the Result type.
▓▓▓ Gleam ██ Typescript
type Result(Val, Err) { type Result<Val, Err> = {
Ok(Val) _tag: "ok";
Error(Err) value: Val;
} } | {
_tag: "error";
value: Err;
}
19 / 23 Example Let's take a look at a simple Todo App written in Gleam. The code can be found on github at: 20 / 23 Why Gleam I have three main cases for why you should consider Gleam for your next project: ██ The FP Noob You want to learn more about functional programming but don't want to step into the world of monads and endofunctors ala Haskell. ▓▓▓ The Beam Enjoyer You want to make use of the BEAM VM and the existing ecosystem of Erlang and Elixir packages, but you prefer the simplicity and style of C or Javascript. ▒▒▒▒ Any sane person Lucy (The Gleam mascot) is just cute af. 21 / 23 Additional Resources ██ Gleam Language Tour ██ Install ██ Project Tutorial
22 / 23 Fin 23 / 23