on master help sign in
Merge pull request #4812 from nickdrozd/factorial
10fd4e7Niklas Larsson
libs/contrib/Data/Nat/Fact.idrnew file+56
@@ -0,0 +1,56 @@
1+||| Properties of factorial functions.
2+module Data.Nat.Fact
3+
4+%access public export
5+
6+%default total
7+
8+||| Recursive definition of factorial.
9+factRec : Nat -> Nat
10+factRec Z = 1
11+factRec (S k) = (S k) * factRec k
12+
13+||| Tail-recursive accumulator for factItr.
14+factAcc : Nat -> Nat -> Nat
15+factAcc Z acc = acc
16+factAcc (S k) acc = factAcc k $ (S k) * acc
17+
18+||| Iterative definition of factorial.
19+factItr : Nat -> Nat
20+factItr n = factAcc n 1
21+
22+----------------------------------------
23+
24+||| Multiplicand-shuffling lemma.
25+multShuffle : (a, b, c : Nat) -> a * (b * c) = b * (a * c)
26+multShuffle a b c =
27+ rewrite multAssociative a b c in
28+ rewrite multCommutative a b in
29+ sym $ multAssociative b a c
30+
31+||| Multiplication of the accumulator.
32+factAccMult : (a, b, c : Nat) ->
33+ a * factAcc b c = factAcc b (a * c)
34+factAccMult _ Z _ = Refl
35+factAccMult a (S k) c =
36+ rewrite factAccMult a k (S k * c) in
37+ rewrite multShuffle a (S k) c in
38+ Refl
39+
40+||| Addition of accumulators.
41+factAccPlus : (a, b, c : Nat) ->
42+ factAcc a b + factAcc a c = factAcc a (b + c)
43+factAccPlus Z _ _ = Refl
44+factAccPlus (S k) b c =
45+ rewrite factAccPlus k (S k * b) (S k * c) in
46+ rewrite sym $ multDistributesOverPlusRight (S k) b c in
47+ Refl
48+
49+||| The recursive and iterative definitions are the equivalent.
50+factRecItr : (n : Nat) -> factRec n = factItr n
51+factRecItr Z = Refl
52+factRecItr (S k) =
53+ rewrite factRecItr k in
54+ rewrite factAccMult k k 1 in
55+ rewrite multOneRightNeutral k in
56+ factAccPlus k 1 k