Reputation: 11234
I am working through example questions from Programming Elixir (PragProg). The question is to write a function that returns numbers from
to to
. My solution is as below. However, sometimes they return characters (equivalent to their ascii). How can I avoid that and return numbers only.
defmodule MyList do
def span(), do: []
def span(from), do: [from]
def span(from, to) when from == to, do: [from]
def span(from, to) when from > to, do: [from] ++ span(from - 1, to)
def span(from, to) when from < to, do: [from] ++ span(from + 1, to)
end
MyList.span(31,34) #=> [31,32,33,34]
MyList.span(-5,-8) #=> [-5,-6,-7,-8]
MyList.span(65,68) #=> 'ABCD' (I need a list with numbers 65 to 68)
Upvotes: 0
Views: 608
Reputation: 9079
You cannot prevent as such, beacuse Elixir and Erlang do not have user-defined types, so there's no way to distinguish between a list and a single quoted string, because both are just lists. You really should not have much of a problem with it.
If its printing then you can do something like this
IO.inspect [65, 66, 67, 68], char_lists: false#[65, 66, 67, 68]
For a good detailed explanation on the cause, go to this post - https://stackoverflow.com/a/30039460/3480449
To add this in your module, which prints the result you will need additional methods , and make others private
defmodule MyList do
def span(), do: IO.inspect [], char_lists: false
def span(from), do: IO.inspect [from], char_lists: false
def span(from, to), do: IO.inspect span_h(from, to), char_lists: false
defp span_h(from, to) when from == to, do: [from]
defp span_h(from, to) when from > to, do: [from] ++ span(from - 1, to)
defp span_h(from, to) when from < to, do: [from] ++ span(from + 1, to)
end
Upvotes: 2