Skip to content

Instantly share code, notes, and snippets.

@takuoka
Last active June 20, 2019 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuoka/7799b6c996582178aa38 to your computer and use it in GitHub Desktop.
Save takuoka/7799b6c996582178aa38 to your computer and use it in GitHub Desktop.
add = fn a, b -> a + b end
is_function add, 1 # false
add.(1, 2) # 3
(fn -> x = 0 end).()
if true do
"ok"
end
if false do
"this won't be seen"
else
"this will"
end
if true do
a = 1 + 2
end
if true, do: 1 + 2
if false, do: "this", else: "that"
if true, do: (
a = 1 + 2
a + 10
)
is_number(if true do
1 + 2
end)
iex> [a: a] = [a: 1]
[a: 1]
iex> a
1
iex> [a: a] = [a: 1, b: 2]
** (MatchError) no match of right hand side value: [a: 1, b: 2]
iex> [b: b, a: a] = [a: 1, b: 2]
** (MatchError) no match of right hand side value: [a: 1, b: 2]
iex> %{} = %{:a => 1, 2 => :b}
%{:a => 1, 2 => :b}
iex> %{:a => a} = %{:a => 1, 2 => :b}
%{:a => 1, 2 => :b}
iex> a
1
iex> %{:c => c} = %{:a => 1, 2 => :b}
** (MatchError) no match of right hand side value: %{2 => :b, :a => 1}
iex> map = %{:a => 1, 2 => :b}
%{:a => 1, 2 => :b}
iex> map.a
1
iex> %{map | :a => 2}
%{:a => 2, 2 => :b}
iex> %{map | :c => 3}
** (ArgumentError) argument error
length([1,[2],3]) = 3
** (CompileError) iex:1: illegal pattern
iex> keyword = []
[]
iex> map = %{}
%{}
iex> Dict.put(keyword, :a, 1)
[a: 1]
iex> Dict.put(map, :a, 1)
%{a: 1}
defmodule Math do
def sum(a, b) do
a + b
end
end
defmodule Math do
def zero?(0) do
true
end
def zero?(x) when is_number(x) do
false
end
end
Math.zero?(0) #=> true
Math.zero?(1) #=> false
Math.zero?([1,2,3])
#=> ** (FunctionClauseError)
defmodule Concat do
def join(a, b, sep \\ " ") do
a <> sep <> b
end
end
IO.puts Concat.join("Hello", "world") #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
defmodule Concat do
def join(a, b \\ nil, sep \\ " ")
def join(a, b, _sep) when is_nil(b) do
a
end
def join(a, b, sep) do
a <> sep <> b
end
end
IO.puts Concat.join("Hello", "world") #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
IO.puts Concat.join("Hello") #=> Hello
iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)
6
iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)
[2, 4, 6]
# キャプチャ構文
iex> Enum.reduce([1, 2, 3], 0, &+/2)
6
iex> Enum.map([1, 2, 3], &(&1 * 2))
[2, 4, 6]
iex> Enum.map(1..3, fn x -> x * 2 end)
[2, 4, 6]
iex> Enum.reduce(1..3, 0, &+/2)
6
1..100_000 |> Enum.map(&(&1 * 3)) |> Enum.filter(odd?) |> Enum.sum
> s = 1..1000000000 |> Stream.map(&(&1 * 3))
#Stream<[enum: 1..1000000000, funs: [#Function<45.113986093/1 in Stream.map/2>]]>
> Enum.take(s, 3)
[3, 6, 9]
iex> stream = Stream.cycle([1, 2, 3])
#Function<15.16982430/2 in Stream.cycle/1>
iex> Enum.take(stream, 10)
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
case {1, 2, 3} do
{4, 5 ,6} -> "この場合マッチしない"
{1, x, 3} -> "これにマッチする"
_ -> "どれでもマッチ"
end
# 2
send self(), {:abc, "dope"}
# {:abc, "dope"}
receive do
{:abc, msg} -> msg
{:woo, msg} -> "aaa"
end
# "dope"
receive do
{:wtf, msg} -> msg
{:woo, msg} -> "aaa"
after
1000 -> "1秒待ったけど何も来なかった..."
end
iex> send self(), :hello
:hello
iex> flush()
:hello
:ok
defmodule KV do
def start_link do
{:ok, spawn_link(fn -> loop(%{}) end)}
end
defp loop(map) do
receive do
{:get, key, caller} ->
send caller, Map.get(map, key)
loop(map)
{:put, key, value} ->
loop(Map.put(map, key, value))
end
end
end
case File.read(file) do
{:ok, body} -> # handle ok
{:error, r} -> # handle error
end
iex> IO.puts :stdio, "hello"
hello
:ok
iex> IO.puts Process.group_leader, "hello"
hello
:ok
defmodule Math do
alias Math.List, as: List
end
defmodule Math do
def plus(a, b) do
alias Math.List
# ...
end
def minus(a, b) do
# ...
end
end
iex> Integer.is_odd(3)
** (CompileError) iex:1: you must require Integer before invoking the macro Integer.is_odd/1
iex> require Integer
nil
iex> Integer.is_odd(3)
true
iex> x = 1
1
iex> case 10 do
...> ^x -> "Won't match"
...> _ -> "Will match"
...> end
iex> import List, only: [duplicate: 2]
nil
iex> duplicate :ok, 3
[:ok, :ok, :ok]
iex> is_atom(String)
true
iex> to_string(String)
"Elixir.String"
iex> :"Elixir.String"
String
iex> :lists.flatten([1,[2],3])
[1, 2, 3]
iex> mod = :lists
:lists
iex> mod.flatten([1,[2],3])
[1,2,3]
defmodule Foo do
defmodule Bar do
end
end
defmodule Elixir.Foo do
defmodule Elixir.Foo.Bar do
end
alias Elixir.Foo.Bar, as: Bar
end
defmodule Math do
@moduledoc """
Provides math-related functions.
## Examples
iex> Math.sum(1, 2)
3
"""
@doc """
Calculates the sum of two numbers.
"""
def sum(a, b), do: a + b
end
defmodule MyServer do
@initial_state %{host: "147.0.0.1", port: 3456}
IO.inspect @initial_state
end
defmodule User do
defstruct name: "john", age: 27
end
> is_map(%User{})
true
iex> john = %User{}
%User{age: 27, name: "john"}
iex> john.name
"john"
iex> meg = %{john | name: "meg"}
%User{age: 27, name: "meg"}
iex> %{meg | oops: :field}
** (ArgumentError) argument error
iex> case {1, 2, 3} do
...> {1, x, 3} when x > 0 -> "マッチする"
...> _-> "マッチしない"
...> end
iex> %User{name: name} = john
%User{age: 27, name: "john"}
iex> name
"john"
iex> %User{} = %{}
** (MatchError) no match of right hand side value: %{}
iex> john.__struct__
User
defprotocol Blank do
@doc "Returns true if data is considered blank/empty"
def blank?(data)
end
# 整数は決してブランクにならない - Integers are never blank
defimpl Blank, for: Integer do
def blank?(_), do: false
end
# 空リストのときだけブランクになる - Just empty list is blank
defimpl Blank, for: List do
def blank?([]), do: true
def blank?(_), do: false
end
# 空のマップのときだけブランクになる - Just empty map is blank
defimpl Blank, for: Map do
# Keep in mind we could not pattern match on %{} because
# it matches on all maps. We can however check if the size
# is zero (and size is a fast operation).
def blank?(map), do: map_size(map) == 0
end
# アトムがfalseとnilのときだけブランクになる - Just the atoms false and nil are blank
defimpl Blank, for: Atom do
def blank?(false), do: true
def blank?(nil), do: true
def blank?(_), do: false
end
iex> Blank.blank?(0)
false
iex> Blank.blank?([])
true
iex> Blank.blank?([1, 2, 3])
false
defimpl Blank, for: User do
def blank?(_), do: false
end
defprotocol Blank do
@fallback_to_any true
def blank?(data)
end
defimpl Blank, for: Any do
def blank?(_), do: false
end
iex> Enum.map [1, 2, 3], fn(x) -> x * 2 end
[2,4,6]
iex> Enum.reduce 1..3, 0, fn(x, acc) -> x + acc end
6
iex> to_string :hello
"hello"
iex> case :ok do
...> :error -> "Won't match"
...> end
# ** (CaseClauseError) no case clause matching: :ok
iex> "age: #{25}"
"age: 25"
iex> tuple = {1, 2, 3}
{1, 2, 3}
iex> "tuple: #{tuple}"
** (Protocol.UndefinedError) protocol String.Chars not implemented for {1, 2, 3}
iex> "tuple: #{inspect tuple}"
"tuple: {1, 2, 3}"
iex> :foo + 1
** (ArithmeticError) bad argument in arithmetic expression
:erlang.+(:foo, 1)
iex> raise "oops"
** (RuntimeError) oops
iex> raise ArgumentError, message: "invalid argument foo"
** (ArgumentError) invalid argument foo
iex> defmodule MyError do
iex> defexception message: "default message"
iex> end
iex> raise MyError
** (MyError) default message
iex> raise MyError, message: "custom message"
** (MyError) custom message
iex> try do
...> raise "oops"
...> rescue
...> e in RuntimeError -> e
...> end
%RuntimeError{message: "oops"}
iex> try do
...> Enum.each -50..50, fn(x) ->
...> if rem(x, 13) == 0, do: throw(x)
...> end
...> "Got nothing"
...> catch
...> x -> "Got #{x}"
...> end
"Got -39"
iex> spawn_link fn -> exit(1) end
#PID<0.56.0>
** (EXIT from #PID<0.56.0>) 1
iex> f = fn
...> x, y when x > 0 -> x + y
...> x, y -> x * y
...> end
#Function<12.71889879/2 in :erl_eval.expr/5>
iex> f.(1, 3)
4
iex> f.(-1, 3)
-3
iex> try do
...> exit "I am exiting"
...> catch
...> :exit, _ -> "not really"
...> end
"not really"
try do
raise "oops"
after
IO.puts "あふたー"
end
あふたー
** (MatchError) no match of right hand side value: {:error, :enoent}
iex> for n <- [1, 2, 3, 4], do: n * n
[1, 4, 9, 16]
iex> for n <- 1..4, do: n * n
[1, 4, 9, 16]
iex> values = [good: 1, good: 2, bad: 3, good: 4]
iex> for {:good, n} <- values, do: n * n
[1, 4, 16]
iex> require Integer
iex> for n <- 1..4, Integer.is_odd(n), do: n * n
[1, 9]
for dir <- dirs,
file <- File.ls!(dir),
path = Path.join(dir, file),
File.regular?(path) do
File.rm!(path)
end
iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>>
iex> for <<r::8, g::8, b::8 <- pixels>>, do: {r, g, b}
[{213,45,132},{64,76,32},{76,0,0},{234,32,15}]
iex> for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>>
"helloworld"
iex> cond do
...> 2 + 2 == 5 ->
...> "This will not be true"
...> 2 * 2 == 3 ->
...> "Nor this"
...> 1 + 1 == 2 ->
...> "But this will"
...> true ->
...> "全部falseだった場合" #何もtrueにならないとエラーになるからこうする
...> end
"But this will"
iex> cond do
...> hd([1,2,3]) ->
...> "nilとfalse以外はtrue"
...> end
"nilとfalse以外はtrue"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment