Created
August 28, 2014 19:49
-
-
Save chrismccord/9abe57badf3e4c0be724 to your computer and use it in GitHub Desktop.
Elixir reduce while
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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