Debian Codegraph @

src/Tactic/RingSolver/Core/Polynomial/Semantics.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- "Evaluating" a polynomial, using Horner's method.
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 open import Tactic.RingSolver.Core.Polynomial.Parameters
10
11 module Tactic.RingSolver.Core.Polynomial.Semantics
12 {r₁ r₂ r₃ r₄}
13 (homo : Homomorphism r₁ r₂ r₃ r₄)
14 where
15
16 open import Data.Nat.Base using (ℕ; suc; zero; _≤′_; ≤′-step; ≤′-refl)
17 open import Data.Vec.Base using (Vec; []; _∷_; uncons)
18 open import Data.List.Base using ([]; _∷_)
19 open import Data.Product.Base using (_,_; _×_)
20 open import Data.List.Kleene using (_+; _*; ∹_; _&_; [])
21
22 open Homomorphism homo hiding (_^_)
23 open import Tactic.RingSolver.Core.Polynomial.Base from
24 open import Algebra.Properties.Semiring.Exp.TCOptimised semiring
25
26 drop : ∀ {i n} → i ≤′ n → Vec Carrier n → Vec Carrier i
27 drop ≤′-refl xs = xs
28 drop (≤′-step i+1≤n) (_ ∷ xs) = drop i+1≤n xs
29
30 drop-1 : ∀ {i n} → suc i ≤′ n → Vec Carrier n → Carrier × Vec Carrier i
31 drop-1 si≤n xs = uncons (drop si≤n xs)
32 {-# INLINE drop-1 #-}
33
34 _*⟨_⟩^_ : Carrier → Carrier → ℕ → Carrier
35 x *⟨ ρ ⟩^ zero = x
36 x *⟨ ρ ⟩^ suc i = ρ ^ (suc i) * x
37 {-# INLINE _*⟨_⟩^_ #-}
38
39 ------------------------------------------------------------------------
40 -- Evaluation
41 ------------------------------------------------------------------------
42 -- Why do we have three functions here? Why are they so weird looking?
43 --
44 -- These three functions are the main bottleneck for all of the proofs:
45 -- as such, slight changes can dramatically affect the length of proof
46 -- code.
47
48 mutual
49
50 _⟦∷⟧_ : ∀ {n} → Poly n × Coeff n * → Carrier × Vec Carrier n → Carrier
51 (x , []) ⟦∷⟧ (ρ , ρs) = ⟦ x ⟧ ρs
52 (x , (∹ xs)) ⟦∷⟧ (ρ , ρs) = ρ * ⅀⟦ xs ⟧ (ρ , ρs) + ⟦ x ⟧ ρs
53
54 ⅀⟦_⟧ : ∀ {n} → Coeff n + → (Carrier × Vec Carrier n) → Carrier
55 ⅀⟦ x ≠0 Δ i & xs ⟧ (ρ , ρs) = ((x , xs) ⟦∷⟧ (ρ , ρs)) *⟨ ρ ⟩^ i
56 {-# INLINE ⅀⟦_⟧ #-}
57
58 ⟦_⟧ : ∀ {n} → Poly n → Vec Carrier n → Carrier
59 ⟦ Κ x ⊐ i≤n ⟧ _ = ⟦ x ⟧ᵣ
60 ⟦ ⅀ xs ⊐ i≤n ⟧ Ρ = ⅀⟦ xs ⟧ (drop-1 i≤n Ρ)
61 {-# INLINE ⟦_⟧ #-}
62
63 ------------------------------------------------------------------------
64 -- Performance
65 ------------------------------------------------------------------------
66 -- As you might imagine, the implementation of the functions above
67 -- seriously affect performance. What you might not realise, though,
68 -- is that the most important component is the *order of the arguments*.
69 -- For instance, if we change:
70 --
71 -- (x , xs) ⟦∷⟧ (ρ , ρs) = ρ * ⅀⟦ xs ⟧ (ρ , ρs) + ⟦ x ⟧ ρs
72 --
73 -- To:
74 --
75 -- (x , xs) ⟦∷⟧ (ρ , ρs) = ⟦ x ⟧ ρs + ⅀⟦ xs ⟧ (ρ , ρs) * ρ
76 --
77 -- We get a function that's several orders of magnitude slower!