Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the Maximum element in a list with pattern matching and recursion F#

Tags:

f#

f#-3.0

I'm trying to find the maximum element in a list without using List.Max for a school assignment using the below given template.

        let findMax l = 
        let rec helper(l,m) = failwith "Not implemented"

        match l with
        | [] -> failwith "Error -- empty list"
        | (x::xs) -> helper(xs,x) 

The only solution to the problem I can think of, atm is

        let rec max_value1 l =
          match l with
          |[] -> failwith "Empty List"
          |[x] -> x
          |(x::y::xs) ->  if x<y then max_value1 (y::xs)
                else max_value1 (x::xs)

        max_value1 [1; 17; 3; 6; 1; 8; 3; 11; 6; 5; 9];;    

Is there any way I can go from the function I built to one that uses the template? Thanks!

like image 952
SharpTooth Avatar asked Dec 08 '22 19:12

SharpTooth


1 Answers

Your helper function should do the work, the outer function just validates that the list is not empty and if it's not, calls the helper, which should be something like this:

let rec helper (l,m) = 
    match (l, m) with
    | []   , m -> m
    | x::xs, m -> helper (xs, max m x)

Note, that you since you're matching against the last argument of the function you can remove it and use function instead of match with:

let rec helper = function
    | []   , m -> m
    | x::xs, m -> helper (xs, max m x)
like image 165
Gus Avatar answered Dec 10 '22 08:12

Gus