is same as Erlang. • Basic data types, module system etc. • Syntax is very similar to Ruby. • Following slides is a digest of Getting Started which assumes readers to know Erlang mechanism and Ruby syntax.
• string: as byte string or list of integers. • boolean: as atom’s syntax sugar. • There are same built-in function as Erlang. • is_boolean/1, is_float/1 etc.
+ b end • For pattern matching, write multiple “<Arguments Pattern> -> <Expression>”. • Get value o module function: &Enum.map/2 • Call: function_value.(1, 2) #=> 3
match" {1, x, 3} -> "will match, and bind x to 2" _ -> "Would match any value" end cond do 1 + 1 == 0 -> “won’t match” 1 + 1 == 2 -> “will match” true -> “default” end if var == 2 do “true clause” else “false clause end
1 • Reassigning new value is valid operation. • To use existing variable as value for pattern matching(e.g. right-hand side of =), Use pin-operator. • ^foo = 2 raise MatchError because foo binds to 1. • foo = 2 binds 2 to foo.
# convert to lowercase string end # default value of `sep` is “,” def join(str_list, sep \\ “,") do # joins strings using the separator end end # Call module functions MyString.lowercase("Foo") #=> “foo" MyString.lowercase “Foo" #=> “foo" MyString.join(["Foo", "Bar", "Baz"]) #=> “Foo,Bar,Baz”
naming. • alias Math.List as: List • import List, only: [duplicate: 2] • Mechanism of alias and import: • Module name is a atom(That’s all): is_atom(List) #=> true • Elixir add prefix “Elixir.” to module name: List == :”Elixir.List” => ? • So List.last(l) calls last function of module named :”Elixir.List”. • (alias and import simply manipulates these atom)
## Implement a protocol defimpl Blank, for: List do def blank?([]), do: true def blank?(_), do: false end defimpl Blank, for: Any do def blank?(_), do: false end
write like @callback parse(String.t) :: any in the behavior module (e.g. Parser). • We can use type specification also. • Use: write @behavior Parser in a module like JSONParser module. • Then compiler checks the behavior.
is default message” end # Use try do raise ParseError, message: “This is custom message” rescue e in ParseError -> IO.puts “Parse error(#{e.message}) was raised.” end
a list file <- File.ls!(dir), # Generate from a list(for each `dir`) path = Path.join(dir, file), # Binds values File.regular?(path) do # Filter by a predicate File.rm!(path) end # => [:ok, :ok, :ok, :ok, :ok] ## Note: In binding sections, you can filter by pattern-matching. # Bit comprehensions pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>> for <<r::8, g::8, b::8 <- pixels>>, do: {r, g, b} # => [{213,45,132},{64,76,32},{76,0,0},{234,32,15}] # Collect result to the stdio stream(echo program) stream = IO.stream(:stdio, :line) for line <- stream, into: stream do "#{line}\n" end