spacemonk

spacemonk

Defining function with same arity but different map values in one of param

Hi! I might be asking a silly one, sorry for that and thanks for your time!
my aim is to implement quite simple logic:
the get_or_create_movie could be called with first param with “type” = “movie”, in that case I do not care about any other params and the code stays the same
if the first param contains “type” => “tv-series”, then the logic start to differ according to values. I feel that the straightforward approach I took looks not really pretty :wink:

  def get_or_create_movie(%{ "type" => "movie" } = movie) do
    # same movie code
  end
  def get_or_create_movie(%{ "type" => "movie" } = movie, _like_time) do
    # same movie code
  end
  def get_or_create_movie(%{ "type" => "movie" } = movie, _like_time, _review_text) do
    # same movie code
  end


  def get_or_create_movie(%{ "type" => "tv-series" } = series) do
    # only series code
  end
  def get_or_create_movie(%{ "type" => "tv-series" } = series, like_time) do
    # like_time only series code
  end
  def get_or_create_movie(%{ "type" => "tv-series" } = series, like_time, review_text) do
    # like_time and review text only series code
  end

the dyalizer complains (warning) that the clauses /2 and /3 was previously defined.
the function could be called with “type” = “movie” in the first param and with second and/or third params present

First 8 of 8 Posts Switch mode

Shakadak

Shakadak

Hello :slight_smile:
Are you certain this is a dialyzer warning ?

It seems to me the problem is about mixing different arity and function clauses.
If you define the same function clause with the same number of arguments together it should be fine, like so:

  def get_or_create_movie(%{ "type" => "movie" } = movie) do
    # same movie code
  end
  def get_or_create_movie(%{ "type" => "tv-series" } = series) do
    # only series code
  end

  def get_or_create_movie(%{ "type" => "movie" } = movie, _like_time) do
    # same movie code
  end
  def get_or_create_movie(%{ "type" => "tv-series" } = series, like_time) do
    # like_time only series code
  end

  def get_or_create_movie(%{ "type" => "movie" } = movie, _like_time, _review_text) do
    # same movie code
  end
  def get_or_create_movie(%{ "type" => "tv-series" } = series, like_time, review_text) do
    # like_time and review text only series code
  end
spacemonk

spacemonk OP

Ah, right! That is correct. One problem is the repetitive code in “movie”-case. is there a more compact, DRY way to match any arity if the “type” => “movie”?

LostKobrakai

LostKobrakai

Can you normalize to just /3 functions? E.g. by using a default value if like_time or review_text are not passed.

Shakadak

Shakadak

I think @LostKobrakai’s suggestion is the better idea, but if you can’t find a neutral element for like_time and review_text you can at least use a helper function

Phxie

Phxie

Not sure what the rest of your code is doing, but is something like the below not possible?

If the like_time/review_text logic is identical for each type, then you can just match on the params as a whole rather than targetting the types specifically. Then handle the “type” within the functions like the below or by using a conditional statement.

  def get_or_create_movie(params) do
    handle_type(params["type"])
    # /1 code 
  end

  def get_or_create_movie(params, _like_time) do
    handle_type(params["type"])
    # /2 code
  end
  
  def get_or_create_movie(params, _like_time, _review_text) do
    handle_type(params["type"])
    # /3 code
  end

  def handle_type("movie"),     do: # Movie code
  def handle_type("tv-series"), do: # TV Code
spacemonk

spacemonk OP

I’ve tried that:

  def get_or_create_movie(%{ "type" => "tv-series" } = series, like_time) do
  end

  def get_or_create_movie(%{ "type" => "movie" } = movie, _time \\ nil, _text \\ nil) do
  end

  def get_or_create_movie(%{ "type" => "tv-series" } = series, like_time, review_text) do
  end

one small hicup I had with this is that I can’t pass the function itself as &get_or_create_movie\3 to a Enum stuff as it will raise an exception when it will be passed with one param so I needed to wrap it to anonymous fun and call it with one param like &(Movie.get_or_create_movie(&1)) so the defaults would work. But that is okay.

after that the Elixir warning complains about clauses and defaults:

def get_or_create_movie/3 has multiple clauses and also declares default values.
In such cases, the default values should be defined in a header. Instead of:

    def foo(:first_clause, b \\ :default) do ... end
    def foo(:second_clause, b) do ... end

one should write:

    def foo(a, b \\ :default)
    def foo(:first_clause, b) do ... end
    def foo(:second_clause, b) do ... end

which I find as not correct logic for my case, is it?

al2o3cr

al2o3cr

Each arity (the number after the /) is effectively a separate function. You can capture one with the defaults by using a smaller number:

defmodule Foo do
  def bar(x, y \\ 1, z \\ 2) do
    {x, y, z}
  end
end

Enum.map([:a, :b, :c], &Foo.bar/1)
# => [{:a, 1, 2}, {:b, 1, 2}, {:c, 1, 2}]

Enum.scan([:a, :b, :c], &Foo.bar/2)
# => [:a, {:b, :a, 2}, {:c, {:b, :a, 2}, 2}]

(The result for Enum.scan isn’t terribly relevant, it was just the first function that came to mind that takes a callback that expects two arguments.)

In both cases, the arguments that aren’t passed to the lower-arity versions Foo.bar/1 and Foo.bar/2 are filled in with the defaults.

It’s common in Erlang code to see a long series of function heads with short heads filling in parameters and calling longer ones. This is the same as what Elixir’s compiler builds:

def bar(x, y \\ 1, z \\ 2), do: ...

# is equivalent to

def bar(x), do: bar(x, 1, 2)
def bar(x, y), do: bar(x, y, 2)
def bar(x, y, z), do: ...

which is why you can capture bar/1 and bar/2 distinctly from bar/3

spacemonk

spacemonk OP

thank you for the detailed explanation. That was really eyes opening insight. Now I got the functions much deeper (still a lot to go I believe). elixir community is amazing

— All posts loaded —

Where Next?

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
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
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
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
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 & Solve. They are GUI (Emerge) and State management (S...
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
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement