pillaiindu

pillaiindu

Is there some good blog post or video from some influential Elixirist (like Jose Valim) about when to use Lists over Tuples and vice versa, and when to use Keyword Lists or Maps or Structs? Better if the blog post is new and is based on Elixir 1.2 or above, so that the Elixir Maps implantation is based on the new Erlang Maps implementaion with the deprecation of HashDict.

Thank You!

Edit
@josevalim Please read this thread from top to bottom, and comment!

Showing Posts 1 to 10

NobbZ

NobbZ

I’m not aware of any blog posts, but I’m wondering why you are asking for lists vs tuples. Usually a list is a collection of similar things, you can have between 0 and many items. Tuples though are grouping different things to form a new thing.

hassan

hassan

… but I’m wondering why you are asking for lists vs tuples. Usually a list is a collection of similar things

And yet the very first example of a list here:

List – Elixir v1.5.2

is a set of dissimilar items. So the question seems reasonable :slight_smile:

jeremyjh

jeremyjh

List versus tuples is easy though; generally your data has a fixed number of elements (tuple) or it doesn’t (list).

There isn’t a sound-byte on this page, but the elixir-lang tutorial does give good guidance on Keywords versus Maps. Keyword lists are ordered, and can have duplicates, but have linear performance. Maps are not ordered, cannot have duplicates and perform well with large numbers of elements. Keyword lists are used commonly for optional arguments and have a constructor syntax sugar for this reason, but one flaw in this purpose is that pattern matching the keys is impractical as you must match them in the correct order. An interesting workaround for this is employed by the Phoenix framework; when you call render in a controller the last argument is a keyword list so you can easily pass assigns. When you define render in a view, the keyword list is converted to a map so you can pattern match the keys.

Structs vs. maps I think is a little more nuanced. Structs have some requirements: fields are known up front, keys can be atoms, sensible defaults exist. But even if all those hold true you may still use a map if the scope / lifetime of the structure is very small, such as a map that is only passed between 2-3 functions. When the scope or lifetime of a structure is larger (used in multiple modules) it may make more sense to define a struct.

kokolegorille

kokolegorille

Learning FP with Elixir, I was also surprised with data structures. It turns out they are very familiar in all FP languages.

As a practical example, this is how I use them

  • List are linked list, and optimized for TCO. That is why You see often [head | tail]. They are not so good for asking the 5th element for example.

  • Tuples are used when position matters… And You often see them as response {:ok, blah} | {:error, reason}. They are connected with Erlang records #{}, or Mnesia. But in Elixir, Struct are replacing records most of the time. They should not be too big, and they are perfect for storing fixed shape data.

  • Keywords are almost everywhere, but under the hood, they are just List of 2 elements tuples. [a: 1, b: 2] == [{:a, 1}, {:b, 2}]. You see this when using def my_func, do: blah.
    They can have duplicate keys. Mostly, I use them when passing options to function, because it’s handy to manage multiple parameters. Like this … my_func(options \\ ) I could then call my_func(blah: 1, blih: 2) and use Keyword module on options

  • Maps are like key value. They are the go to structure in Elixir. They cannot have duplicate keys, nor the key order is preserved… I mostly use them as GenServer state

  • Structs are just like super maps, they only accept atom keys, so you can call it with dot notation. It would be like an object, but without methods… after all, it’s FP here. It’s also what You use when persisting with ecto.

I did not mention MapSet, and maybe I am missing other structs… but You get the idea, each data structure is special in a way.

16
Post #4
hassan

hassan

List versus tuples is easy though; generally your data has a fixed number of elements (tuple) or it doesn’t (list).

And yet, while the Tuple doc also says

“… (are) mostly meant to be used as a fixed-size container”

3 of the 5 Tuple functions change the size of the tuple. Which
seems a bit contradictory :slight_smile:

jeremyjh

jeremyjh

There is no contradiction. When you pattern match a tuple, you will only match on tuples for that size. Transforming a tuple to a different size is the equivalent of changing it to a different type. This would be like mapping your data from one struct to a different struct. The fact that the functions are there, doesn’t mean you use them to treat tuples as lists.

michalmuskala

michalmuskala

In my 2.5 years of professionally writing elixir daily, I never used any function from the Tuple module besides Tuple.to_list/1 (and that mostly for some meta-programming or some nasty processing in the depths of ecto). You generally only pattern match on tuples and handle them that way.

10
Post #7
hassan

hassan

There is no contradiction.

I disagree, given the context of the original question.

For someone new to Elixir looking for guidance on when to use what
data structure, saying “use this for fixed size collections” and “here’s
how you change the size” is – not contradictory? not even slightly
confusing?

And whether those functions are frequently used in practice by an
experienced developer is irrelevant; I’m talking about how the docs
help or hinder informing the OP’s question.

jeremyjh

jeremyjh

That may depend on whether or not they have experience with other functional languages, or at least reading an introductory book for Elixir (all of which make this very clear). I can tell you with certainty that this is not surprising or iconsistent for someone experienced in Haskell or Scala (nor, I don’t think, in OCaml, F#, Clojure or Lisp). Tuples of different sizes (and with different member types) are different types. In Erlang and Elixir, they are also different types but perhaps its more useful to think of them as like being functions of different aritys. Sure, you can transform one type to another type, and Tuple gives you some functions for doing so. That doesn’t mean they are equivalent to or readily confused with linked lists.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews