vegabook
Pattern matching using [first | rest] in with clause seems to fail?
:digraph.add_edge gives unpredictable results when adding an edge, one only knows that the first element in the list will be :"$e"
I am trying to create an atomic :digraph.add_vertex+:digraph.add_edge+:dets.insert function. If any clauses in the with statement below fail, I need to roll back the previous ones. So if the last clause (:dets.insert) fails, I need to delete the vertex and the edge I just created. In order to do that, I need to destructure the return of the :digraph.add_edge function in the with clause, so that I can refer back to the created edge in the else part…
defp atomic_vedge({detspath, graph}, v, parent, meta, ts) do
# atomic add of a vertex and its edge to parent and save to dets
# if any stage fails preceding successes are rolled back
with {:addvertex, v} <- {:addvertex, :digraph.add_vertex(graph, v, meta)},
{:addedge, [:"$e" | rest]} <- {:addedge, :digraph.add_edge(graph, parent, v)},
{:insert, :ok} <-
{:insert, :dets.insert(detspath, {v, parent, ts, :vertedge, meta})} do
{:ok, {detspath, graph}}
else
{:addvertex, {:error, reason}} ->
{:error, reason}
{:addedge, {:error, reason}} ->
:digraph.del_vertex(graph, v)
{:error, reason}
{:insert, false} ->
:digraph.del_vertex(graph, v)
:digraph.del_edge(graph, [:"$e" | rest])
{:error, "dets vertex insert failed"}
end
end
However this is giving me an error when compiling:
Does this mean I cannot destructure into [first | rest] in a with statement? So I cannot track what the :digraph.add_edge returned in order to roll it back? It seems to be a problem with the [head | rest] part because the previous {:addvertex, v} doesn’t seem to cause a problem.
(the problem here btw is that :digraph is side-effecty. It doesn’t return a new graph each time because it uses ETS tables and that’s why I’m having to jump through these hoops)
Marked As Solved
sabiwara
This is a scope problem: rest is not available in the else clauses since it only gets defined when the pattern-matching succeeds.
Since you only need it in the insert case, you could pass it in the tuple maybe? {:insert, rest, :dets.insert(...)}
Regarding v, it is available in the parent scope, which is why you’re not getting the error (but it might not be the value of v you expect). Here is a minimal example:
iex(1)> with [x] <- 0, do: x, else: (_ -> x)
error: undefined variable "x"
iex:1
** (CompileError) cannot compile code (errors have been logged)
iex(1)> x = 1
1
iex(2)> with [x] <- 0, do: x, else: (_ -> x)
1
PS: Complex else clauses in with can be considered an anti-pattern, maybe this code would actually be clearer with simply nesting case? This way, the necessary variables from intermediate matches would be in scope.
Also Liked
sabiwara
I agree that avoiding over-nesting and splitting in small functions is good advice in general.
Regarding what the exact maximum nesting level should be, 1 feels quite opinionated. For example, it is quite easy to find examples that are nesting 2 or 3 case expressions within the Elixir codebase.
But like anything readability related, this is a very controversial topic, so I don’t think that there’s such a thing as a correct answer.
For the record, here is an opposite take embracing nesting over splitting functions (not necessarily agreeing but interesting to hear both sides).
adamu
Did you just tell the guy who wrote it to look it up? ![]()
Eiji
Elixir works as expected. The bug is in your code. Firstly let’s take a look at the warning. As it says the rest variable is not used inside do … else block. Secondly the value is assigned to variable only on success, so it cannot be used outside of do … else block which contains instructions for success scenario. Having above in mind the error message is also correct as there is no rest variable assigned for else … end block which contains an instructions when with matches fails.
You can still access this data, but this is a bit tricky … See a simplified example below:
# a simple list of atoms
list = ~w[a b c]a
# simplified with
with [a | bc] <- list,
# a tricky part i.e. we need to reassign the list for every next result
{true, _reassigned_list} <- {is_nil(a), list}
# possibly more clauses here with list reassignment
do
{"a is nil", a, bc}
else
# here a list is available not from success matching, but as a failed match result
{false, [a | bc]} -> {"a is not nil", a, bc}
end
The above code obviously returns:
{"a is not nil", :a, [:b, :c]}
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance











