Hello.
Today, I am going to show you how to effectively debug an Elixir program using dbg and pry.
To get started, first run:
If you look at lib/codewars_problem.ex, you will notice two dbg statements located within the file. dbg is used to stop execution of your code when combined with the invocation of iex --dbg pry. Let’s try it out:
$ iex --dbg pry lib/codewars_problem.ex
iex(1)> CodewarsProblem.solution(“AABBCCAABB")
Erlang/OTP 26 [erts-14.1.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit]
Interactive Elixir (1.15.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> CodewarsProblem.solution("AABBCCAABB")
Break reached: CodewarsProblem.solution/1 (lib/codewars_problem.ex:31)
28: prev = fetch(table, "prev")
29: result = fetch(table, "result")
30:
31: dbg([item, prev, result])
32:
33: if prev != item do
34: :ets.insert(table, {"prev", item})
iex(2)>
We’ve hit our first instance of dbg! Here, we can do whatever we like at the point of the dbg, including inspect variables:
iex(2)> item
65
iex(3)> prev
""
iex(4)> result
[]
iex(5)>
Now, type continue. You will be greeted with the printing of the updated variables from before:
iex(5)> continue
[item, prev, result] #=> [65, "", []]
Break reached: CodewarsProblem.solution/1 (lib/codewars_problem.ex:31)
28: prev = fetch(table, "prev")
29: result = fetch(table, "result")
30:
31: dbg([item, prev, result])
32:
33: if prev != item do
34: :ets.insert(table, {"prev", item})
iex(6)>
Here, you can again print out variables you are interested in. Hit up to scroll back to your last continue. Keep entering continue until the program completes.
If you scroll back up to the printed variables, you will notice result taking shape, but backwards. This is by design, as prepending to a linked list is less costly than appending. Of course, we then need to remember to Enum.reverse the list at the end, which we do.
Now try running CodewarsProblem.solution_without_ets(“AABBCCDDAABB”). What do you notice?
Hope you enjoyed this walk through Elixir debugging with me. Have a great day!
UPDATE: Due to a recent patch ( https://github.com/elixir-lang/elixir/pull/13309 ), you will soon be able to continue execution of your program with just c (instead of having to type out continue every time). This mimics gdb's behavior and should help with typing. Thanks, José and team!!