stage-2022/FinalExample.java

79 lines
2.1 KiB
Java

//////////////// FIRST CLASS TABLE /////////////////
class MinGetter extends Object {
/*
Returns the lesser of the two input integers
*/
Int min(Int a, Int b){
return a.lt(b).ite(a,b);
}
/*
Returns the minimum of the input list, None if the list is empty.
*/
Optional listMin(List a) {
return a.ensureFinite().isEmpty().ite(new None(), new Some(this.min((Int)this.listMin(a.tail).orElse(a.head), a.head)))
}
}
class Sort extends Object {
List sort(List in){
ensure(in).isEmpty().ite(in,minOnStart(in,(Int)((Some)new MinGetter().listMin(in)).value));
}
/*
Put the first occurence of 'min' in 'in' to the start of the list and sort the rest.
*/
List minOnStart(List in, Int min) {
return min::this.sort(in.removeFirst(min));
}
}
///////////////// SECOND CLASS TABLE /////////////////
class MaxGetter extends Object {
/*
Returns the bigger of the two input integers
*/
Int max(Int a, Int b){
return a.gt(b).ite(a,b);
}
/*
Returns the maximum of the input list, None if the list is empty
*/
Optional listMax(List a) {
return a.ensureFinite().isEmpty().ite(
new None(),
new Some(this.max((Int)this.listMax(a.tail).orElse(a.head), (Int)a.head)))
}
}
class Sort extends Object {
List sort(List in){
return this.sortAcc(in, []);
}
List sortAcc(List in, List acc) {
ensure(in).isEmpty().ite(acc,maxToEnd(in,((Some)new MaxGetter().listMax(in)).value));
}
/*
Removes max from in, applies sortAcc on the new list, and adds max to the accumulator.
*/
List maxToEnd(List in, Int max) {
return this.sortAcc(in.removeFirst(max), max::in.removeFirst(max));
}
}
///////////////// TEST INTERFACE /////////////////¨
// These three lines gives access to Integer construction
Int ()
S (Int)
S <: Int
// These three lines allows line construction
List ()
Cons (List, o)
Cons <: List
// These two lines allows use of the sort function,
// the only one whose implementation differs between the two class tables.
Sort ()
Sort: sort(List)