I have to write a function, that returns true if a given list is sorted in ascending order. The empty and 1-element lists are sorted. Also, [5,12,12] should return true.
I’ve written a function that seems to work:
let rec isSorted (l: int list) =
match l with
| [] -> true
| [x] -> true
| [x;y] -> x <= y
| x::y::xr -> if x > y then false else isSorted([y] @ xr);
But it seems a bit off… I’m thinking there must be an easier way to do this? I hate that I have to match 4 cases, but I cant figure out how to make it any smarter.
Any better solutions?
Well, never say
when
will do just as well. (In general,
@is a code smell.)Kinda nitpicky, but the last line could be
and save you from doing any allocation.
Now, do you need the third case? What happens if you remove it?