LoginSignup
2
0

More than 1 year has passed since last update.

(初学者向け)すべてiexで簡単に、Enum.mapの動きをデバッグで見たい(IO.inspect 編)

Last updated at Posted at 2022-12-31

Enum.mapの処理手順をすべてiexで動かしながら見たい場合

Enum.mapの処理手順をすべてiexで動かしながら、いかに手軽に確認できるかを考えました。
こんなパターンもいけるよ的な感じで書きます。

まず、やりたいのは、Enum.mapで送られてくる引数が何なのか出力したいという事です。
普通に関数で書けば実現できます。

iex> defmodule Ex2 do
iex>    def add(a) do
iex>      IO.inspect(a)
iex>      a + 1
iex>    end
iex> end
{:module, Ex2,
 <<70, 79, 82, 49, 0, 0, 5, 168, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 185,
   0, 0, 0, 20, 10, 69, 108, 105, 120, 105, 114, 46, 69, 120, 50, 8, 95, 95,
   105, 110, 102, 111, 95, 95, 10, 97, 116, ...>>, {:add, 1}}
iex(35)> Enum.map([1, 2, 3], &Ex2.add(&1))
1
2
3
[2, 3, 4]

まあ、当然、できます。

ただ、これだと関数つくの面倒なので、無名関数でなんとかしたいと考えました。
しかし、関数を書くように改行してコードを入れても、下記のようにエラーになります。

iex> Enum.map([1, 2, 3], &(IO.nspect(&1)
iex> &1 + 1))
** (CompileError) iex:36: block expressions are not allowed inside the capture operator &, got: IO.nspect(&1)
&1 + 1
    (elixir 1.14.0) src/elixir_expand.erl:538: :elixir_expand.expand_fn_capture/4
    (elixir 1.14.0) src/elixir_expand.erl:618: :elixir_expand.expand_arg/3
    (elixir 1.14.0) src/elixir_expand.erl:634: :elixir_expand.mapfold/5
    (elixir 1.14.0) src/elixir_expand.erl:848: :elixir_expand.expand_remote/8
    (elixir 1.14.0) src/elixir.erl:364: :elixir.quoted_to_erl/3
    (elixir 1.14.0) src/elixir.erl:274: :elixir.eval_forms/3
    (elixir 1.14.0) lib/module/parallel_checker.ex:100: Module.ParallelChecker.verify/1

どうしたらいいのか考えた結果、こういうのはどうかという事で、
以下のようにシンプルに書けました。

iex(2)> Enum.map([1, 2, 3], &(IO.inspect(&1) + 1))
1
2
3
[2, 3, 4]

ただ、これだと安直で不十分な感じもします。

本記事を見た偉大なElixirの先輩からdbgを教えてもらい、次の記事でさらに簡単な方法を模索していきたいと思います。

(初学者向け)すべてiexで簡単に、Enum.mapの動きをデバッグで見たい(dbg 編)に続く

2
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0