Finding a max in an unsorted array with imperative code is quite straight forward
e.g. in Java (I'm sure it can be written better, only used for illustration purposes)
public class Main {
public static void main(String[] args) {
int[] array = {1,3,5,4,2};
int max = findMax(array);
System.out.println(max);
}
public static int findMax(int[] array){
int max = Integer.MIN_VALUE; //or array[0], but it requires a null check and I want to keep it simple :)
for (int i = 0, size = array.length; i < size ; i++) {
int current = array[i];
if(current > max) max = current;
}
return max;
}
}
What is the functional way of doing it? e.g.
- without mutable variables (e.g. make max be a
valin Scala /finalin Java) - without looping (e.g. use recursion, tail preferred)
In Scala's sources I saw it was done using recudeLeft, which seems quite clever
def max[B >: A](implicit cmp: Ordering[B]): A = {
if (isEmpty)
throw new UnsupportedOperationException("empty.max")
reduceLeft((x, y) => if (cmp.gteq(x, y)) x else y)
}
But let's say I don't have (for some reason) reduce / reduceLeft available / implemented (And I don't want / can't implement it for some reason, i.e. I'm working with plain Java)
What is the "idiomatic" functional way to do a max without relying on other functional methods (e.g. how would I implement it in bare bones Java for example, but with the functional paradigm in mind)
Answers can be with any language (Java / Scala preferred though)