Skip to content

Instantly share code, notes, and snippets.

@chrismccord
Created August 28, 2014 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismccord/9abe57badf3e4c0be724 to your computer and use it in GitHub Desktop.
Save chrismccord/9abe57badf3e4c0be724 to your computer and use it in GitHub Desktop.
Elixir reduce while
defmodule Reduce do
def while(collection, initial, while_func, reduce_func) do
try do
Enum.reduce collection, initial, fn element, acc ->
if while_func.(element, acc) do
reduce_func.(element, acc)
else
throw {:halt, acc}
end
end
catch
:throw, {:halt, acc} -> acc
end
end
end
iex(4)> Reduce.while [1, 2, 3], 0, fn _, _ -> true end, fn x, acc -> x + acc end
6
iex(5)> Reduce.while [1, 2, 3], 0, fn x, _ -> x < 3 end, fn x, acc -> x + acc end
3
iex(6)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment