I’d like to know the best way to scala-ize this idiom I do from time to time in Common Lisp. Can someone help suggest the cleanest/most-correct way to do it?
While performing an otherwise functional style iteration, I sometimes arrive upon a condition that allows me to short-circuit the rest of the calculation, and just return a result. E.g., If I’m multiplying a sequence of matrices, using some sort of reduce, and I arrive upon the zero matrix, I’d like to just return zero, and abort the rest of the iteration.
In Common Lisp it looks something like the following
(defun Foo (data) (reduce (lambda (total value) (if (some-predicate value) (RETURN-FROM Foo some-default) (combine total value))) data))
There is of course a similar way to do this from an arbitrary block, not just returning from the top level function. I can also do a similar type of RETURN-FROM from inside a local recursive function, where I return a particular value from the outer function (by name), which terminates the recursion.
(defun Foo (data) (labels ((local-fun (data acc) (cond ((null data) acc) ((some-predicate data) (RETURN-FROM Foo some-default)) (t (local-fun (cdr data) (combine (car data) acc)))))) (local-fun data 0.0)))
What is the correct way to do this in Scala? I can think of some complicated ways, such as raise an exception, and catch it with try. But perhaps there’s a less obscure way?