Help Understanding Return of Function

Hello,

I’m going through Elixir in Action right now and one of the exercises is to create a function that returns the list of all values between two numbers. When I use certain value pairs it seems like I’m getting returned bitstrings for some reason. The output should just be one, and with other values it returns a single value list with 1 but there’s two cases I’ve ran into so far where it’s not returning properly.

Here’s the code:

defmodule NumUtil do
  def get_range(num1, num2) do
    do_range(Kernel.min(num1, num2), Kernel.max(num1, num2), 1, [])
  end
  
  defp do_range(start_num, target_num, current_iter, list) when start_num + current_iter == target_num do
    list
  end

  defp do_range(start_num, target_num, current_iter, list) do
    update_list = [start_num + current_iter | list ]
    new_iter = current_iter + 1
    do_range(start_num, target_num, new_iter, update_list)
  end
end

So when I do NumUtil.get_range(12, 15) I get back the expected [14, 13] but when I do NumUtil.get_range(12, 14) I get back '\r'. I had initial input at 0 instead of one before and with 12,13 it returned back '\f'. I figure it was something I didn’t understand about single element lists but if I do it on a different value pair like (1,3) I get back the expected [2]… There are other pairs that seem to return strings but I’m not sure why. Could anyone please help me understand the behavior?

Also what is the “proper” way to write this function, I’m pretty sure mines a bit of a mess so any tips would be appreciated. Thanks for the help in advance!

You created a charlist, nothing wrong with that, it’s just a little odd.

iex(19)> inspect 'hello', charlists: :as_lists 
"[104, 101, 108, 108, 111]"
iex(20)> inspect 'hello'                      
"'hello'"

iex(21)> inspect [104, 101, 108, 108, 111]
"'hello'"
iex(22)> inspect [104, 101, 108, 108, 111], charlists: :as_lists
"[104, 101, 108, 108, 111]"

iex(24)> [104, 101, 108, 108, 111] == 'hello'
true
iex(25)> [104, 101, 108, 108, 111] == "hello"
false
iex(26)> 'hello' == "hello"
false

iex(27)> is_list('hello')
true
iex(28)> is_list("hello")
false
iex(29)> is_binary("hello")
true
1 Like

https://hexdocs.pm/elixir/List.html#module-charlists

1 Like

In elixir by default iex print their ascii value if a valid value is input for example
iex(12)> [101, 102, 103, 104]
‘efgh’

Any number which is not valid will be print as is as List format for example below
iex(13)> [411, 412, 413, 414, 415]
[411, 412, 413, 414, 415]

Now if want to print the actual numbers instead of ascii then we need to try below

iex(14)> [101, 102, 103, 104] |> inspect(charlists: :as_lists)
“[101, 102, 103, 104]”

Refer this link for more details.

1 Like

@neetspin Here is another quick small function to do the same thing thing you’re looking for

  def get_mid_numbers(first, last) do
    first + 1 ..last - 1
    |> Enum.to_list
  end

See more: :slightly_smiling_face:

2 Likes