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

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

Where Next?

Popular in Questions Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement