Open14

Elixir quiz

tatotato

[1 | [2 | [3 | []]]]

答え

[1, 2, 3]

[1, [2], [[3]]] |> List.flatten()

答え

[1, 2, 3]

[1, [2], [[3]]] |> Enum.flat_map(& &1)

答え

** (Protocol.UndefinedError) protocol Enumerable not implemented for 1 of type Integer

[[], [2], [[3]]] |> Enum.flat_map(& &1)

答え

[2, [3]]

tatotato
defmodule Quiz do
  def which(0), do: "zero"
  def which(n) when n == 0, do: "guard zero"
  def which(n), do: n
end

Quiz.which(0.0)
答え

"guard zero"

0 == 0.0 #=> true
0 === 0.0 #=> false

tatotato

iex> %{c: 1, b: 2, a: 3}

答え

%{a: 3, b: 2, c: 1}

Map.values(%{a: 1, c: 3, b: 2})

答え

[1, 2, 3]
(蛇足かな)

Map.take(%{a: 1, b: 2, c: 3}, [:c, :b, :a])

答え

%{a: 1, b: 2, c: 3}

Map.get(%{a: nil}, :a, 1)

答え

nil

Map.put_new(%{a: nil}, :a, 1)

答え

%{a: nil}

tatotato

Enum.into([a: 1, a: 2], %{})

答え

%{a: 2}

Enum.into(%{a: 1}, %{a: 2})

答え

%{a: 1}

Keyword.get([a: 1, a: 2], :a)

答え

1

tatotato

Regex.scan(~r/./, "abcde")

答え

[["a"], ["b"], ["c"], ["d"], ["e"]]

Regex.scan(~r/.*/, "abcde")

答え

[["abcde"], [""]]

Regex.scan(~r/.*?/, "abcde")

答え

[[""], ["a"], [""], ["b"], [""], ["c"], [""], ["d"], [""], ["e"], [""]]

tatotato
map = %{a: 1, b: 2}
# 次の3つ
map.a
map[:c]
map.c
答え
1
nil
** (KeyError) key :c not found in: %{a: 1, b: 2}
%{map | c: 3}
答え
** (KeyError) key :c not found in: %{a: 1, b: 2}
tatotato

10 / 2

答え

5.0

div(10, 2)

答え

5

div(10, 2.0)

答え

** (ArithmeticError) bad argument in arithmetic expression

tatotato
"My name is " <> <<what::binary>> = "My name is Hoge"
答え

"Hoge"

<<what::binary>> <> " is Hoge" = "My name is Hoge"
答え

(CompileError)

<<what::binary-7>> <> " is Hoge" = "My name is Hoge"
答え

"My name"

tatotato

Agent.cast

defmodule Sample do
  use Agent
  def start, do: Agent.start_link(fn -> "Hello" end, name: __MODULE__)
end

Sample.start()
Agent.cast(Sample, fn msg ->
  IO.inspect(msg, label: "First")
  :timer.sleep(1000)
  IO.inspect(msg, label: "First")
  "First done"
end)
Agent.cast(Sample, fn msg ->
  IO.inspect(msg, label: "Second")
  "Second done"
end)
IO.puts "END"
IO.gets "" # 処理待ちのお約束
答え
END
First: "Hello"
First: "Hello"
Second: "First done"
  • ENDと最初の First: "Hello" は前後する可能性がありそう
tatotato

Nx

Nx.iota({2, 2})[[0..-1//1, 1]]

答え
#Nx.Tensor<
  s64[2]
  [1, 3]
>

Nx.iota({2, 2})[[0..-1//1, 1..1//1]]

答え
#Nx.Tensor<
  s64[2][1]
  [
    [1],
    [3]
  ]
>
tatotato

バイナリまわり

is_binary("abc")

答え

true

is_binary(<<97, 98, 99>>)

答え

true

is_binary('abc')

答え

false

String.codepoints("abc") == 'abc'

答え

false

コードポイントに分けてくれるだけで、要素はStringのままなのでfalse