📎 Webclip
A Simple Example of Calling an Elixir Library from Gleam
Michael Lynch wanted to see Gleam’s flagship interop feature in action, calling an Elixir library, but couldn’t find a worked example anywhere. So he built one himself: a Gleam wrapper around the Elixir CSV package’s encode function, documented step by step as a beginner learning both languages at once.
The core difficulty is the type mismatch between a statically typed language and a dynamically typed one running on the same virtual machine. Elixir and Gleam both compile to BEAM bytecode, so Gleam can call Elixir functions directly, but Gleam has no native concept of Elixir’s Enumerable protocol, and the wrapper has to bridge that gap by hand.
Fichamento#
- Gleam calls Elixir code through the
@external(erlang, "Elixir.CSV", "encode")attribute, using theElixir.prefix because that’s the namespace Elixir functions get compiled to on BEAM. CSV.encodetakes a list of lists of strings and returns something typed as Elixir’sEnumerable, which has no Gleam equivalent, so Lynch defines an opaqueElixirEnumerableplaceholder type just to receive it.- Converting that placeholder into something Gleam can actually use requires a second external call, to Elixir’s
Enum.to_list, which turns theEnumerableinto a plain Elixir list that matches Gleam’sListtype. - The final public wrapper is three lines: pipe the input through
csv_encode, then throughenum_to_list, exposing only that combined function and keeping the two low-level externals private. - He hit a version bug immediately:
gleam newscaffolded agleeunitdependency requiring Gleam 1.11.0 while he had 1.10.0 installed, fixed by pinninggleeunitback to 1.3.1. - Before writing any Gleam code, he explored
CSV.encode’s behavior directly iniex, Elixir’s interactive shell, since he didn’t yet know Elixir’s sigil syntax or the exact shape of the function’s output.
