Skip to content
HN On Hacker News ↗

You should try Gleam

▲ 146 points • 137 comments • by nchagnet • 2w ago • HN discussion ↗

Pangram verdict · v3.3

We believe that this text is a mix of AI and human-written content.

14 %

AI likelihood · overall

Mixed
86% human-written 14% AI-generated
SEGMENTS · HUMAN 7 of 11
SEGMENTS · AI 4 of 11
WORD COUNT 1,543
PEAK AI % 100% · §4
Analyzed
Nov 9
backend: pangram/v3.3
Segments scanned
11 windows
avg 140 words each
Distribution
86 / 14%
human / AI fraction
Verdict
Mixed
Pangram v3.3

Article text · 1,543 words · 11 segments analyzed

Human AI-generated
§1 Human · 0%

Introduction If you have read my recent rant about programming languages, you'll know I've been quite interested in Gleam. Gleam is a functional language that targets BEAM, the Erlang VM,1 with a simple syntax and interoperability with the wider BEAM ecosystem (Erlang and Elixir). Interestingly, Gleam can also target JavaScript i.e., Gleam can be compiled into JavaScript and run through Node.js. I've been mostly using Rust for hobby projects, which at the moment is the only language that really makes coding enjoyable for me, and Gleam has managed to scratch that itch too. If you're a Rust connaisseur, then Gleam will feel familiar to you, bar a few key differences. I feel like 80% of the code I write could be copy pasted to Rust (with a tinge of search-and-replace for syntax) and it'd compile. This post won't give an exhaustive overview of the language, if you want to learn more, I recommend the excellent interactive tour. You'll get a good feel for Gleam in under half an hour. Gleam: the good On its homepage, Gleam is described as "a friendly language for building type-safe systems that scale!" (emphasis theirs) which does a good job of conveying what Gleam is all about. Gleam is friendly The syntax is extremely simple, most of the complex stuff is hidden by the Erlang runtime which you don't really have to interact with unless you want to! Of course, Gleam is a functional language, so if you have lived in a C-shaped imperative world your whole life, it might be a bit daunting at first. But if you compare it to other functional languages (OCaml, Haskell, Erlang), you'll quickly notice Gleam is much simpler. After using it a bit, it feels like all the functional parts of Rust, with a few missing ones, and none of the imperative parts. Let's start from an example piece of code: Gleam// Omitted imports pub fn main() { let total = "1,X,5,6" // String |> string.split(on: ",") // List(String) |> list.map(int.parse) // List(Result(Int, Nil)) |> result.values // List(Int), the invalid entries are dropped |> list.reduce(fn(acc, x) { acc + x }) // Result(Int, Nil) |> result.unwrap(0) // Int echo total // 12 }Rustfn main() { let total = "1,X,5,6" // &str .split(",") .map(|s| s.parse::<i64>()) .filter_map(Result::ok) // Could have used .sum() here .reduce(|acc, x| acc + x) .unwrap_or(0); println!("{}", total); // 12 }Dissecting this a bit, you can see a few specificities of Gleam: variables in Gleam are immutable (so no mut keyword or anything like that), chained functions here all return a new element.2 You can still shadow a binding with a new let, which is how you "update" a value. |> (typed |>) is the pipe operator used to chain functions on data. The main constraint is that the piped variable should be the first argument of the function in the pipe. just like Rust, errors in Gleam are just values as part of the Result monad.3 Comparing with the Rust code snippet, you can see that, up to a few naming choices, they look pretty similar. The main difference in this example is really the piping vs. chaining syntax. Gleam types have no methods so piping is used instead. The piping operator |> is the first of the three mascot features of Gleam you will meet in this post, the other two being the use pattern and tail-call optimization. The use pattern If you've written a lot of JavaScript, you might be used to the indentation creep that arises when nesting many callbacks into one another someFunc(arg, function(param) { someOtherFunc(param, function(otherParam) { // ... }) })In Gleam, many functions expect a callback, for example because as a way to control access to a resource and clean up when the process is done (closing a database connection, releasing a file handle, etc.). To avoid this kind of tower of callbacks, Gleam provides some syntactic sugar: use param <- some_func(arg) is equivalent to some_func(arg, fn(param) { ...

§2 Human · 0%

}).

§3 Human · 0%

The callback must always be the last argument of the function. That is the opposite of |>, which fills the first one. With useuse param <- some_func(arg) use other_param <- some_other_func(param) echo other_paramWithout usesome_func(arg, fn(param) { some_other_func(param, fn(other_param) { echo other_param }) })Tail-call optimization This one might genuinely trip you up if you're not familiar with it. The first thing you need to know is there are no loops in Gleam! Again, if you've written OCaml or Haskell before, you won't be surprised by this. In 98% of cases,4 loops are simple operations over bounded iterations. Think for loops on a list or a set. Exactly the kind of thing which in Rust you always have two ways of doing: one imperative with the exact for loop, one more functional with a combination of operations on iterators. Well, if you look at the code example in the previous section, you'll see Gleam uses the second kind and has a plethora of functions to iterate over lists, sets, tuples, strings, anything. But what if you need something more complicated? What about the 2%? This is where you would instead use recursion! A simple algorithm which illustrates this is Euclid's algorithm to compute the Greatest Common Divisor (GCD). Below you can find a Rust iterative example, and a Gleam recursive example. Rustfn gcd(mut a: u64, mut b: u64) -> u64 { while b != 0 { let remainder = a % b; a = b; b = remainder; } a }Gleamfn gcd(a: Int, b: Int) -> Int { case b { 0 -> a _ -> gcd(b, a % b) } }Of course, you can also write the recursive version in Rust, but this usually isn't such a great idea.

§4 AI · 100%

Recursion in imperative languages can quickly get out of hand: every call adds a new stack frame, and a deeply recursive function can blow the stack (the infamous stack overflow). On the BEAM there is no fixed-size stack, so runaway recursion eats heap memory until the process is killed instead, but the point remains: deep recursions equals trouble.

§5 Human · 0%

To avoid that problem, compilers for functional languages implement a technique called Tail Call Optimization (TCO), which applies when the recursive call is the last thing the function does. The existing stack frame is then reused instead of stacking a new one, giving performance close to an imperative while loop.5 Gleam is type-safe This piece of the slogan is mostly there to answer the obvious question "why Gleam and not Elixir?" (another Erlang-based language). While Elixir is a dynamically-typed language (with gradual typing now!), Gleam was built as a statically-typed language with a strong type system: strong types are its raison d'être. A type in Gleam encompasses both the enum and the struct concepts in Rust: Gleam// A usual enum type Directions { Left Right } // A 'struct-like' type type Person { Person(name: String, age: Int) } // A combination of both type MyError { Missing InvalidQuery(String) }Rustenum Directions { Left, Right } struct Person { name: String, age: i64 } enum MyError { Missing, InvalidQuery(String) }Because Gleam types are algebraic data types, they are very useful to ensure undesired states are impossible. A great aspect of Gleam, which will be relevant a little bit later, is that it compiles to both the BEAM virtual machine and to JavaScript. So you can share these strong type definitions across different applications in both targets. This is particularly handy if you need a web application to communicate with a BEAM app. Gleam is made for systems that scale That, of course, refers to BEAM, the Erlang VM. Unlike languages which target the native system (Rust, Go, C++), a VM provides an extra abstraction layer between the system and the program. In the case of BEAM, that layer is exceptionally good at handling concurrent processes and failures while remaining fast. Gleam makes good use of that, and this is what a concurrent program would look like: // Omitted imports pub fn main() { let order_number_and_amounts = [ #(101, 100), #(102, 200), #(103, 300) ] order_number_and_amounts |> list.each(fn(x) { let #(order_no, amount) = x let order_description = "Order #" <> int.to_string(order_no) // Spawn unlinked: a crashing worker must not take the parent down.

§6 Human · 0%

process.spawn_unlinked(fn() { // 101 and 103 will succeed, 102 will crash process_order(order_description, amount) }) }) io.println("All orders dispatched!")

§7 AI · 100%

// Keep the parent alive until the children have had time to run.

§8 Human · 0%

process.sleep(10) } fn process_order(order: String, amount: Int) { process.sleep(1) case amount { 200 -> panic as "Payment failed!" _ -> io.println(order <> " processed successfully") } } // Stdout // ---- // All orders dispatched! // Order #101 processed successfully // Order #103 processed successfullyWhat you should take away from this code is that it's the BEAM that handles processes.

§9 Human · 19%

The call to process.spawn_unlinked triggers a new process with no link to its creator, so when order 102 crashes, neither the parent nor siblings are affected.

§10 AI · 100%

With a plain process.spawn the child would be linked to the caller, and that panic would have taken the whole program down.

§11 AI · 100%

If you look closely, I also added process.sleep(10) so the parent wouldn't close before the children could finish: this is a hack, since the delay is only a guess and a slower child would still be cut off.