2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

草莽Erlang ── 21. lists:foldl

Last updated at Posted at 2023-01-11

口で言うより行うことがErlang習得への近道と信じています。

lists:foldl

foldl(fun((term, term) -> term), term, [term]) -> term
foldl(fun((要素, 累積IN) -> 累積OUT), 累積の初期値, リスト) -> 累積の最終値

他のプログラミング言語でいうreduce関数のようなものです。リストを1つの値に絞り込むことができます。

  • 各要素 に対して与えられた関数を適用し累積(アキュムレータ)を更新
  • 累積は次の関数呼び出しに渡される
  • 最後に、累積の最終値が返される
  • リストが空の場合、累積初期値が返される

馴染みのない方は闘魂Elixirの図を眺めてみるとなんとなく感覚が掴めるかもしれません。

練習してみます。

% 和を求める
> lists:foldl(fun (X, Acc) -> Acc + X end, 0, [1, 2, 3, 4]).
10

> lists:foldl(fun (X, Acc) -> Acc + X end, 0, []).
0

listsモジュールには他にもリスト処理のための関数がたくさんあります。

Elixirにも挑戦したい

闘魂ElixirシリーズとElixir Schoolがオススメです。

2
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?