aboutsummaryrefslogtreecommitdiff
path: root/plugins/syntax/NatSyntaxViaZ.v
blob: adee347d9025e13effd3ce1422eaae19d2510002 (plain)
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
Declare ML Module "numeral_notation_plugin".
Require Import BinNums.

(** ** Parsing and Printing digit strings as type nat *)

Fixpoint pos_pred_double x :=
  match x with
  | xI p => xI (xO p)
  | xO p => xI (pos_pred_double p)
  | xH => xH
  end.

Definition nat_of_Z x :=
  match x with
  | Z0 => Some O
  | Zpos p =>
      let fix iter p a :=
        match p with
        | xI p0 => a + iter p0 (a + a)
        | xO p0 => iter p0 (a + a)
        | xH => a
        end
      in
      Some (iter p (S O))
  | Zneg p => None
  end.

Fixpoint pos_succ x :=
  match x with
  | xI p => xO (pos_succ p)
  | xO p => xI p
  | xH => xO xH
  end.

Definition Z_succ x :=
  match x with
  | Z0 => Zpos xH
  | Zpos x => Zpos (pos_succ x)
  | Zneg x =>
      match x with
      | xI p => Zneg (xO p)
      | xO p => Zneg (pos_pred_double p)
      | xH => Z0
      end
  end.

Fixpoint Z_of_nat_loop n :=
  match n with
  | O => Z0
  | S p => Z_succ (Z_of_nat_loop p)
  end.

Definition Z_of_nat n := Some (Z_of_nat_loop n).

Numeral Notation nat nat_of_Z Z_of_nat : nat_scope
  (warning after 5000).