# Enum.reduce/2 throws Enum.EmptyError

**URL:** <https://forum.elixirforum.com/t/enum-reduce-2-throws-enum-emptyerror/9695>\
**Category:** Questions\
**Tags:** enumerables, how-to-question\
**Created:** [October 28, 2017, 11:44am UTC](https://forum.elixirforum.com/t/enum-reduce-2-throws-enum-emptyerror/9695 "2017-10-28T11:44:57Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![peerreynders](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/peerreynders/32/5826_2.png) [@peerreynders](https://forum.elixirforum.com/u/peerreynders)\
**Post date:** [October 28, 2017, 2:36pm UTC](https://forum.elixirforum.com/t/enum-reduce-2-throws-enum-emptyerror/9695/6 "2017-10-28T14:36:07Z")

</div>

> [@vfsoraki](#):
>
> Using Enum.reduce/3 is not elegant:

My choice would have been:

```elixir
defmodule Demo do
  def run(a_list, default_value) do
    iterator = fn
      x, ^default_value -> x
      x, win when win < x -> x
      _, win -> win
    end
    Enum.reduce(a_list, default_value, iterator)
  end
end

IO.inspect (Demo.run [], :no_winner)
IO.inspect (Demo.run [1,2,3], :no_winner)
IO.inspect (Demo.run [3,1,2], :no_winner)

```

```bash
$ elixir demo.exs
:no_winner
3
3

```

Of course intercepting the empty case before it gets to the `reduce` is more “efficient” (though by all accounts pattern matching is pretty fast) and ultimately creates the scenario that `reduce/2` was designed for - i.e. it already has been established that the enumerable has at least one item (which doesn’t need to be evaluated by the function).

```elixir
defmodule Demo2 do
  def reduce([h|t],f) do
    Enum.reduce(t,h,f)
  end
end

fun = fn (x, acc) -> x * 2 + acc end
IO.inspect (Enum.reduce [3,2,1],0,fun)
IO.inspect (Demo2.reduce [3,2,1],fun)
IO.inspect (Enum.reduce [3,2,1],fun)

```

```bash
$ elixir demo2.exs
12
9
9

```

---

_[View the full topic](https://forum.elixirforum.com/t/enum-reduce-2-throws-enum-emptyerror/9695)._
