What is a instance function?

In his awesome talk Escher painting using Scenic Ju Liu mentions an “instance function” (you can see it at 27:06). The code looks like the following:

defmodule SomeModule do
  def some_function do
    @side fn
      # does something


I have never seen such Elixir code, can somebody please explain it to me? What’s an instance function? :slightly_smiling_face:

I think the name “instance function” is a loan from Ruby, though to me it doesn’t really make sense here as there’s no such thing as an instance in Elixir.

Here Ju is using a module attribute as a mutable variable that can be referenced before it is defined in order to create a recursive anonymous function. This is needed because in Elixir anonymous functions cannot refer to themselves, unlike in Erlang.

You can’t assign module attributes inside functions, so it would be used more like this:

defmodule Thingy do
  @func fn ->
    # Can call itself using @func.()

1 Like

One could do something like that in elixir as well, but it looks ugly…

f = fn f ->
  # do something and call `f.()`
g = fn -> f.(f) end

Have done similar in erlang all the time before named anonymous functions became a thing. Haven’t used erlang much since they are :wink:


Yes, that’s probably what I would have gone for rather than using a module attribute.

1 Like

Yeah, I understand anonymous functions, however Ju’s code was confusing me a lot :wink: