0

I was trying to check if a list is sorted in PolyML. The list is not of the built-in type but was defined by me as :

datatype list = empty | cons of int*list; 

I don't know how to check for both increasing and decreasing order, so for now I've restricted myself to increasing order (any hint to a more general solution are welcome!).

So my approach is as follows :

local
    fun sortedIncreasing (empty) = 1000
    |   sortedIncreasing (cons(v,l)) = if(v < sortedIncreasing(l)) then v else Int.minInt
in
    fun isSortedInc (empty) = true
    |   isSortedInc (cons(v,l)) = if (sortedIncreasing(cons(v,l)) = Int.minInt) then false else true
end;   

First thing Int.minInt is not of type Int so I have a type mismatch. How could I solve that?
Secondly I'm afraid this approach is quite naive, how would I solve the problem in a better way?

Thanks for your time, have a good day!

MFranc
  • 366
  • 1
  • 2
  • 14

1 Answers1

0

This problem could be solved using a more general approach whereby the sorted function takes a comparator as a parameter.

A possible implementation of this might look like:

fun sorted comp empty = true
  | sorted comp (cons(x,empty)) = true
  | sorted comp (cons(x,cons(y,xs))) =
        (comp (x,y)) andalso (sorted comp (cons(y,xs)));

In this way, you can check that the list is sorted according to an arbitrary ordering as defined by the comparator. For example, you could define a function sortedIncreasing as:

val sortedIncreasing = sorted op<=;

Here's a full runnable example to demonstrate the point:

datatype mylist = empty | cons of int * mylist;

fun sorted comp empty = true
  | sorted comp (cons(x,empty)) = true
  | sorted comp (cons(x,cons(y,xs))) =
        (comp (x,y)) andalso (sorted comp (cons(y,xs)));

fun fromList [] = empty
  | fromList (x::xs) = cons(x, fromList xs);

val a = fromList [1,2,3,4,5,6];
val b = fromList [6,5,4,3,2,1];
val c = fromList [1,3,2,4,5,6];

val sortedIncreasing = sorted op<=;
val sortedDecreasing = sorted op>=;

sortedIncreasing a; (* val it = true: bool *)
sortedDecreasing a; (* val it = false: bool *)
sortedIncreasing b; (* val it = false: bool *)
sortedDecreasing b; (* val it = true: bool *)
sortedIncreasing c; (* val it = false: bool *)
sortedDecreasing c; (* val it = false: bool *)
maxcampman
  • 156
  • 4