tbk

tbk

Reusing function variables in a `when` conditional

I have a function with a condition:

  def iteraterefs(divisor, number, table, out, i) when number >= divisor do
    number = number - divisor
    out = out <> elem(table, i)
  end

However it seems that the compiler does not like the condition when number >= divisor do, is there something about reuse of function variables I am missing from the documentation?

Marked As Solved

dimitarvp

dimitarvp

IMO this thread is getting a bit too micro, you are kind of posting an error after error and I think you should step back and just post your entire module source code, and state the end goal.

It also sounds like you haven’t practiced Elixir enough if lack of mutability and the lexical scope are still surprising for you. Exercism requires some understanding of the language’s constructs. Without that you’ll just be crashing into one error after another, as it seems it is happening currently.

Also Liked

al2o3cr

al2o3cr

FunctionClauseError is what I’d expect from iteraterefs if it was called with number < divisor. You likely need to define it for those inputs as well to pass Exercism’s tests.

General note: this isn’t going to do what you want. i = i + 1 rebinds the name i inside the do / end block but that value doesn’t escape or even make it to the next iteration.

Same thing for out = out <> elem(table, i) inside iteraterefs; the name out is bound to a new name but then the scope ends immediately.

My recommendation would be to forget completely about Enum.each for a little while; it is almost never the right solution in Elixir.

tbk

tbk

I went away, far up into the mountains which are the Elixir documents, I learned many things and when I returned to take on the challenge again, it neatly folded before me like the recursion I used to solve it:

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
  @refs {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @refs, @table, 0, "")
  end

  defp iterate(num, refs, table, index, out) do
    if num == 0 do 
      out
    else
      ref = elem(refs, index)
      cond do
        num >= ref -> sym = elem(table, index)
                      iterate(num - ref, refs, table, index, out <> sym)
        true -> iterate(num, refs, table, index + 1, out)
      end
    end
  end 
end
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Nicely done, a big improvement! Probably the only other change I’d advocate for is to do this:

  defp iterate(0, _refs, _table, _index, out) do
    out
  end

  defp iterate(num, refs, table, index, out) do
    ref = elem(refs, index)
    cond do
      num >= ref ->
        sym = elem(table, index)
        iterate(num - ref, refs, table, index, out <> sym)
      true ->
        iterate(num, refs, table, index + 1, out)
    end
  end

It’s conventional that when you’re doing recursion like this to define the “base case” or “termination case” as its own clause up front, and then you have other clauses after. This is entirely a stylistic thing though, so it’s up to you!

al2o3cr

al2o3cr

Looks reasonable, though using lists can help avoid tricky off-by-one or off-the-end issues with elem.

As a demonstration of that principle, here are some refactors of the module:

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table {{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}}

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, 0, "")
  end

  defp iterate(num, table, index, out) do
    if num == 0 do 
      out
    else
      {sym, ref} = elem(table, index)
      cond do
        num >= ref ->
          iterate(num - ref, table, index, out <> sym)

        true ->
          iterate(num, table, index + 1, out)
      end
    end
  end
end

This first refactor keeps the tuple-shaped table, but brings the symbols and the values together for readability and future maintainability. Having @table and @refs be different-sized tuples would be Not Good, so combining them together makes that bug impossible.

There’s another place for bugs to hide, though: when we write iterate(num, table, index+1, out), that will try to execute elem(table, index+1) and give:

** (ArgumentError) errors were found at the given arguments:

  * 1st argument: out of range

    :erlang.element(14, {{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}})
    iex:21: RomanNumerals.iterate/4

(this happened in an earlier version when I made a typo)

The root cause is that the recursive call to iterate assumes that a “next” element of table exists, without checking. You could add extra checks to ensure that index < tuple_size(table), but again it’s better to write code that literally can’t run off the end.

First, a very bad refactor that makes things slower. Enum.at is expensive compared to elem, since it needs to traverse the list. This also applies the early-exit cleanup that @benwilson512 suggested.

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table [{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}]

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, 0, "")
  end

  defp iterate(0, _, _, out), do: out

  defp iterate(num, table, index, out) do
    {sym, ref} = Enum.at(table, index)
    cond do
      num >= ref ->
        iterate(num - ref, table, index, out <> sym)

      true ->
        iterate(num, table, index + 1, out)
    end
  end
end

This will fail in a slightly different way for an negative input (match error vs argument error) but it still “goes off the end” and crashes. Checking length(table) is expensive (traversing the list again!) so checking is even harder. Why am I telling you to use lists anyways?

Two things come together to make lists powerful here:

  • a call to iterate will only ever care about index or higher in table

  • There’s one place in a list that isn’t expensive to access: the first element (aka “the head”). It’s also easy to check for, since only [] doesn’t have a head.

This refactor applies that principle: instead of keeping track of table and index separately, it uses hd and tl to interact with the first element and the rest. This is fast and requires no allocations.

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table [{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}]

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, "")
  end

  defp iterate(0, _, out), do: out

  defp iterate(num, table, out) do
    {sym, ref} = hd(table)
    cond do
      num >= ref ->
        iterate(num - ref, table, out <> sym)

      true ->
        iterate(num, tl(table), out)
    end
  end
end

A small cleanup refactor: the pattern of “do something with hd and something else with tl” is so common that it’s usually not written explicitly. This uses pattern-matching to accomplish the same thing as the previous version

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table [{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}]

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, "")
  end

  defp iterate(0, _, out), do: out

  defp iterate(num, [head | rest] = table, out) do
    {sym, ref} = head
    cond do
      num >= ref ->
        iterate(num - ref, table, out <> sym)

      true ->
        iterate(num, rest, out)
    end
  end
end

It’s also very common to absorb a binding like {sym, ref} = head into the function head:

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table [{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}]

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, "")
  end

  defp iterate(0, _, out), do: out

  defp iterate(num, [{sym, ref} | rest] = table, out) do
    cond do
      num >= ref ->
        iterate(num - ref, table, out <> sym)

      true ->
        iterate(num, rest, out)
    end
  end
end

This version crashes in yet a different way, so what can we do about it? The error message gives us a clue:

iex(26)> RomanNumerals.numeral(-1)                                                                                                                                       
** (FunctionClauseError) no function clause matching in RomanNumerals.iterate/3    
    
    The following arguments were given to RomanNumerals.iterate/3:
    
        # 1
        -1
    
        # 2
        []
    
        # 3 
        ""
    
    iex:36: RomanNumerals.iterate/3

Think about what iterate being called with [] for table means: the conversion process has run out of symbols to try. That’s directly representable in code:

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table [{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}]

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, "")
  end

  defp iterate(0, _, out), do: out
  defp iterate(_, [], _), do: raise("bad number")

  defp iterate(num, [{sym, ref} | rest] = table, out) do
    cond do
      num >= ref ->
        iterate(num - ref, table, out <> sym)

      true ->
        iterate(num, rest, out)
    end
  end
end

Another not-actually-relevant-here-but-worth-keeping-in-mind tip on performance: <> in a loop (or recursion) should be regarded with suspicion as it can result in lots of short-lived binaries. A common idiom avoids the repeated operations and does them at the end:

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table [{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}]

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, [])
  end

  defp iterate(0, _, out), do: out |> Enum.reverse() |> Enum.join()
  defp iterate(_, [], _), do: raise("bad number")

  defp iterate(num, [{sym, ref} | rest] = table, out) do
    cond do
      num >= ref ->
        iterate(num - ref, table, [sym | out])

      true ->
        iterate(num, rest, out)
    end
  end
end

As a final cleanup, the cond with one non-default branch could be replaced with an if - or even a guard! The guard style makes the control structures disappear almost completely:

defmodule RomanNumerals do
  @doc """
  Convert the number to a roman number.
  """
  @table [{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}]

  @spec numeral(pos_integer) :: String.t()
  def numeral(number) do
    iterate(number, @table, [])
  end

  defp iterate(0, _, out), do: out |> Enum.reverse() |> Enum.join()
  defp iterate(_, [], _), do: raise("bad number")

  defp iterate(num, [{sym, ref} | _] = table, out) when num >= ref do
    iterate(num - ref, table, [sym | out])
  end

  defp iterate(num, [_ | rest], out) do
    iterate(num, rest, out)
  end
end

Apologies for the long post, but I wanted to avoid the usual “the steps between these two versions are OBVIOUS” hand-waving and justify each piece.

sodapopcan

sodapopcan

Pinning variables only performs a match, it doesn’t create a binding. You aren’t actually doing any pinning in your example so I’m not quite sure how you are picturing it would work but, for example, this doesn’t work:

foo = 1
^foo = 1 + 1 # This is a match error

^foo = 1 + 1 gets expanded to 1 = 2 which, of course, does not match.

If you want to accumulate a variable the most basic ways to are either recursion or Enum.reduce.

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
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
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

We're in Beta

About us Mission Statement