eeff

eeff OP

Hi, I am learning Elixir and recently reading the Supervisor source code, and came accross start_link/2 and start_link/3:

# https://github.com/elixir-lang/elixir/blob/v1.20.1/lib/elixir/lib/supervisor.ex#L733
def start_link(children, options) when is_list(children) do

# https://github.com/elixir-lang/elixir/blob/v1.20.1/lib/elixir/lib/supervisor.ex#L976
def start_link(module, init_arg, options \\ []) when is_list(options)

As far as I understand, the default argument in def start_link(module, init_arg, options \\ []) should cause another start_link/2 to be defined and should result in ambiguity ? Does guard helps the compiler reduce ambiguity and thus the compiler treats it as a second clause for start_link/2 ? If so, the two clauses does not need to be grouped together ?

I tried the following:

defmodule A do
  def f(a), do: "f(#{inspect(a)})"

  def f(a, b \\ []) when is_list(b), do: "f(#{inspect(a)}, #{inspect(b)})"
end

and result in a warning:

➜  /tmp iex test.ex
Erlang/OTP 27 [erts-15.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [jit:ns]

    warning: this clause for f/1 cannot match because a previous clause at line 2 always matches
    │
  4 │   def f(a, b \\ []) when is_list(b), do: "f(#{inspect(a)}, #{inspect(b)})"
    │       ~
    │
    └─ test.ex:4:7

Interactive Elixir (1.19.0-dev) - press Ctrl+C to exit (type h() ENTER for help)

But if I changed the order of the def’s:

defmodule A do
  def f(a, b \\ []) when is_list(b), do: "f(#{inspect(a)}, #{inspect(b)})"

  def f(a), do: "f(#{inspect(a)})"
end

it results in an error:

➜  /tmp iex test.ex
Erlang/OTP 27 [erts-15.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [jit:ns]

    error: def f/1 conflicts with defaults from f/2
    │
  4 │   def f(a), do: "f(#{inspect(a)})"
    │       ^
    │
    └─ test.ex:4:7: A.f/1

** (CompileError) test.ex: cannot compile module A (errors have been logged)
    test.ex:4: (module)

Can anybody point me to related documentation about this behavior difference ?

First 10 of 10 Posts Switch mode

hauleth

hauleth

The difference is that in Supervisor example you have provided there is guard, which limits about of cases it will match.

So the expanded code will look like

def a(x) when is_list(x), do: …

def a(x), do: a(x, :default)

def a(x, y), do: …

So as you can see, there is a situation when 1st clause match.

If you swap order of these functions, then it will mean that there would be no option to call first clause.

eeff

eeff OP

I still don’t understand why switching the order would switch between warning and error.

mudasobwa

mudasobwa

Creator of Cure

Sidenote: Please upgrade the toolchain to Elixir1.20.1 / OTP29.

The compiler explicitly handles \\ operator because Erlang does not have default argument values. It does not allow any redeclaration after \\ has been expanded. Look-behind, though, would have a ton of redundant tracking involved, decreasing performance, that’s why it does not blow up immediately.

The error you observe is raised by first-pass compiler, meeting the \\ default parameters within the function redeclaration.

The warning you observe if you swap clauses is the second-pass compiler, simply warning you about unreachable clause, it has nothing to do with \\ because there is no look-behind.

odelbos

odelbos

You need to do it like this:

defmodule A do
  def f(a, b \\ [])

  def f(a, []), do: "f(#{inspect(a)})"
  def f(a, b) when is_list(b), do: "f(#{inspect(a)}, #{inspect(b)})"
end

IO.puts A.f(5)
# Output --> f(5)

IO.puts A.f(5, [:one, :two])
# Output --> f(5, [:one, :two])
eeff

eeff OP

yes, I know about this but this does not answer my question. thank you anyway!

eeff

eeff OP

It does not allow any redeclaration after \\ has been expanded. Look-behind, though, would have a ton of redundant tracking involved, decreasing performance, that’s why it does not blow up immediately.

this does make more sense to me, I guess there are no public documentation about this behavior.

mudasobwa

mudasobwa

Creator of Cure

Here is the documentation:

If a function with default values has multiple clauses, it is required to create a function head (a function definition without a body) for declaring defaults — Modules and functions — Elixir v1.20.2

Just don’t try to hack the proposed syntax. Supervisor also ditched this cludge, that’s why I suggested to use the latest versions of the toolchain.

odelbos

odelbos

It’s because of the declarative f/1 order.
When we write:

def f(a, b \\ [])

I fact the compiler will expand it in two functions:

def f(a), do: f(a, [])  # <-- This is not a declarative f/1 it's the default-argument of f/2
def f(a, b) do: ...

So in the first case

defmodule A do
  def f(a), do: "f(#{inspect(a)})"     # <--- declarative f/1

  def f(a, b \\ []) when is_list(b), do: ...   # <--- will be expanded by the compiler
end

You will have two f/1 but with the declarative f/1 in first position (top-bottom) will match all clauses. So the compiler emit a warning for the unreachable expanded f/1 that handle the default-argument case of f/2.

In the second case:

defmodule A do
  def f(a, b \\ []) when is_list(b), do ...   # <--- will be expanded by the compiler
  def f(a), do: "f(#{inspect(a)})"     # <--- declarative f/1
end

The declarative f/1 is after the expanded f/1 but from the compiler’s perspective, the expanded f/1 is not a declarative f/1 function it’s the mechanism that handle the default-argument of the f/2 function. So when later the compiler encounter the declarative f/1 which is in conflict with the auto-generated f/1 it emit a compilation error.

mudasobwa

mudasobwa

Creator of Cure

What’s “declarative function” and what does mean “in conflict” in regard to function clauses?

odelbos

odelbos

A declarative function is a function written by the coder in contrast with the auto-generated (or meta-programming) function written by the compiler.

In the first case, there isn’t any conflict with the declarative f/1 (meaning the coder want this function), so when calling f/1 the declarative f/1 will be called. The compiler emit a warning saying “hey I’m doing a trick to handle the default-argument case of f/2 but it will not work” because of the declarative f/1 that will match all clauses about f/1).

In the second case, the compiler is doing his trick to handle the default-argument of f/2, so it add a f/1 but this auto-generated f/1 break the intent of the coder who declared his own f/1. This f/1 will never be called because of the auto-generated f/1, so in this case there is a conflict (breaking coder intent). This is why the compiler emit an error (“I’m doing something that break your intent”):

error: def f/1 conflicts with defaults from f/2

PS:

def f([]), do: ...   # <-- not matching all possible clauses of f/1 (only matching [] clause)
def f(5), do: ...

def f(a), do: ...    # <--- matching all possibles clauses
— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
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
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

We're in Beta

About us Mission Statement