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!!!
A group of one or more characters enclosed by [ ] as part of Like operator's right string expression. This list contains single characters and/or character ranges which describe the characters in the list.
A bitstring is a fundamental data type in Elixir, denoted with the <<>> syntax. A bitstring is a contiguous sequence of bits in memory.
In Elixir the to_string function can convert a number into a string. There is already a function in the String module for reversing a string called String. reverse . Strings can be converted into integers using the String.
Just throw in |> IO. inspect(label: "foo") anywhere to print the value with a label without affecting the behavior of the original code.
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
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With