Viklund Random thoughts


Learning Gleam

Gleam is a statically typed functional programming language that runs on the Erlang virtual machine. I work with .NET, so there’s no realistic hope of using it at work. But as a language it has everything I like: it’s functional, it has strong static typing and pattern matching, and its API is small and consistent.

I’m currently working through the Exercism Gleam track, and I must say it’s a joy to program without classes, interfaces and other bloat.

Here’s my solution to the Raindrops exercise, which turns a number into raindrop sounds based on its factors. First in Gleam:

pub fn convert(number: Int) -> String {
  let sounds =
    [#(3, "Pling"), #(5, "Plang"), #(7, "Plong")]
    |> list.filter(fn(coded_sound) { number % pair.first(coded_sound) == 0 })
    |> list.map(pair.second)

  case sounds {
    [] -> int.to_string(number)
    _ -> string.concat(sounds)
  }
}

And the same in C#, the language I write every day:

public static class Raindrops
{
    public static string Convert(int number)
    {
        var sounds = new List<(int, string)> { (3, "Pling"), (5, "Plang"), (7, "Plong") };

        var result = Join("", sounds.Select(s => number % s.Item1 == 0 ? s.Item2 : "").ToArray());

        return IsNullOrEmpty(result) ? number.ToString() : result;
    }
}

Both do the same thing, but I find the Gleam version much easier to read. No class, no ternaries, just a list of sounds and a case for when there are none.

Let’s see how far I get with the track, but at least the start has been great.