vegabook

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 Switch mode

sabiwara

sabiwara

Elixir Core Team

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

sabiwara

Elixir Core Team

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

adamu

Did you just tell the guy who wrote it to look it up? :grinning_face_with_smiling_eyes:

Eiji

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]}

Last Post!

vegabook

vegabook

yeah I’m gonna say 90% of Elixir devs know what Racket is.

BTW if I may say, this ~w[a b c]a is a complete code-golf gratuitous overcomplication which doesn’t even save a single keystroke. You should refrain from trying to look clever because it detracts from your otherwise decent points.

Merry Christmas to you too!

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement