Search code examples
listf#maxfold

F# list.fold maximum


I wanted to use a new built-in function (list.fold) in F#. I have a list with numbers in it and I have to return the maximum of it. If the list is empty it should 0. I tryied to solve it this way:

let max a b : Nat = if a > b then a else b
let maxofList = List.fold max
let maximum (xs: Nat list): Nat = maxofList xs 

I can't compile it and I don't know how to solve it in another way, maybe I just don't really understand how the built-in functions works. The input looks like this:

maximum [12N; 4N; 67N; 5N] = 67N

Solution

  • As noted in comments, it is slightly confusing that you are using the Nat type - this is a custom type defined somewhere in a library that you are using, not a standard F# type. You should be able to get things to work with your Nat type, but I'll just simplify things and use an integer.

    Now, your code is almost right. The only problem is that List.fold takes a function to combine the current state with the next element (that's your max) but it also needs an initial state. This should be a number that is smallest than anything else in your list. If you just have positive numbers, you can use zero:

    let max a b : int = if a > b then a else b
    let maxofList = List.fold max 0 // Added '0' as an extra parameter here!
    let maximum (xs: int list): int = maxofList xs
    

    In your case, this will likely be 0N. Alternatively, you could use List.reduce which takes the first element of the list as an initial value and fails if the list is empty:

    let maxofList = List.reduce max