Question

I play with Range in Elixir.
It works fine:

>1..10 |> Enum.map fn(x) -> x |> IO.puts end
>1
>..
>10
>[:ok, :ok, :ok, :ok, :ok, :ok, :ok, :ok, :ok, :ok]

But here have error:

>'a'..'z' |> Enum.map fn(x) -> x |> IO.puts end
 ** (Protocol.UndefinedError) protocol Range.Iterator not implemented for 'a'
 /Users/elix_lang/lib/elixir/lib/range.ex:7: Range.Iterator.impl_for!/1

I come from Ruby familiar with Erlang
I want to understand what's the problem?
Thanks!!!

Was it helpful?

Solution 2

Regarding the 1st one, I think Enum.each can be used, if you just want to iterate through the range.

iex(1)> 1..10 |> Enum.each fn(x) -> IO.puts(x) end
iex(2)> 1..10 |> Enum.each &IO.puts(&1)
1
2
...
:ok

Regarding the 2nd one, one option might be like the following (though there may be a better way).

iex(3)> ?a..?z |> Enum.each &IO.puts(String.from_char_list!([&1]))
a
b
...
:ok

iex(4)> ?a..?z |> Enum.map(&String.from_char_list!([&1])) |> IO.puts
abcdefghijklmnopqrstuvwxyz
:ok

[2.3 Strings (binaries) and char lists (lists)] in the following covers some of the char list (?a, etc.) http://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html

OTHER TIPS

The provided answer no longer works in elixir 1.4.1 because String.from_char_list/1 was deprecated. You can now generate a list of characters like this:

?a..?z
|> Enum.to_list
|> List.to_string

I quite like using the following syntax to generate a list of characters due to its clarity on specifically wanting the UTF-8 binary representation of the character returned, rather than its codepoint:

iex(1)> Enum.map(?a..?z, fn(x) -> <<x :: utf8>> end)
["a", "b", "c", ..., "z"]

Or, its for comprehension syntax:

iex(1)> for x <- ?a..?z, do: <<x :: utf8>>
["a", "b", "c", ..., "z"]

So, in your specific case:

iex(1)> Enum.map(?a..?z, fn(x) -> <<x :: utf8>> |> IO.puts() end)
a
b
c
# ...
z
[:ok, :ok, :ok, ..., :ok]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top