python.mlw 1.82 KB
Newer Older
1 2 3 4 5

module Python

  use import int.Int
  use import ref.Ref
6
  use array.Array as A
7

8 9
  (* Python's lists are actually resizable arrays, but we simplify here *)
  type list 'a = A.array 'a
10 11

  function ([]) (l: list 'a) (i: int) : 'a =
12
    A.get l i
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
13 14

  function len (l: list 'a) : int =
15 16 17 18 19
    A.length l

  let len (l: list 'a) : int
    ensures { result = len(l) }
  = A.length l
20 21

  let ([]) (l: list 'a) (i: int) : 'a
22
    requires { 0 <= i < A.length l }
23
    ensures  { result = l[i] }
24
  = A.([]) l i
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
25 26

  let ([]<-) (l: list 'a) (i: int) (v: 'a) : unit
27
    requires { 0 <= i < A.length l }
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
28
    writes   { l }
29 30
    ensures  { l = A.([<-]) (old l) i v }
  = A.([]<-) l i v
31 32 33

  val range (l u: int) : list int
    requires { l <= u }
34
    ensures  { A.length result = u - l }
35 36
    ensures  { forall i. l <= i < u -> result[i] = i }

37 38
  (* Python's division and modulus according are neither Euclidean division,
     nor computer division, but something else defined in
39 40
     https://docs.python.org/3/reference/expressions.html *)

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
  use import int.Abs
  use int.EuclideanDivision as E

  function div (x y: int) : int =
    let q = E.div x y in
    if y >= 0 then q else if E.mod x y > 0 then q-1 else q
  function mod (x y: int) : int =
    let r = E.mod x y in
    if y >= 0 then r else if r > 0 then r+y else r

  lemma div_mod:
    forall x y:int. y <> 0 -> x = y * div x y + mod x y
  lemma mod_bounds:
    forall x y:int. y <> 0 -> 0 <= abs (mod x y) < abs y
  lemma mod_sign:
    forall x y:int. y <> 0 -> if y < 0 then mod x y <= 0 else mod x y >= 0

  let (//) (x y: int) : int
    requires { y <> 0 }
    ensures  { result = div x y }
  = div x y

  let (%) (x y: int) : int
    requires { y <> 0 }
    ensures  { result = mod x y }
  = mod x y

  (* random.randint *)
69 70 71 72
  val randint (l u: int) : int
    requires { l <= u }
    ensures  { l <= result <= u }

73
end