[Solved] How do I get the max value from a list with a function that takes two arguments?


A simple recursive solution:

let max2 x y = if x < y then y else x

let max_list list =
  let rec loop hi list = 
     match list with 
     | h::t -> let hi = max2 h hi
               loop hi t
     | []   -> hi
  match list with
  | h::t -> loop h t
  | []   -> invalidArg "list" "Empty list"

Test in FSI:

> max_list [3;4;5;1;2;9;0];;
val it : int = 9

For each element in the list, compare it to the previous highest (‘hi’). Pass the new highest and the rest of the list into the loop function, until the input list is empty. Then just return ‘hi’.

2

solved How do I get the max value from a list with a function that takes two arguments?