You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The `performantTraversables` exercise has three problems:
1. It is not deterministic. People report (and I experienced it myself) that the result is sometime `true` and sometimes `false`.
2. You should not benchmark method calls like this. The JVM needs to warm up, there are a lot of optimizations going on. Use a microbenchmarking framework.
3. The comment states that you might receive a `StackOverflowError`. This is not true, as `reduceRight` is implemented based on `reduceLeft`, making it also tail recursive if `reduceLeft` is tail recursive.
I suggest to replace the exercise with another one demonstrating the relationship between the left and the right operation. The new exercise is deterministic. Also I removed the wrong comment about the `StackOverflowError`.
Copy file name to clipboardExpand all lines: src/main/scala/stdlib/Traversables.scala
+12-16Lines changed: 12 additions & 16 deletions
Original file line number
Diff line number
Diff line change
@@ -511,23 +511,19 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin
511
511
intList.min should be(res3)
512
512
}
513
513
514
-
/** You would choose `foldLeft`/`reduceLeft` or `foldRight`/`reduceRight` based on your mathematical goal. One other reason for deciding is performance - `foldLeft` generally has better performance since it uses tail recursion. This exercise will either work fine or you will receive a `StackOverflowError`:
514
+
/** The naive recursive implementation of `reduceRight` is not tail recursive and would lead to a stack overflow if used on larger traversables.
515
+
* However, `reduceLeft` can be implemented with tail recursion.
516
+
*
517
+
* To avoid the potential stack overflow with the naive implementation of `reduceRight` we can easily implement it based on `reduceLeft` by reverting the list and the inverting the reduce function.
518
+
* The same applies for folding operations.
519
+
*
520
+
* There is also a `reduce` (and `fold`) available, which works exactly like `reduceLeft` (and `foldLeft`) and it should be the prefered method to call unless there is a strong reason to use `reduceRight` (or `foldRight`).
0 commit comments