Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I personally prefer the <code>/:</code> and <code>:\</code> forms of <code>foldLeft</code> and <code>foldRight</code>. Two reasons:</p> <ol> <li><p>It has a more natural feel because you can see that you are pushing a value into the left/right of a collection and applying a function. That is</p> <pre><code>(1 /: ints) { _ + _ } ints.foldLeft(1) { _ + _ } </code></pre> <p>Are both equivalent, but I tend to think the former emphasises my intuition as to what is happening. If you want to know <em>how</em> this is happening (i.e. the method appears to be called on the value 1, not the collection), it's because methods ending in a colon are right-associative. This can be seen in <code>::</code>, <code>+:</code> etc etc elsewhere in the standard library. </p></li> <li><p>The ordering of the <code>Function2</code> parameters is the same order as the folded element and that which is folded into:</p> <pre><code> (b /: as) { (bb, a) =&gt; f(bb, a) } // ^ ^ ^ ^ // ^ ^ ^ ^ // B A B A </code></pre> <p>Better in every way than:</p> <pre><code>as.foldLeft(b) { (bb, a) =&gt; f(bb, a) } </code></pre> <p>Although I admit that this was a far more important difference in the era before decent IDE support: nowadays IDEA can tell me what function is expected with a simple CTRL-P</p></li> </ol> <p>I hope it should also be obvious how <code>:\</code> works with foldRight - it's basically exactly the same, except that the value appears to be being pushed in from the right hand side. I must say, I tend to steer well clear of <code>foldRight</code> in scala because of how it is implemented (i.e. wrongly).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload