First steps in Elixir. Simple file IO and parsing in my module
Dictionary.ex.
defmodule Dictionary do
def longest_word do
IO.puts ("assets/words.txt")
|> File.read!()
|> String.split(~r/\n/)
|> Enum.max_by(&String.length/1)
end
def word_list do
stream = File.stream!("assets/words.txt")
Enum.each(stream, fn(x) -> IO.puts x end)
end
def random_word do
"assets/words.txt"
|> File.read!()
|> String.split(~r/\n/)
|> Enum.random()
end
end
Execute With These Terminal and REPL Commands
$ iex -S mix
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe]
[kernel-poll:false] [dtrace]
Interactive Elixir (1.4.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1) r Dictionary
warning: redefining module Dictionary (current version loaded from _build/dev/
lib/dictionary/ebin/Elixir.Dictionary.beam)
lib/dictionary.ex:1
{:reloaded, Dictionary, [Dictionary]}
iex(2)> Dictionary.random_word()
"tourist"
iex(3)> Dictionary.random_word()
"away"
iex(4)>
Exercise: Get a Tuple From String
This string will be divided by its comma.
iex(15)> stuff = "had we but world enough, and time"
iex(16)> [head | tail] = String.split(stuff, ~r/\,/)
["had we but world enough", " and time"]
iex(17)> head
"had we but world enough"
iex(18)> tail
[" and time"]
iex(19)>
Exercise: Get a Tuple From String
This string will be divided by its several commas.
iex(26)> gamma = "one,two,three,four,five"
"one,two,three,four,five"
iex(27)> [alpha | omega] = String.split(gamma, ~r/\,/)
["one", "two", "three", "four", "five"]
iex(28)> alpha
"one"
iex(29)> omega
["two", "three", "four", "five"]
iex(30)> gamma = "one, two, three, four, five"
"one, two, three, four, five"
iex(31)> [first | last] = String.split(gamma, ~r/\,[ ]?/)
["one", "two", "three", "four", "five"]
iex(32)> first
"one"
iex(33)> last
["two", "three", "four", "five"]
iex(34)>
Pattern Matching Assignment
iex(47)> [a, b, c] = [1, 2, 3]
[1, 2, 3]
iex(48)> a
1
iex(49)> b
2
iex(50)> c
3
iex(51)> [four, five, six] = [4, 5, 6]
[4, 5, 6]
iex(52)> four
4
iex(53)> five
5
iex(54)> six
6
iex(55)>