TaggedTuple

A library to work with tagged tuples.
Provides functions to work with chains of tags for nested tuples.

Some of the supported operations are: add/remove tag chain to a core value, converting a tuple to list or to map and back. The latter one is useful for converting tuples to/from JSON representation.

iex> use TaggedTuple
...> core_value = 12
...> :tag --- core_value
{:tag, 12}
...> tagged_tuple = :a --- :tag --- :chain --- core_value
{:a, {:tag, {:chain, 12}}}
...> match?(:a --- :tag --- _tail, tagged_tuple)
true

iex> {chain, value} = TaggedTuple.split({:a, {:tag, {:chain, 2}}})
...> chain == {:a, {:tag, :chain}}
...> value == 2
iex> TaggedTuple.tag(2, {:a, {:tag, :chain}})
{:a, {:tag, {:chain, 2}}}

iex> TaggedTuple.to_map({:a, {:tag, {:chain, 2}}})
%{a: %{tag: %{chain: 2}}}
iex> TaggedTuple.from_map(%{a: %{tag: %{chain: 2}}})
{:a, {:tag, {:chain, 2}}}

More information here:

6 Likes

Super great work, man. I like the tagged_tuple library a lot, already used it in a small hobby project as a test!

One thing that might be worth mentioning: would you consider making the custom syntax (the 3 dashes: ---) optional and injectable through use or a configuration setting? Not critical but I’d like to be able to not inject a custom Elixir syntax in my projects.

2 Likes

Well, you can just do not use use TaggedTuple and instead just require TaggedTuple.

1 Like

I can imagine the situation that the --- operator is to be used somehow else in the project. Let’s see what can be done in regards to optional overriding.

Is it possible to see a snippet demonstrating where TaggedTuple can typically be useful?

1 Like

I’m not sure about the use case over Records (besides nice helper functions for conversion). To me it seems ‘Tagged Tuple vs Record’ is like ‘Map vs Struct’. Dynamic vs static.

Sure. tagged_tuple is to operate with sum types. Which are one of the ways to making impossible states impossible in the app. Here is a good article about these Better domain modeling in Elixir with sum types

Here is an example of ShipmentWeight sum type that can be persisted with Ecto.
And this is generic Domo/tagged_tuple_ecto_type.ex at master · IvanRublev/Domo · GitHub to do so for any tagged tuple.

2 Likes

Very interesting article! Thank you