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?
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.
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: "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With