How should I create a path from a list?
mmower opened this issue · comments
Matt Mower commented
I want to create a dynamic path.
data = [{:a, []}, {:b, [{:c, []}]}]
assert {:ok, {:c, []}} = view(data, path 1 / 1 / 0)
This is good, but what if I don't know [1, 1, 0] at compile time. I couldn't see anything documented about passing a list as a path, so I tried the following:
def make_path(elems) do
elems
|> Enum.map(fn elem -> path elem end)
|> Enum.reduce(fn p1, p2 -> p1 ~> p2 end)
end
assert {:ok, {:c, []}} = view(data, make_path([1, 1, 0]))
# fails with :error
Any idea what I am missing here?
Thanks.
Matt
Hissssst commented
Hi, @mmower, you're generally going the right way, but you have a bug in your code:
Try
|> Enum.reduce(fn p1, p2 -> p2 ~> p1 end)
Matt Mower commented
I was briefly baffled because my test cases had all used p1 ~> p2
and then it hit me that the accumulator goes second! Many thanks for the steer.
Hissssst commented
This happens to me every time when I switch to/from python (in python first argument is the accumulator and second is an item)