Qqwy

Qqwy

TypeCheck Core Team

Fun with mapping over tuples

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?

Popular in Discussions Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54921 245
New
AstonJ
I’ve just started the Phoenix part of the utterly brilliant online course by @pragdave. On generating the Phoenix app he uses the --no-ec...
New
pillaiindu
In django there is a cache framework backed by memcached. Rails also puts a lot of emphasis on caching, and even the idea of russian-doll...
New
MarioFlach
Hello, I want to share a project I’ve been working on for a while: https://github.com/almightycouch/gitgud Background Some time ago I ...
New
lucaong
Hello Elixir and Nerves community, I have been working for a while on an open-source embedded key-value database for Elixir, that I call...
230 14350 124
New
eteeselink
Hi all, In the last days, two things happened: A blog post titled “They might never tell you it’s broken” made the rounds. It’s about ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement