Function Arity question

context

Working on the Little Elixir and OTP guidebook, and I have a simple question from chapter 3.

question:

The function head of defp compute_temperature(json) do is arity/1

The call to function compute_temperature (see below) is arity/0 (right?) If so, how is compute_temperature(json) arity/1 being called when it looks like it’s arity/0 after it’s passed from JSON.decode! after the pipe operator?

  defp parse_response({:ok, %HTTPoison.Response{body: body, status_code: 200}}) do
    body |> JSON.decode! |> compute_temperature
  end

source: https://github.com/benjamintanweihao/the-little-elixir-otp-guidebook-code/blob/master/chapter_3/metex/lib/worker.ex

1 Like

http://elixir-lang.org/docs/stable/elixir/Kernel.html#|>/2

Basically whatever is left of |> gets put into the first argument on whatever is on the right, thus:

4 |> blah # Is actually:  blah(4)

42 |> bloop(1, 2) # is actually:  bloop(42, 1, 2)

Thus for your example body |> JSON.decode! |> compute_temperature becomes:

compute_temperature(JSON.decode!(body))

It is done for readability purposes, left-to-right operations instead of inside to out.
:slight_smile:

2 Likes

Oh! Does that mean we can never call an arity/0 function after the 1st pipe operator?

1 Like

Yep, because that would make sense and is an error. :slight_smile:

3 Likes

Thank you for answering my questions so quickly! :joy:

2 Likes

Might also take a look into partial (function) application (and the linked to Currying) and Thunk.
These three concepts are the building blocks of functional programming (in general).

1 Like

Technically Erlang and Elixir both lack partial application and currying. You can make a new anonymous function that wraps a function with more calls, but it itself does not have currying. That is one feature that I really wish Elixir added to Erlang. ^.^

3 Likes

Agreed. Auto (or at least manual) currying would make piped functions a lot better.

There’s this.

1 Like

Quark is awesome! I’ve mentioned here a few times on the forum, among other libraries by the same person. :slight_smile:

Still have to state the partials though, does not work with arbitrary functions inline sadly.