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? :smile:

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

Eiji

Nesting case is also anti-pattern. Since Elixir version 1.12.0 (see Kernel.then/2) and especially after Livebook version 0.7 (see Interactive user interface to visualize and edit Elixir pipelines) my personal guilty pleasure is to use pipes often, really really often. :smiling_imp:

~w[a b c]a
|> then(fn
  [nil | bc] -> {:ok, {"a is nil", a, bc}}
  [a | bc] -> {:ok, {"a is not nil", a, bc}}
  data -> {:error, {"data does not match", data}}
end)

It’s much more clear than above with code since we see much better:

  1. On what data we are working (value in pipe)
  2. Every variable scope, so we understand the code much easier just looking at it
kokolegorille

kokolegorille

You might have an arrow too much… it should be fn instead of fn → :slight_smile:

Where I could use multiple heads anonymous function… I would prefer normal Module function with multiple heads.

But it’s just a question of taste

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New

We're in Beta

About us Mission Statement