Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:erlang.bit_size(nil) error when first argument in function is zero

Tags:

erlang

elixir

defmodule Complex do
    def complex_to_string(r, i) do
        to_str = ""
        to_str = to_str <>
        if r != 0 do
            "#{r}"
        end

        to_str = to_str <>
        cond do
            i < 0 or (r == 0 and i != 0) ->
                "#{i}i"
            i > 0 ->
                "+#{i}i"
            :true ->
                ""
        end
        to_str
    end
end

Everything works fine when first argument is not zero.

iex(111)> Complex.complex_to_string(-1, 4)
"-1+4i"
iex(109)> Complex.complex_to_string(4, 2)
"4+2i"
iex(110)> Complex.complex_to_string(4, 0)
"4"

After calling function with zero as a first parameters error happens.

iex(111)> Complex.complex_to_string(0, 4)

** (ArgumentError) argument error :erlang.bit_size(nil) iex:111: Complex.complex_to_string/2

Why is this happening? Is it possible to call a function with first parameter as zero? If not then why?

Edit 1:

After quick analysis I've managed to deal with this problem. The problem was that if r == 0 then to_str <> nil would happen. There was no default option (else) for conditional instruction.

    to_str = to_str <>
    cond do 
        r != 0 -> 
            "#{r}"
        true ->
            ""
    end

This solves the problem.

like image 353
karlosos Avatar asked Jan 28 '23 00:01

karlosos


1 Answers

The problem is in this line:

to_str = to_str <>
  if r != 0 do
    "#{r}"
  end

When r == 0, the if returns nil (because there is no else block) which can't be appended to a String. If you don't want to append anything if r == 0, return "" from else:

to_str = to_str <>
  if r != 0 do
    "#{r}"
  else
    ""
  end

or shorter:

to_str = to_str <> if(r != 0, do: "#{r}", else: "")
like image 112
Dogbert Avatar answered Feb 14 '23 09:02

Dogbert