stefanluptak

stefanluptak

Why Enum.reduce fun arguments are x, acc instead of acc, x?

Good day everyone!

I am using Enum.reduce/3 (Enum — Elixir v1.9.0-rc.0) function quite often and I am regularly wondering why are the arguments for reducing function x, acc instead of acc, x.

Almost all functions in Elixir are in the form of Module.function(subject_of_change, change_argument). For example MapSet.put/2 or List.delete/2. Thanks to this, we can write code like:

changeset
|> cast(params, [ ... ])
|> validate_required([ ... ])
|> unique_constraint( ... )

But then, when I want to do something like this:

Enum.reduce([1,2,3,4], MapSet.new, &MapSet.put(&2, &1))

I need to use the &2, &1 form which is a bit unhandy. I think this form would be a lot nicer:

Enum.reduce([1,2,3,4], MapSet.new, &MapSet.put/2)

Is there some explanation for this? I am really curious. :slight_smile:

Thanks a lot.

Most Liked

michalmuskala

michalmuskala

I always thought that it follows the order of the arguments to Enum.reduce itself - first the collection, then the accumulator, so in the reducer you get the element first and the accumulator second.

10
Post #2
sasajuric

sasajuric

Author of Elixir In Action

Don’t know the answer, but FWIW I also think that passing the acc first, collection element second would be more intuitive, and I frequently find myself flipping these two args in reduce.

peerreynders

peerreynders

I think you’re remembering that foldl is easier to tco than foldr.

defmodule Fold do
  # reduce _is_ foldl
  # foldl [a] -> b -> (a -> b -> b) -> b
  def foldl([], acc, _),
    do: acc

  def foldl([x | xs], acc, f),
    do: foldl(xs, f.(x, acc), f)

  # foldr [a] -> b -> (a -> b -> b) -> b
  def foldr([], acc, _),
    do: acc

  def foldr([x | xs], acc, f),
    do: f.(x, foldr(xs, acc, f))
end

list = [1, 2, 3]
f = &[&1 | &2]

IO.inspect(Fold.foldl(list, [], f)) # [3,2,1]
IO.inspect(Fold.foldr(list, [], f)) # [1,2,3]

Folding (reducing) emerged from “folding lists” - the most common list operation is cons-ing:

f = &[&1 | &2]

Note how the parameter order isn’t “unhandy”. One could argue that the unhandy-ness is a result of the preferred parameter order in Elixir due to pipelining. In a curried language the opposite order (the thing that changes should be last) would be preferred.

Note also that Elixir inherited the order from Erlang (1986):

and Erlang has no pipelining.


FYI:

Haskell (1990):

Prelude.foldl: (a -> b -> a) -> a -> [b] -> a
Prelude.foldr: (a -> b -> b) -> b -> [a] -> b

OCaml (1996):

fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b

Interestingly for “fold left” it’s (acc, elem -> acc) while for “fold right” it’s (elem, acc -> acc)

Hypothesis:

  • (acc, elem -> acc) for “fold left” accumulator is built from the list left-to-right (left associative)
  • (elem, acc -> acc) for “fold right” accumulator is built from the list right-to-left (right associative)

LISP (1958)

(reduce (lambda (x y) (+ (* x 10) y)) '(1 2 3 4)) => 1234
iex(1)> Enum.reduce([1,2,3,4], & &2 * 10 + &1)
1234

Again LISP used (acc, elem -> acc) for reduce/fold left.

So why would Erlang use (elem, acc -> acc)?

Hypothesis:

  • Conceptually general “folding” refers to foldr because it preserves the order within a list - hence (elem, acc -> acc).
defmodule X do
  def map_1(list, f),
    do: :lists.foldr(&[f.(&1) | &2], [], list)

  def map_2(list, f) do
    (&[f.(&1) | &2])
    |> :lists.foldl([], list)
    |> :lists.reverse()
  end

  def scan_1(list, init, f) do
    fun = fn x, g ->
      fn y ->
        value = f.(x, y)
        [value | g.(value)]
      end
    end

    acc = fn _ -> [] end
    lazy = :lists.foldr(fun, acc, list)
    lazy.(init)
  end

  def scan_2(list, init, f) do
    fn
      x, [y | _] = acc ->
        [f.(x, y) | acc]

      x, [] ->
        [f.(x, init)]
    end
    |> :lists.foldl([], list)
    |> :lists.reverse()
  end
end

list = [1, 2, 3]
f = &(&1 * 2)
g = &Kernel.+/2

IO.inspect(X.map_1(list, f))     # [2, 4, 6]
IO.inspect(X.map_2(list, f))     # [2, 4, 6]
IO.inspect(X.scan_1(list, 2, g)) # [3, 5, 8]
IO.inspect(X.scan_2(list, 2, g)) # [3, 5, 8]

From a performance standpoint foldl is preferred for long lists but requires reversal if order is relevant. But for pragmatic reasons sticking to the same function type (elem, acc -> acc) makes a function usable for both foldr and foldl.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31265 143
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
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
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43757 214
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
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement