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
… 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!