Packages
altworx_runbox
17.2.0
25.0.0
24.0.0
23.1.0
23.0.0
22.2.0
22.1.0
22.0.0
21.2.0
21.1.2
21.1.1
21.1.0
21.0.0
20.0.0
19.0.0
18.0.0
17.2.0
17.1.0
17.0.1
17.0.0
16.2.0
16.1.0
16.0.0
15.0.0
14.1.0
14.0.1
14.0.0
13.0.3
13.0.2
13.0.1
13.0.0
12.1.0
12.0.0
11.0.1
11.0.0
10.0.0
9.0.0
8.0.0
7.0.1
7.0.0
6.0.0
5.0.0
4.0.0
3.0.0
2.1.0
2.0.0
1.4.1
1.4.0
1.3.0
1.2.0
1.1.0
1.0.0
0.1.3
0.1.2
0.1.1
0.1.0
Runbox is a library for running Altworx scenarios.
Current section
Files
Jump to
Current section
Files
lib/runbox/utils/traversal.ex
defmodule Runbox.Utils.Traversal do
@moduledoc group: :utilities
@doc """
Performs a depth-first pre-order traversal on the given `value`.
Transforms each subterm via the given `fun`, before descending into its descendants.
## Example
iex> Traversal.prewalk(
...> [1, 2, :pi, 4, %{5 => [6, 7]}],
...> fn
...> x when is_integer(x) -> Integer.to_string(x)
...> x when is_list(x) -> Enum.reverse(x)
...> x -> x
...> end
...> )
[%{"5" => ["7", "6"]}, "4", :pi, "2", "1"]
"""
def prewalk(value, fun) do
value
|> fun.()
|> prewalk_children(fun)
end
defp prewalk_children(list, fun) when is_list(list) do
Enum.map(list, &prewalk(&1, fun))
end
defp prewalk_children(tuple, fun) when is_tuple(tuple) do
tuple
|> Tuple.to_list()
|> Enum.map(&prewalk(&1, fun))
|> List.to_tuple()
end
defp prewalk_children(%module{} = struct, fun) do
struct
|> Map.from_struct()
|> Map.new(fn {key, value} ->
{prewalk(key, fun), prewalk(value, fun)}
end)
|> Map.put(:__struct__, module)
end
defp prewalk_children(map, fun) when is_map(map) do
Map.new(map, fn {key, value} ->
{prewalk(key, fun), prewalk(value, fun)}
end)
end
defp prewalk_children(scalar, _fun) do
scalar
end
end