在将OO映射到顺序Elixir(一般的函数式语言)时,您可以使用On模式,您可以创建一个数据对象(不是OO对象)并将其作为第一个参数传递给函数。这样,您就可以在每次通话中转换数据。
所以,你的api将形状像def link(maze, cell, bidirectional \\ true)
。使用地图来表示迷宫,将{x,y}
元组作为关键字,并使用地图作为值,以访问单个单元格并更新它们。
这里有一些未经测试的代码作为例子。
def Maze do
def new, do: %{cells: %{], links: %{}, start: {0,0}}}
def link(maze, cell1, cell2, bidirectional \\ true) do
maze
|> put_in([:links, cell2], true)
|> link_bidirectional(cell1, bidirectional)
end
defp link_bidirectional(maze, _, _, false), do: maze
defp link_bidirectional(maze, cell1, cell2, _) do
link(maze, cell2, cell1, false)
end
end
编辑:这里是用于连接
defmodule Maze do
def new do
%{cells: %{{0, 0} => Cell.create(0,0)}, tree: {{0, 0}, nil, nil}}
end
def new_cell(maze, row, column) do
# ignoring the tree for now
put_in(maze, [:cells, {row, column}], Cell.create(row, column))
end
def link(maze, cell1, cell2, bidirectional \\ true)
def link(maze, %{} = cell1, %{} = cell2, bidirectional) do
maze
|> update_in([:cells, cell1[:origin]], &(Cell.link(&1, cell2)))
|> do_bidirectional(cell1, cell2, bidirectional, &link/4)
end
def link(maze, {_, _} = pt1, {_, _} = pt2, bidirectional) do
link(maze, maze[:cells][pt1], maze[:cells][pt2], bidirectional)
end
def unlink(maze, %{} = cell1, %{} = cell2, bidirectional \\ true) do
maze
|> update_in([:cells, cell1[:origin]], &(Cell.unlink(&1, cell2)))
|> do_bidirectional(cell1, cell2, bidirectional, &unlink/4)
end
defp do_bidirectional(maze, _, _, false, _), do: maze
defp do_bidirectional(maze, cell1, cell2, _, fun) do
fun.(maze, cell2, cell1, false)
end
end
defmodule Cell do
def create(row,column), do: %{origin: {row, column}, links: %{}}
def link(self, cell) do
update_in(self, [:links, cell[:origin]], fn _ -> true end)
end
def unlink(self, cell) do
update_in(self, [:links], &Map.delete(&1, cell[:origin]))
end
end
iex(26)> Maze.new() |>
...(26)> Maze.new_cell(0,1) |>
...(26)> Maze.new_cell(1,0) |>
...(26)> Maze.link({0,0}, {0,1}) |>
...(26)> Maze.link({0,0}, {1,0})
%{cells: %{{0,
0} => %{links: %{{0, 1} => true, {1, 0} => true}, origin: {0, 0}},
{0, 1} => %{links: %{{0, 0} => true}, origin: {0, 1}},
{1, 0} => %{links: %{{0, 0} => true}, origin: {1, 0}}},
tree: {{0, 0}, nil, nil}}
iex(27)>
官能溶液