<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="355591" data-post-id="355591">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="jswanner" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/jswanner/120/24585_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  jswanner
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Maybe having a different example will help?</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Counter do
  defstruct current: 0

  def new, do: struct!(__MODULE__)

  defimpl Enumerable do
    def count(_), do: {:error, __MODULE__}
    def member?(_, _), do: {:error, __MODULE__}
    def slice(_), do: {:error, __MODULE__}

    def reduce(_counter, {:halt, acc}, _fun), do: {:halted, acc}
    def reduce(counter, {:suspend, acc}, fun), do: {:suspended, acc, &amp;reduce(counter, &amp;1, fun)}

    def reduce(counter, {:cont, acc}, fun) do
      reduce(update_in(counter.current, &amp;(&amp;1 + 1)), fun.(counter.current, acc), fun)
    end
  end
end

Counter.new()
|&gt; Enum.take(3)
# [0, 1, 2]
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="355591" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/enum-reduce-3-vs-enumerable-reduce-3/69268/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-355591" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="355591"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="355592" data-post-id="355592">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="James_E" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/James_E/120/36696_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  James_E
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="cevado" data-post="12" data-topic="69268">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cevado/48/40655_2.png" class="avatar"> cevado:</div>
<blockquote>
<p>“how to implement the enumerable protocol for this struct”</p>
</blockquote>
</aside>
<p>There’s really no X-Y problem, here; that is in fact <em>exactly</em> what I’m asking. I have a struct, and a clear definition of enumeration on it; I just can’t see how to warp that into the <code>Enumerable.reduce/3</code> callback shape.</p>
<hr>
<p>I implemented a Multiset class mainly as a <strong>didactic exercise</strong> and thought fully implementing the <code>Enumerable</code> protocol on it would be a great next step in that.</p>
<ul>
<li>implementing <code>count/1</code> was trivial;</li>
<li>implementing an efficient <code>member?/2</code> was elegant, once I thought to enforce <code>pos_integer()</code> invariant on the internal data;</li>
<li>doing <code>slice/1</code> in better than linear time took a few days of thinking, and a lot of trial and error, but I came out of it understanding more about both Elixir and Erlang;</li>
<li>but this last callback, <code>reduce/3</code>, just has me tied up. I <em>cannot</em> see the twisted logic behind its interface <em>per se</em>.</li>
</ul> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="355592" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/enum-reduce-3-vs-enumerable-reduce-3/69268/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-355592" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="355592"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="355599" data-post-id="355599">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="cevado" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cevado/120/40655_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  cevado
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>so explaining the Enumerable.reduce/3 protocol to be implemented, starting by unnesting it’s type signature:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">reduce(your_data_type, {:halt, accumulator}, reducer_fun) :: {:halted, accumulator}
reduce(your_data_type, {:suspend, accumulator}, reducer_fun) :: {:suspended, accumulator, continuation_fun}
reduce(your_data_type, {:cont, accumulator}, reducer_fun) :: recursion | {:done, accumulator}
</code></pre>
<p>so given your explanation on <code>:halt</code> scenarios you just gonna halt and return the accumulator:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def reduce(multiset, {:halt, acc}, _fun), do: {:halted, acc}
</code></pre>
<p>on suspension you gonna need to build a continuation function:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def reduce(multiset, {:suspend, acc}, fun) do
continuation = fn x -&gt; ... end
{:suspended, acc, continuation}
end
</code></pre>
<p>and in the <code>:cont</code> scenario you want two implementations one for when it’s the end of the multiset and one for when the recursion must keep going:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def reduce(%{&lt;"crazy pattern match"&gt;}, {:cont, acc}, _fun), do: {:done, acc}
def reduce(multiset, {:cont, acc}, fun) do
  {updated_multiset, next_term} = extract_next_term(multiset)
  reduce(updated_multiset, {:cont, fun.(next_term, acc)}, fun)
end
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="355599" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/enum-reduce-3-vs-enumerable-reduce-3/69268/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-355599" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="355599"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="355618" data-post-id="355618">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="LostKobrakai" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/LostKobrakai/120/3072_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  LostKobrakai
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p><code>Enum.reduce</code> and <code>Enumerable.reduce</code> are quite different functions operating at completly different levels of abstraction.</p>
<p><code>Enum.reduce</code> has no idea about how getting to the individual values of the input works. It relies completely on <code>Enumerable.reduce</code> to handle that for it. <code>Enumerable.reduce</code> sits behind – at least as a fallback – any <code>Enum</code> features though. So it cannot e.g. expect to always iterate through all values like <code>Enum.reduce</code>. Someone might use e.g. <code>Enum.take/2</code> to get just the first two items of an enumerable. Reduce shouldn’t need to iterate all items to get to the first two – to the contrary, as doing so would break infinite enumerables like streams.</p>
<p>I hope that at least explains a bit why <code>Enumerable.reduce</code> has a completely different API as it needs to be quite a bit more flexible.</p>
<p>To the other question: How do you define an enumerable relative to another enumerable you can transform to. That’s exactly what happens as part of the Enumerable implementation for maps: <a href="https://github.com/elixir-lang/elixir/blob/v1.18.2/lib/elixir/lib/enum.ex#L4967-L4988" class="inline-onebox" rel="nofollow">elixir/lib/elixir/lib/enum.ex at v1.18.2 · elixir-lang/elixir · GitHub</a></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="355618" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/enum-reduce-3-vs-enumerable-reduce-3/69268/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-355618" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="355618"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #15"></div>
  </section>
</div>
    <div class="postbit" id="355648" data-post-id="355648">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="cevado" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cevado/120/40655_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  cevado
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>just to correct this the last <code>cont</code> implementation was wrong…</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def reduce(%{&lt;"crazy pattern match"&gt;}, {:cont, acc}, _fun), do: {:done, acc}
def reduce(multiset, {:cont, acc}, fun) do
  {updated_multiset, next_term} = extract_next_term(multiset)
  reduce(updated_multiset, fun.(next_term, acc), fun)
end
</code></pre>
<p>it actually needs to be something like that… who decides to “wrap” in a <code>{:cont, acc}</code> or <code>{:halt, acc}</code> or <code>{:suspend, acc}</code> is the one using <code>Enumerable.reduce</code>.</p>
<aside class="quote no-group" data-username="LostKobrakai" data-post="16" data-topic="69268">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/lostkobrakai/48/3072_2.png" class="avatar"> LostKobrakai:</div>
<blockquote>
<p>Reduce shouldn’t need to iterate all items to get to the first two – to the contrary, as doing so would break infinite enumerables like streams.</p>
</blockquote>
</aside>
<p>Just  to add that if the intetion is to build a infinite enumerable it’s good to consider using <code>Stream.cycle/1</code>, <code>Stream.unfold/2</code> or <code>Stream.resource/3</code> to build a stream. It isn’t mandatory but comunicates better your intentions.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="355648" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/enum-reduce-3-vs-enumerable-reduce-3/69268/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-355648" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="355648"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>