Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The recursive version is fine, but limited to <code>List</code> (with limited changes, it would work well on <code>LinearSeq</code>).</p> <p>If it was implemented in the standard library (would make sense) it would probably be done in <code>IterableLike</code> and have a completely imperative implementation (see for instance method <code>find</code>)</p> <p>You can interrupt the <code>foldLeft</code> with a <code>return</code> (in which case you need only the previous element and not boolean all along)</p> <pre><code>import Ordering.Implicits._ def isOrdered[A: Ordering](seq: Seq[A]): Boolean = { if (!seq.isEmpty) seq.tail.foldLeft(seq.head){(previous, current) =&gt; if (previous &gt; current) return false; current } true } </code></pre> <p>but I don't see how it is any better or even idiomatic than an imperative implementation. I'm not sure I would not call it imperative actually. </p> <p>Another solution could be </p> <pre><code>def isOrdered[A: Ordering](seq: Seq[A]): Boolean = ! seq.sliding(2).exists{s =&gt; s.length == 2 &amp;&amp; s(0) &gt; s(1)} </code></pre> <p>Rather concise, and maybe that could be called idiomatic, I'm not sure. But I think it is not too clear. Moreover, all of those methods would probably perform much worse than the imperative or tail recursive version, and I do not think they have any added clarity that would buy that. </p> <p>Also you should have a look at <a href="https://stackoverflow.com/q/7830471/754787">this question</a>.</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