I am super stuck on trying to get a list of paths from a keyword list. Let me give you some examples:
# This keyword list..
[:a, :b]
# Should produce this:
[[:a], [:b]]
# This keyword list..
[:a, b: [:c, d: :e]]
# Should produce this:
[
[:a],
[:b, :c],
[:b, :d, :e],
]
# This keyword list..
[:a, b: [:c, d: [:e]]]
# Should produce this:
[
[:a],
[:b, :c],
[:b, :d, :e],
]
The closest I’ve come is the following:
defmodule Path do
def reduce_over_path([{field, path}], acc, fun) do
reduce_over_path(path, fun.(field, acc), fun)
end
def reduce_over_path([field], acc, fun) do
fun.(field, acc)
end
def reduce_over_path(fields = [_|_], acc, fun) do
Enum.map(fields, fn
field ->
reduce_over_path(field, acc, fun)
end)
end
def reduce_over_path({field, rest}, acc, fun) do
reduce_over_path(rest, fun.(field, acc), fun)
end
def reduce_over_path(field, acc, fun) do
fun.(field, acc)
end
end
Path.reduce_over_path([:a, b: [:c, d: :e]], [], fn x, acc -> acc ++ [x] end)
# Returns this:
[
[:a],
[ [:b, :c], [:b, :d, :e] ]
]
The problem is the nested array.
Do I need to use Dijkstra’s Shortest Path Algorithm or something?