Qqwy

Qqwy

TypeCheck Core Team

During writing some code related to Arrays , I encountered a situation in which I wanted to map a function over a tuple.

Now, code that does this is very easy to write if you know exactly what size of tuple you have.
If you don’t… it becomes a little tedious, as Erlang supports tuples with up to 255 elements (EDIT: Turns out that nowadays it supports tuples with up to 2^24 number of elements… :open_mouth: ).
But in Elixir, we can have the code write itself, with some simple metaprogramming:

defmodule TupleMap do
  @max_tuple_size 255

  def map_tuple({}, _fun), do: {}
  def map_tuple({val}, fun), do: {fun.(val)}
  def map_tuple({val1, val2}, fun), do: {fun.(val1), fun.(val2)}

  # ... etc.
  # But writing this by hand is tiresome. So instead:

  for index <- 3..@max_tuple_size do
    vars = Enum.map(1..index//1, fn index -> Macro.var(:"val#{index}", nil) end)
    vars_tuple = {:{}, [], vars}

    result_vars =
      Enum.map(vars, fn var ->
        quote do
          unquote(Macro.var(:fun, nil)).(unquote(var))
        end
      end)

    result_tuple = {:{}, [], result_vars}

    def map_tuple(unquote(vars_tuple), fun) do
      unquote(result_tuple)
    end
  end

  # For comparison:
  def map_tuple_through_list(tuple, fun) do
    list =  Tuple.to_list(tuple)
    result_list =  :lists.map(fun, list)
    List.to_tuple(result_list)
  end
end

I ran a small benchmark on this code, for tuples with up to 20 elements (it would definitely be interesting to run a longer benchmark later).
The results are interesting: It seems that mapping over a tuple is ~30%-50% faster than mapping over a list.
The memory usage (not shown in this picture) is also only 1/4th of that of a list.

This benchmark is of course not very scientific, but I still thought it was interesting and something that might be nice to share.

I don’t know how frequent it is to map a function over all elements in a tuple, but if someone wants above code could easily be wrapped up in a library. Or even better: changed into a macro which includes a defp-implementation in a module that needs it, which will then guarantee that the tuple-call is inlined.

EDIT: I couldn’t help myself and have run a larger benchmark: :sweat_smile:

Where Next? Top

Trending in Discussions Top

budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
achempion
I’ve been using Emacs as my main code editor for more than a two years. It’s a custom build version although I’ve tried doom emacs and sp...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New
jtormey
Lately I’ve been thinking about how to organize components as a LiveView application grows. One of the pain points I’ve found (for myself...
New
Null-logic-0
What IDE or editor are you using for Elixir development? Personally, I use Zed, and I really like it, but sometimes I wish there were a ...
New

Other Trending Topics Top

KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
kip
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews