user305904
user305904

Reputation: 37

Working with non recursive lists

So I've been working with lists recently. I want to make a non recursive function name: int list -> int, that returns the difference between the highest and lowest number in a list. Is there a simple way of doing it with maybe list.fold, list.filter or list.exist?

I guess i can do it with list.max and list.min, but i want to try with some other functions.

Any help?

Upvotes: 0

Views: 69

Answers (1)

Olaf
Olaf

Reputation: 3986

To you mean something like this?

let distanceMinMax xs = 
    let (min,max) = List.fold (fun (min, max) x -> ((if x < min then x else min), (if x > max then x else max))) 
                              (System.Int32.MaxValue, System.Int32.MinValue)
                              xs
    (max - min)

Tested in the REPL:

> distanceMinMax [1;-1;2;5;7;-3];;
val it : int = 10

Hint: The empty list [] is not supported:

> distanceMinMax [];;
val it : int = 1

Upvotes: 2

Related Questions