0

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)
Bala
  • 11,068
  • 19
  • 67
  • 120
  • `> MyList.span(65, 68) == [65, 66, 67, 68] #=> true`, that's how console interprets the list with `charcodes`. http://stackoverflow.com/questions/32804904/how-to-print-out-a-maps-array-values-in-elixir – sobolevn Jun 13 '16 at 11:03
  • Sure there is a pattern match but I would like to print numbers (imagine a non-technical user using it, they would raise a defect ...lol) – Bala Jun 13 '16 at 11:06
  • Then `IO.inspect [65, 66, 67, 68], char_lists: :as_lists` – sobolevn Jun 13 '16 at 11:06
  • 4
    Possible duplicate of [Elixir lists interpreted as char lists](http://stackoverflow.com/questions/30037914/elixir-lists-interpreted-as-char-lists) – Dogbert Jun 13 '16 at 11:51

1 Answers1

2

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
Community
  • 1
  • 1
coderVishal
  • 8,369
  • 3
  • 35
  • 56