概要
paiza.ioでelixirやってみた。
練習問題、やってみた。
練習問題
真理値表を表示する、インタープリターを書け。
コマンド
lut 3 -- 表、全体を定義、この場合 3
lin 2 -- 入力を定義、この場合 2
lout 1 -- 出力を定義、この場合 1
code 02 01 -- 入力と出力を定義、この場合 1と0なら、1
方針
- HTMLを使う。
- XORを書く。
lut 3
lin 2
lout 1
code 00 00
code 01 01
code 02 01
code 03 00
サンプルコード
defmodule Lut do
def start_link do
Agent.start_link(fn ->
%{l: 0, i: 0, o: 0, u: ""}
end, name: __MODULE__)
end
def lut(d) do
Agent.update(__MODULE__, fn v ->
{a, _} = Integer.parse(d)
%{v | l: a}
end)
end
def lin(d) do
Agent.update(__MODULE__, fn v ->
{a, _} = Integer.parse(d)
%{v | i: a}
end)
end
def lout(d) do
Agent.update(__MODULE__, fn v ->
{a, _} = Integer.parse(d)
%{v | o: a}
end)
end
def td(d, l) do
<<a>> = Base.decode16!(d)
a
|> Integer.to_string(2)
|> String.pad_leading(l, "0")
|> String.codepoints
|> Enum.map(fn i ->
"<td>" <> i <> "</td>"
end)
|> Enum.join()
end
def th(d) do
cond do
d == 1 ->
"<th>A</th>"
d == 2 ->
"<th>A</th><th>B</th>"
d == 3 ->
"<th>A</th><th>B</th><th>C</th>"
d == 4 ->
"<th>A</th><th>B</th><th>C</th><th>D</th>"
d == 5 ->
"<th>A</th><th>B</th><th>C</th><th>D</th><th>E</th>"
d == 6 ->
"<th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th>"
d == 7 ->
"<th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>G</th>"
d == 8 ->
"<th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>G</th><th>H</th>"
true ->
"not match"
end
end
def code(a, b) do
Agent.update(__MODULE__, fn v ->
str = "<tr>" <> td(a, v.i) <> " " <> td(b, v.o) <> "</tr>\n"
%{v | u: v.u <> str}
end)
end
def print() do
Agent.get(__MODULE__, fn v ->
IO.puts "<html>\n" <>
"""
<head>
<style>
table {
border-collapse: collapse;
}
td,th {
width: 30px;
border: 1px solid #000;
}
td {
text-align: center;
}
th {
background-color: #ccc;
}
</style>
</head>
<body>
<table>
""" <> "<tr>" <> th(v.i) <> th(v.o) <> "</tr>\n"
<> v.u <>
"</table>\n" <>
"</body>\n" <>
"</html>\n"
end)
end
end
defmodule Main do
def run(str) do
Enum.map(String.split(str, "\n"), fn l ->
s = String.split(l, " ")
cond do
Enum.at(s, 0) == "lut" ->
Lut.lut(Enum.at(s, 1))
Enum.at(s, 0) == "lin" ->
Lut.lin(Enum.at(s, 1))
Enum.at(s, 0) == "lout" ->
Lut.lout(Enum.at(s, 1))
Enum.at(s, 0) == "code" ->
Lut.code(Enum.at(s, 1), Enum.at(s, 2))
true ->
IO.puts ""
end
end)
Lut.print
end
end
Lut.start_link
Main.run("""
lut 3
lin 2
lout 1
code 00 00
code 01 01
code 02 01
code 03 00
""")
写真
成果物
以上。
