forked from epfl-lara/stainless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSort.scala
69 lines (58 loc) · 1.93 KB
/
InsertionSort.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* Copyright 2009-2021 EPFL, Lausanne */
import stainless.annotation._
import stainless.lang._
object InsertionSort {
sealed abstract class List
case class Cons(head:Int,tail:List) extends List
case class Nil() extends List
sealed abstract class OptInt
case class Some(value: Int) extends OptInt
case class None() extends OptInt
def size(l : List) : BigInt = (l match {
case Nil() => BigInt(0)
case Cons(_, xs) => 1 + size(xs)
}).ensuring(_ >= 0)
def contents(l: List): Set[Int] = l match {
case Nil() => Set.empty
case Cons(x,xs) => contents(xs) ++ Set(x)
}
def min(l : List) : OptInt = l match {
case Nil() => None()
case Cons(x, xs) => min(xs) match {
case None() => Some(x)
case Some(x2) => if(x < x2) Some(x) else Some(x2)
}
}
def isSorted(l: List): Boolean = l match {
case Nil() => true
case Cons(x, Nil()) => true
case Cons(x, Cons(y, ys)) => x <= y && isSorted(Cons(y, ys))
}
/* Inserting element 'e' into a sorted list 'l' produces a sorted list with
* the expected content and size */
def sortedIns(e: Int, l: List): List = {
require(isSorted(l))
l match {
case Nil() => Cons(e,Nil())
case Cons(x,xs) => if (x <= e) Cons(x,sortedIns(e, xs)) else Cons(e, l)
}
}.ensuring(res => contents(res) == contents(l) ++ Set(e)
&& isSorted(res)
&& size(res) == size(l) + 1
)
/* Insertion sort yields a sorted list of same size and content as the input
* list */
def sort(l: List): List = (l match {
case Nil() => Nil()
case Cons(x,xs) => sortedIns(x, sort(xs))
}).ensuring(res => contents(res) == contents(l)
&& isSorted(res)
&& size(res) == size(l)
)
@extern
def main(args: Array[String]): Unit = {
val ls: List = Cons(5, Cons(2, Cons(4, Cons(5, Cons(1, Cons(8,Nil()))))))
println(ls)
println(sort(ls))
}
}