Agda Type-Checking Error - typechecking

I'm currently making an ordered vector datatype and I'm trying to create operations from the data type but I get an error:
(Set (.Agda.Primitive.lsuc β„“)) != Set
when checking that the expression A has type Set β„“
This is the datatype
module ordered-vector (A : Set) (_<A_ : A β†’ A β†’ 𝔹) where
data ordered-𝕍 : {A : Set}β†’ A β†’ β„• β†’ Set where
[] : {a : A} β†’ ordered-𝕍 a 0
_::_ : (head : A) {min : A} β†’ {n : β„•} β†’ (tail : ordered-𝕍 min n) β†’ true (min <A head) β†’ ordered-𝕍 head (suc n)
And this is the operation:
[_]o𝕍 : βˆ€ {β„“} {A : Set β„“} β†’ A β†’ ordered-𝕍 A 1
[ x ]o𝕍 = x :: []
I believe the following code is more correct for the datatype. How do I retain the correctness of the cons part of the definition?
data ordered-𝕍 {β„“} (A : Set β„“) : β„• β†’ Set β„“ where
[] : ordered-𝕍 A 0
_::_ : (head : A) {min : A} β†’ {n : β„•} β†’ ordered-𝕍 min n β†’ true (min <A head) β†’ ordered-𝕍 head (suc n)
This is the nat module
http://lpaste.net/147233

First of all, the type of [_]o𝕍 doesn't make much sense, because you are passing the type of the argument (the type of x) as the index to ordered-𝕍; I believe you are trying to do
[_]o𝕍 : βˆ€ {β„“} {A : Set β„“} β†’ (a : A) β†’ ordered-𝕍 a 1
instead.
If you change the type of [_]o𝕍 accordingly, you will still get the error message
(Set β„“) != Set
when checking that the expression a has type A
and that is because your definition of [_]o𝕍 tries to be level-polymorphic, but your definition of ordered-𝕍 isn't.
You can either make [_]o𝕍 "dumber":
[_]o : βˆ€ {A : Set} β†’ (a : A) β†’ ordered a 1
[ x ]o = x ∷ []
or make ordered-𝕍 "smarter":
data ordered-𝕍 {β„“} {A : Set β„“} : A β†’ β„• β†’ Set β„“ where
[] : {a : A} β†’ ordered-𝕍 a 0
_∷_ : (head : A) {min : A} β†’ {n : β„•} β†’ (tail : ordered-𝕍 min n) β†’ true (min <A head) β†’ ordered-𝕍 head (suc n)
However, if you want A and _<A_ to be parameters to your module, I think this is altogether the wrong approach, and ordered-𝕍 should simply not be parametric in the choice of A at all:
module ordered-vector (A : Set) (_<A_ : A β†’ A β†’ 𝔹) where
data ordered-𝕍 : A β†’ β„• β†’ Set where
[] : {a : A} β†’ ordered-𝕍 a 0
_∷_ : (head : A) {min : A} β†’ {n : β„•} β†’ (tail : ordered-𝕍 min n) β†’ true (min <A head) β†’ ordered-𝕍 head (suc n)

Related

Guidance on very shallow embedding VHDL in AGDA

for my project in Programming Languages I am doing a very shallow and simple embedding VHDL digital circuits in agda. The aim is to write the syntax, static semantics, dynamic semantics and then write some proofs to show our understanding of the material. Up till now I have written the following code:
data Ckt : Set where
var : String β†’ Ckt
bool : Bool β†’ Ckt
empty : Ckt
gate : String β†’ β„• β†’ β„• β†’ Ckt -- name in out
series : String β†’ Ckt β†’ Ckt β†’ Ckt -- name ckt1 ckt2
parallel : String β†’ Ckt β†’ Ckt β†’ Ckt --name ckt1 ckt2
And : Ckt
And = gate "And" 2 1
data Ctxt : Set where
β–‘ : Ctxt
_,_ : (String Γ— β„• Γ— β„•) β†’ Ctxt β†’ Ctxt
_β‰ˆ_ : Ctxt β†’ Ctxt β†’ Set
β–‘ β‰ˆ β–‘ = ⊀
β–‘ β‰ˆ (_ , _) = βŠ₯
(_ , _) β‰ˆ β–‘ = βŠ₯
((s₁ , (in₁ , outβ‚‚)) , Γ₁) β‰ˆ ((sβ‚‚ , (in₃ , outβ‚„)) , Ξ“β‚‚) = True (s₁ β‰Ÿ sβ‚‚) Γ— in₁ ≑ in₃ Γ— outβ‚‚ ≑ outβ‚„ Γ— Γ₁ β‰ˆ Ξ“β‚‚
--static Semantics
data _⊒_ : (Ξ“ : Ctxt) β†’ (e : Ckt) β†’ Set where
VarT : βˆ€ {Ξ“ s Ο„} β†’ ((s , Ο„) ∈ Ξ“) β†’ Ξ“ ⊒ var s
BoolT : βˆ€ {Ξ“ b} β†’ Ξ“ ⊒ bool b
EmptyT : βˆ€ {Ξ“} β†’ Ξ“ ⊒ empty
GateT : βˆ€ {Ξ“ s i o} β†’ (s , (i , o)) ∈ Ξ“ β†’ Ξ“ ⊒ gate s i o
SeriesT : βˆ€ {Ξ“ s c₁ cβ‚‚} β†’ Ξ“ ⊒ c₁ β†’ Ξ“ ⊒ cβ‚‚ β†’ Ξ“ ⊒ series s c₁ cβ‚‚
ParallelT : βˆ€ {Ξ“ s c₁ cβ‚‚} β†’ Ξ“ ⊒ c₁ β†’ Ξ“ ⊒ cβ‚‚ β†’ Ξ“ ⊒ parallel s c₁ cβ‚‚
What I am stuck at is how can I convert this program so as to carry out the program execution i-e I don't know how to start writing the dynamic semantics. Also, if there is any way to improve the syntax or statics of my current program then please let me know.

Formulating proof for assignment

Consider the following code from an assignment. The aim here is to prove that transactions on accounts are commutative. From what i understand is there are two accounts e1{cash 10} and e2{cash 20}. So if i make a transaction on e1 by giving 10 and then on e2 by giving 10 then and then i do it in the reverse order then at the end the account state is the same. For this i have to prove the the account states in between are equivalent.
like the account state [e1{10} e2{20}]->[e1{0} e2{20}]->[e1{0} e2{10}] and [e1{10} e2{20}]->[e1{10} e2{10}]->[e1{0} e2{10}] i-e the states in between lead to the same state. Is my thinking correct? How do i formulate this? This looked trivial at first glance to me but is not that easy.
module Acc where
open import Data.Nat hiding (_β‰Ÿ_; _+_; _≀_)
open import Data.Integer hiding (_β‰Ÿ_; suc)
open import Data.String
open import Data.Product
open import Relation.Nullary
open import Relation.Nullary.Decidable
open import Relation.Binary.PropositionalEquality
-- Trivial example of an EDSL inspired by
-- http://www.lpenz.org/articles/hedsl-sharedexpenses/
-- We have n people who go on a trip
-- they pay for things
-- they give each other money
-- at the end we want to have the balance on each account
-- Syntax
infixr 10 _β€’_
infixr 10 _and_
infix 20 _β‡’_
data Person : Set where
P : String β†’ Person
data Exp : Set where
_β‡’_ : Person β†’ β„• β†’ Exp
_[_]β‡’_ : Person β†’ β„• β†’ Person β†’ Exp
_and_ : Exp β†’ Exp β†’ Exp
data Accounts : Set where
β–‘ : Accounts
_,_ : (String Γ— β„€) β†’ Accounts β†’ Accounts
data _∈ᡣ_ : (String Γ— β„€) β†’ Accounts β†’ Set where
hereα΅£ : βˆ€ {ρ s v} β†’ (s , v) ∈ᡣ ((s , v) , ρ)
skipα΅£ : βˆ€ {ρ s v s' v'} β†’
{Ξ± : False (s β‰Ÿ s')} β†’ (s , v) ∈ᡣ ρ β†’ (s , v) ∈ᡣ ((s' , v') , ρ)
update : Accounts β†’ String β†’ β„€ β†’ Accounts
update β–‘ s amount = (s , amount) , β–‘
update ((s₁ , amount₁) , accounts) sβ‚‚ amountβ‚‚ with (s₁ β‰Ÿ sβ‚‚)
... | yes _ = (s₁ , (amount₁ + amountβ‚‚)) , accounts
... | no _ = (s₁ , amount₁) , update accounts sβ‚‚ amountβ‚‚
data account : Exp β†’ Accounts β†’ Accounts β†’ Set where
spend : βˆ€ {s n Οƒ} β†’ account (P s β‡’ (suc n)) Οƒ (update Οƒ s -[1+ n ])
give : βˆ€ {s₁ sβ‚‚ n Οƒ} β†’ account (P s₁ [ suc n ]β‡’ P sβ‚‚) Οƒ
(update (update Οƒ s₁ -[1+ n ]) sβ‚‚ (+ (suc n)))
_β€’_ : βˆ€ {e₁ eβ‚‚ σ₁ Οƒβ‚‚ σ₃} β†’
account e₁ σ₁ Οƒβ‚‚ β†’ account eβ‚‚ Οƒβ‚‚ σ₃ β†’ account (e₁ and eβ‚‚) σ₁ σ₃
andComm : βˆ€ {Οƒ Οƒ' Οƒ'' e₁ eβ‚‚} β†’ account (e₁ and eβ‚‚) Οƒ Οƒ' β†’
account (eβ‚‚ and e₁) Οƒ Οƒ'' β†’ Οƒ' ≑ Οƒ''
andComm (a₁ β€’ a) (b β€’ b₁) = {!!}

Why is Monad of sort Set1?

I've been trying to encode the Monad typeclass in Agda. I've gotten this far:
module Monad where
record Monad (M : Set β†’ Set) : Set1 where
field
return : {A : Set} β†’ A β†’ M A
_⟫=_ : {A B : Set} β†’ M A β†’ (A β†’ M B) β†’ M B
So a Monad 'instance' is really just a record of functions that gets passed around. Question: Why is Monad of sort Set1? Annotating it with Set gives the following error:
The type of the constructor does not fit in the sort of the
datatype, since Set₁ is not less or equal than Set
when checking the definition of Monad
What thought process should I be going through to determine that Monad is Set1 rather than Set?
Agda has an infinite hierarchy of universes Set : Set1 : Set2 : ... to prevent paradoxes (Russell's paradox, Hurkens' paradox). _->_ preserves this hierarchy: (Set -> Set) : Set1, (Set1 -> Set) : Set2, (Set -> Set2) : Set3, i.e. the universe where A -> B lies depends on the universes where A and B lie: if A's is bigger than B's, then A -> B lies in the same universe as A, otherwise A -> B lies in the same universe as B.
You're quantifying over Set (in {A : Set} and {A B : Set}), hence the types of return and _⟫=_ lie in Set1, hence the whole thing lies in Set1. With explicit universes the code looks like this:
TReturn : (Set β†’ Set) β†’ Set1
TReturn M = {A : Set} β†’ A β†’ M A
TBind : (Set β†’ Set) β†’ Set1
TBind M = {A B : Set} β†’ M A β†’ (A β†’ M B) β†’ M B
module Monad where
record Monad (M : Set β†’ Set) : Set1 where
field
return : TReturn M
_⟫=_ : TBind M
More on universe polymorphism in Agda wiki.

Termination-checking of function over a trie

I'm having difficulty convincing Agda to termination-check the function fmap below and similar functions defined recursively over the structure of a Trie. A Trie is a trie whose domain is a Type, an object-level type formed from unit, products and fixed points (I've omitted coproducts to keep the code minimal). The problem seems to relate to a type-level substitution I use in the definition of Trie. (The expression const (ΞΌβ‚œ Ο„) * Ο„ means apply the substitution const (ΞΌβ‚œ Ο„) to the type Ο„.)
module Temp where
open import Data.Unit
open import Category.Functor
open import Function
open import Level
open import Relation.Binary
-- A context is just a snoc-list.
data Cxt {𝒂} (A : Set 𝒂) : Set 𝒂 where
Ξ΅ : Cxt A
_∷ᡣ_ : Cxt A β†’ A β†’ Cxt A
-- Context membership.
data _∈_ {𝒂} {A : Set 𝒂} (a : A) : Cxt A β†’ Set 𝒂 where
here : βˆ€ {Ξ”} β†’ a ∈ Ξ” ∷ᡣ a
there : βˆ€ {Ξ” aβ€²} β†’ a ∈ Ξ” β†’ a ∈ Ξ” ∷ᡣ aβ€²
infix 3 _∈_
-- Well-formed types, using de Bruijn indices.
data _⊦ (Ξ” : Cxt ⊀) : Set where
nat : Ξ” ⊦
𝟏 : Ξ” ⊦
var : _ ∈ Ξ” β†’ Ξ” ⊦
_+_ _β¨°_ : Ξ” ⊦ β†’ Ξ” ⊦ β†’ Ξ” ⊦
ΞΌ : Ξ” ∷ᡣ _ ⊦ β†’ Ξ” ⊦
infix 3 _⊦
-- A closed type.
Type : Set
Type = Ρ ⊦
-- Type-level substitutions and renamings.
Sub Ren : Rel (Cxt ⊀) zero
Sub Ξ” Ξ”β€² = _ ∈ Ξ” β†’ Ξ”β€² ⊦
Ren Ξ” Ξ”β€² = βˆ€ {x} β†’ x ∈ Ξ” β†’ x ∈ Ξ”β€²
-- Renaming extension.
extendα΅£ : βˆ€ {Ξ” Ξ”β€²} β†’ Ren Ξ” Ξ”β€² β†’ Ren (Ξ” ∷ᡣ _) (Ξ”β€² ∷ᡣ _)
extendᡣ ρ here = here
extendᡣ ρ (there x) = there (ρ x)
-- Lift a type renaming to a type.
_*α΅£_ : βˆ€ {Ξ” Ξ”β€²} β†’ Ren Ξ” Ξ”β€² β†’ Ξ” ⊦ β†’ Ξ”β€² ⊦
_ *α΅£ nat = nat
_ *ᡣ 𝟏 = 𝟏
ρ *ᡣ (var x) = var (ρ x)
ρ *α΅£ (τ₁ + Ο„β‚‚) = (ρ *α΅£ τ₁) + (ρ *α΅£ Ο„β‚‚)
ρ *α΅£ (τ₁ β¨° Ο„β‚‚) = (ρ *α΅£ τ₁) β¨° (ρ *α΅£ Ο„β‚‚)
ρ *α΅£ (ΞΌ Ο„) = ΞΌ (extendα΅£ ρ *α΅£ Ο„)
-- Substitution extension.
extend : βˆ€ {Ξ” Ξ”β€²} β†’ Sub Ξ” Ξ”β€² β†’ Sub (Ξ” ∷ᡣ _) (Ξ”β€² ∷ᡣ _)
extend ΞΈ here = var here
extend ΞΈ (there x) = there *α΅£ (ΞΈ x)
-- Lift a type substitution to a type.
_*_ : βˆ€ {Ξ” Ξ”β€²} β†’ Sub Ξ” Ξ”β€² β†’ Ξ” ⊦ β†’ Ξ”β€² ⊦
ΞΈ * nat = nat
θ * 𝟏 = 𝟏
ΞΈ * var x = ΞΈ x
ΞΈ * (τ₁ + Ο„β‚‚) = (ΞΈ * τ₁) + (ΞΈ * Ο„β‚‚)
ΞΈ * (τ₁ β¨° Ο„β‚‚) = (ΞΈ * τ₁) β¨° (ΞΈ * Ο„β‚‚)
ΞΈ * ΞΌ Ο„ = ΞΌ (extend ΞΈ * Ο„)
data Trie {𝒂} (A : Set 𝒂) : Type β†’ Set 𝒂 where
〈βŒͺ : A β†’ 𝟏 β–· A
γ€”_,_〕 : βˆ€ {τ₁ Ο„β‚‚} β†’ τ₁ β–· A β†’ Ο„β‚‚ β–· A β†’ τ₁ + Ο„β‚‚ β–· A
↑_ : βˆ€ {τ₁ Ο„β‚‚} β†’ τ₁ β–· Ο„β‚‚ β–· A β†’ τ₁ β¨° Ο„β‚‚ β–· A
roll : βˆ€ {Ο„} β†’ (const (ΞΌ Ο„) * Ο„) β–· A β†’ ΞΌ Ο„ β–· A
infixr 5 Trie
syntax Trie A Ο„ = Ο„ β–· A
{-# NO_TERMINATION_CHECK #-}
fmap : βˆ€ {a} {A B : Set a} {Ο„} β†’ (A β†’ B) β†’ Ο„ β–· A β†’ Ο„ β–· B
fmap f (〈βŒͺ x) = 〈βŒͺ (f x)
fmap f γ€” σ₁ , Οƒβ‚‚ 〕 = γ€” fmap f σ₁ , fmap f Οƒβ‚‚ 〕
fmap f (↑ Οƒ) = ↑ (fmap (fmap f) Οƒ)
fmap f (roll Οƒ) = roll (fmap f Οƒ)
It would seem that fmap recurses into a strictly smaller argument in each case; certainly the product case is fine if I remove recursive types. On the other hand, the definition handles recursive types fine if I remove products.
What's the simplest way to proceed here? The inline/fuse trick does not look particularly applicable, but maybe it is. Or should I be looking for another way to deal with the substitution in the definition of Trie?
The inline/fuse trick can be applied in (perhaps) surprising way. This trick is suited for problems of this sort:
data Trie (A : Set) : Set where
nil : Trie A
node : A β†’ List (Trie A) β†’ Trie A
map-trie : {A B : Set} β†’ (A β†’ B) β†’ Trie A β†’ Trie B
map-trie f nil = nil
map-trie f (node x xs) = node (f x) (map (map-trie f) xs)
This function is structurally recursive, but in a hidden way. map just applies map-trie f to the elements of xs, so map-trie gets applied to smaller (sub-)tries. But Agda doesn't look through the definition of map to see that it doesn't do anything funky. So we must apply the inline/fuse trick to get it past termination checker:
map-trie : {A B : Set} β†’ (A β†’ B) β†’ Trie A β†’ Trie B
map-trie f nil = nil
map-trie {A} {B} f (node x xs) = node (f x) (mapβ€² xs)
where
mapβ€² : List (Trie A) β†’ List (Trie B)
mapβ€² [] = []
mapβ€² (x ∷ xs) = map-trie f x ∷ mapβ€² xs
Your fmap function shares the same structure, you map a lifted function of some sort. But what to inline? If we follow the example above, we should inline fmap itself. This looks and feels a bit strange, but indeed, it works:
fmap fmapβ€² : βˆ€ {a} {A B : Set a} {Ο„} β†’ (A β†’ B) β†’ Ο„ β–· A β†’ Ο„ β–· B
fmap f (〈βŒͺ x) = 〈βŒͺ (f x)
fmap f γ€” σ₁ , Οƒβ‚‚ 〕 = γ€” fmap f σ₁ , fmap f Οƒβ‚‚ 〕
fmap f (↑ Οƒ) = ↑ (fmap (fmapβ€² f) Οƒ)
fmap f (roll Οƒ) = roll (fmap f Οƒ)
fmapβ€² f (〈βŒͺ x) = 〈βŒͺ (f x)
fmapβ€² f γ€” σ₁ , Οƒβ‚‚ 〕 = γ€” fmapβ€² f σ₁ , fmapβ€² f Οƒβ‚‚ 〕
fmapβ€² f (↑ Οƒ) = ↑ (fmapβ€² (fmap f) Οƒ)
fmapβ€² f (roll Οƒ) = roll (fmapβ€² f Οƒ)
There's another technique you can apply: it's called sized types. Instead of relying on the compiler to figure out when somethig is or is not structurally recursive, you instead specify it directly. However, you have to index your data types by a Size type, so this approach is fairly intrusive and cannot be applied to already existing types, but I think it is worth mentioning.
In its simplest form, sized type behaves as a type indexed by a natural number. This index specifies the upper bound of structural size. You can think of this as an upper bound for the height of a tree (given that the data type is an F-branching tree for some functor F). Sized version of List looks almost like a Vec, for example:
data SizedList (A : Set) : β„• β†’ Set where
[] : βˆ€ {n} β†’ SizedList A n
_∷_ : βˆ€ {n} β†’ A β†’ SizedList A n β†’ SizedList A (suc n)
But sized types add few features that make them easier to use. You have a constant ∞ for the case when you don't care about the size. suc is called ↑ and Agda implements few rules, such as ↑ ∞ = ∞.
Let's rewrite the Trie example to use sized types. We need a pragma at the top of the file and one import:
{-# OPTIONS --sized-types #-}
open import Size
And here's the modified data type:
data Trie (A : Set) : {i : Size} β†’ Set where
nil : βˆ€ {i} β†’ Trie A {↑ i}
node : βˆ€ {i} β†’ A β†’ List (Trie A {i}) β†’ Trie A {↑ i}
If you leave the map-trie function as is, the termination checker is still going to complain. That's because when you don't specify any size, Agda will fill in infinity (i.e. don't-care value) and we are back at the beginning.
However, we can mark map-trie as size-preserving:
map-trie : βˆ€ {i A B} β†’ (A β†’ B) β†’ Trie A {i} β†’ Trie B {i}
map-trie f nil = nil
map-trie f (node x xs) = node (f x) (map (map-trie f) xs)
So, if you give it a Trie bounded by i, it will give you another Trie bounded by i as well. So map-trie can never make the Trie larger, only equally large or smaller. This is enough for the termination checker to figure out that map (map-trie f) xs is okay.
This technique can also be applied to your Trie:
open import Size
renaming (↑_ to ^_)
data Trie {𝒂} (A : Set 𝒂) : {i : Size} β†’ Type β†’ Set 𝒂 where
〈βŒͺ : βˆ€ {i} β†’ A β†’
Trie A {^ i} 𝟏
γ€”_,_〕 : βˆ€ {i τ₁ Ο„β‚‚} β†’ Trie A {i} τ₁ β†’ Trie A {i} Ο„β‚‚ β†’
Trie A {^ i} (τ₁ + Ο„β‚‚)
↑_ : βˆ€ {i τ₁ Ο„β‚‚} β†’ Trie (Trie A {i} Ο„β‚‚) {i} τ₁ β†’
Trie A {^ i} (τ₁ β¨° Ο„β‚‚)
roll : βˆ€ {i Ο„} β†’ Trie A {i} (const (ΞΌ Ο„) * Ο„) β†’
Trie A {^ i} (ΞΌ Ο„)
infixr 5 Trie
syntax Trie A Ο„ = Ο„ β–· A
fmap : βˆ€ {i 𝒂} {A B : Set 𝒂} {Ο„} β†’ (A β†’ B) β†’ Trie A {i} Ο„ β†’ Trie B {i} Ο„
fmap f (〈βŒͺ x) = 〈βŒͺ (f x)
fmap f γ€” σ₁ , Οƒβ‚‚ 〕 = γ€” fmap f σ₁ , fmap f Οƒβ‚‚ 〕
fmap f (↑ Οƒ) = ↑ fmap (fmap f) Οƒ
fmap f (roll Οƒ) = roll (fmap f Οƒ)

Assisting Agda's termination checker

Suppose we define a function
f : N \to N
f 0 = 0
f (s n) = f (n/2) -- this / operator is implemented as floored division.
Agda will paint f in salmon because it cannot tell if n/2 is smaller than n. I don't know how to tell Agda's termination checker anything. I see in the standard library they have a floored division by 2 and a proof that n/2 < n. However, I still fail to see how to get the termination checker to realize that recursion has been made on a smaller subproblem.
Agda's termination checker only checks for structural recursion (i.e. calls that happen on structurally smaller arguments) and there's no way to establish that certain relation (such as _<_) implies that one of the arguments is structurally smaller.
Digression: Similar problem happens with positivity checker. Consider the standard fix-point data type:
data ΞΌ_ (F : Set β†’ Set) : Set where
fix : F (ΞΌ F) β†’ ΞΌ F
Agda rejects this because F may not be positive in its first argument. But we cannot restrict ΞΌ to only take positive type functions, or show that some particular type function is positive.
How do we normally show that a recursive functions terminates? For natural numbers, this is the fact that if the recursive call happens on strictly smaller number, we eventually have to reach zero and the recursion stops; for lists the same holds for its length; for sets we could use the strict subset relation; and so on. Notice that "strictly smaller number" doesn't work for integers.
The property that all these relations share is called well-foundedness. Informally speaking, a relation is well-founded if it doesn't have any infinite descending chains. For example, < on natural numbers is well founded, because for any number n:
n > n - 1 > ... > 2 > 1 > 0
That is, the length of such chain is limited by n + 1.
≀ on natural numbers, however, is not well-founded:
n β‰₯ n β‰₯ ... β‰₯ n β‰₯ ...
And neither is < on integers:
n > n - 1 > ... > 1 > 0 > -1 > ...
Does this help us? It turns out we can encode what it means for a relation to be well-founded in Agda and then use it to implement your function.
For simplicity, I'm going to bake the _<_ relation into the data type. First of all, we must define what it means for a number to be accessible: n is accessible if all m such that m < n are also accessible. This of course stops at n = 0, because there are no m so that m < 0 and this statement holds trivially.
data Acc (n : β„•) : Set where
acc : (βˆ€ m β†’ m < n β†’ Acc m) β†’ Acc n
Now, if we can show that all natural numbers are accessible, then we showed that < is well-founded. Why is that so? There must be a finite number of the acc constructors (i.e. no infinite descending chain) because Agda won't let us write infinite recursion. Now, it might seem as if we just pushed the problem back one step further, but writing the well-foundedness proof is actually structurally recursive!
So, with that in mind, here's the definition of < being well-founded:
WF : Set
WF = βˆ€ n β†’ Acc n
And the well-foundedness proof:
<-wf : WF
<-wf n = acc (go n)
where
go : βˆ€ n m β†’ m < n β†’ Acc m
go zero m ()
go (suc n) zero _ = acc Ξ» _ ()
go (suc n) (suc m) (s≀s m<n) = acc Ξ» o o<sm β†’ go n o (trans o<sm m<n)
Notice that go is nicely structurally recursive. trans can be imported like this:
open import Data.Nat
open import Relation.Binary
open DecTotalOrder decTotalOrder
using (trans)
Next, we need a proof that ⌊ n /2βŒ‹ ≀ n:
/2-less : βˆ€ n β†’ ⌊ n /2βŒ‹ ≀ n
/2-less zero = z≀n
/2-less (suc zero) = z≀n
/2-less (suc (suc n)) = s≀s (trans (/2-less n) (right _))
where
right : βˆ€ n β†’ n ≀ suc n
right zero = z≀n
right (suc n) = s≀s (right n)
And finally, we can write your f function. Notice how it suddenly becomes structurally recursive thanks to Acc: the recursive calls happen on arguments with one acc constructor peeled off.
f : β„• β†’ β„•
f n = go _ (<-wf n)
where
go : βˆ€ n β†’ Acc n β†’ β„•
go zero _ = 0
go (suc n) (acc a) = go ⌊ n /2βŒ‹ (a _ (s≀s (/2-less _)))
Now, having to work directly with Acc isn't very nice. And that's where Dominique's answer comes in. All this stuff I've written here has already been done in the standard library. It is more general (the Acc data type is actually parametrized over the relation) and it allows you to just use <-rec without having to worry about Acc.
Taking a more closer look, we are actually pretty close to the generic solution. Let's see what we get when we parametrize over the relation. For simplicity I'm not dealing with universe polymorphism.
A relation on A is just a function taking two As and returning Set (we could call it binary predicate):
Rel : Set β†’ Set₁
Rel A = A β†’ A β†’ Set
We can easily generalize Acc by changing the hardcoded _<_ : β„• β†’ β„• β†’ Set to an arbitrary relation over some type A:
data Acc {A} (_<_ : Rel A) (x : A) : Set where
acc : (βˆ€ y β†’ y < x β†’ Acc _<_ y) β†’ Acc _<_ x
The definition of well-foundedness changes accordingly:
WellFounded : βˆ€ {A} β†’ Rel A β†’ Set
WellFounded _<_ = βˆ€ x β†’ Acc _<_ x
Now, since Acc is an inductive data type like any other, we should be able to write its eliminator. For inductive types, this is a fold (much like foldr is eliminator for lists) - we tell the eliminator what to do with each constructor case and the eliminator applies this to the whole structure.
In this case, we'll do just fine with the simple variant:
foldAccSimple : βˆ€ {A} {_<_ : Rel A} {R : Set} β†’
(βˆ€ x β†’ (βˆ€ y β†’ y < x β†’ R) β†’ R) β†’
βˆ€ z β†’ Acc _<_ z β†’ R
foldAccSimple {R = R} accβ€² = go
where
go : βˆ€ z β†’ Acc _ z β†’ R
go z (acc a) = accβ€² z Ξ» y y<z β†’ go y (a y y<z)
If we know that _<_ is well-founded, we can skip the Acc _<_ z argument completly, so let's write small convenience wrapper:
recSimple : βˆ€ {A} {_<_ : Rel A} β†’ WellFounded _<_ β†’ {R : Set} β†’
(βˆ€ x β†’ (βˆ€ y β†’ y < x β†’ R) β†’ R) β†’
A β†’ R
recSimple wf accβ€² z = foldAccSimple accβ€² z (wf z)
And finally:
<-wf : WellFounded _<_
<-wf = {- same definition -}
<-rec = recSimple <-wf
f : β„• β†’ β„•
f = <-rec go
where
go : βˆ€ n β†’ (βˆ€ m β†’ m < n β†’ β„•) β†’ β„•
go zero _ = 0
go (suc n) r = r ⌊ n /2βŒ‹ (s≀s (/2-less _))
And indeed, this looks (and works) almost like the one in the standard library!
Here's the fully dependent version in case you are wondering:
foldAcc : βˆ€ {A} {_<_ : Rel A} (P : A β†’ Set) β†’
(βˆ€ x β†’ (βˆ€ y β†’ y < x β†’ P y) β†’ P x) β†’
βˆ€ z β†’ Acc _<_ z β†’ P z
foldAcc P accβ€² = go
where
go : βˆ€ z β†’ Acc _ z β†’ P z
go _ (acc a) = accβ€² _ Ξ» _ y<z β†’ go _ (a _ y<z)
rec : βˆ€ {A} {_<_ : Rel A} β†’ WellFounded _<_ β†’
(P : A β†’ Set) β†’ (βˆ€ x β†’ (βˆ€ y β†’ y < x β†’ P y) β†’ P x) β†’
βˆ€ z β†’ P z
rec wf P accβ€² z = foldAcc P accβ€² _ (wf z)
I would like to offer a slightly different answer than the ones given above. In particular, I want to suggest that instead of trying to somehow convince the termination checker that actually, no, this recursion is perfectly fine, we should instead try to reify the well-founded-ness so that the recursion is manifestly fine in virtue of being structural.
The idea here is that the problem comes from being unable to see that n / 2 is somehow a "part" of n. Structural recursion wants to break a thing into its immediate parts, but the way that n / 2 is a "part" of n is that we drop every other suc. But it's not obvious up front how many to drop, we have to look around and try to line things up. What would be nice is if we had some type that had constructors for "multiple" sucs.
To make the problem slightly more interesting, let's instead try to define the function that behaves like
f : β„• β†’ β„•
f 0 = 0
f (suc n) = 1 + (f (n / 2))
that is to say, it should be the case that
f n = ⌈ logβ‚‚ (n + 1) βŒ‰
Now naturally the above definition won't work, for the same reasons your f won't. But let's pretend that it did, and let's explore the "path", so to speak, that the argument would take through the natural numbers. Suppose we look at n = 8:
f 8 = 1 + f 4 = 1 + 1 + f 2 = 1 + 1 + 1 + f 1 = 1 + 1 + 1 + 1 + f 0 = 1 + 1 + 1 + 1 + 0 = 4
so the "path" is 8 -> 4 -> 2 -> 1 -> 0. What about, say, 11?
f 11 = 1 + f 5 = 1 + 1 + f 2 = ... = 4
so the "path" is 11 -> 5 -> 2 -> 1 -> 0.
Well naturally what's going on here is that at each step we're either dividing by 2, or subtracting one and dividing by 2. Every naturally number greater than 0 can be decomposed uniquely in this fashion. If it's even, divide by two and proceed, if it's odd, subtract one and divide by two and proceed.
So now we can see exactly what our data type should look like. We need a type that has a constructor that means "twice as many suc's" and another that means "twice as many suc's plus one", as well as of course a constructor that means "zero sucs":
data Decomp : β„• β†’ Set where
zero : Decomp zero
2*_ : βˆ€ {n} β†’ Decomp n β†’ Decomp (n * 2)
2*_+1 : βˆ€ {n} β†’ Decomp n β†’ Decomp (suc (n * 2))
We can now define the function that decomposes a natural number into the Decomp that corresponds to it:
decomp : (n : β„•) β†’ Decomp n
decomp zero = zero
decomp (suc n) = decomp n +1
It helps to define +1 for Decomps:
_+1 : {n : β„•} β†’ Decomp n β†’ Decomp (suc n)
zero +1 = 2* zero +1
(2* d) +1 = 2* d +1
(2* d +1) +1 = 2* (d +1)
Given a Decomp, we can flatten it down into a natural number that ignores the distinctions between 2*_ and 2*_+1:
flatten : {n : β„•} β†’ Decomp n β†’ β„•
flatten zero = zero
flatten (2* p) = suc (flatten p)
flatten (2* p +1 = suc (flatten p)
And now it's trivial to define f:
f : β„• β†’ β„•
f n = flatten (decomp n)
This happily passes the termination checker with no trouble, because we're never actually recursing on the problematic n / 2. Instead, we convert the number into a format that directly represents its path through the number space in a structurally recursive way.
Edit It occurred to me only a little while ago that Decomp is a little-endian representation of binary numbers. 2*_ is "append 0 to the end/shift left 1 bit" and 2*_+1 is "append 1 to the end/shift left 1 bit and add one". So the above code is really about showing that binary numbers are structurally recursive wrt dividing by 2, which they ought to be! That makes it much easier to understand, I think, but I don't want to change what I wrote already, so we could instead do some renaming here: Decomp ~> Binary, 2*_ ~> _,zero, 2*_+1 ~> _,one, decomp ~> natToBin, flatten ~> countBits.
After accepting Vitus' answer, I discovered a different way to accomplish the goal of proving a function terminates in Agda, namely using "sized types." I am providing my answer here because it seems acceptable, and also for critique of any weak points of this answer.
Sized types are described:
http://arxiv.org/pdf/1012.4896.pdf
They are implemented in Agda, not only MiniAgda; see here: http://www2.tcs.ifi.lmu.de/~abel/talkAIM2008Sendai.pdf.
The idea is to augment the data type with a size that allows the typechecker to more easily prove termination. Size is defined in the standard library.
open import Size
We define sized natural numbers:
data Nat : {i : Size} \to Set where
zero : {i : Size} \to Nat {\up i}
succ : {i : Size} \to Nat {i} \to Nat {\up i}
Next, we define predecessor and subtraction (monus):
pred : {i : Size} β†’ Nat {i} β†’ Nat {i}
pred .{↑ i} (zero {i}) = zero {i}
pred .{↑ i} (succ {i} n) = n
sub : {i : Size} β†’ Nat {i} β†’ Nat {∞} β†’ Nat {i}
sub .{↑ i} (zero {i}) n = zero {i}
sub .{↑ i} (succ {i} m) zero = succ {i} m
sub .{↑ i} (succ {i} m) (succ n) = sub {i} m n
Now, we may define division via Euclid's algorithm:
div : {i : Size} β†’ Nat {i} β†’ Nat β†’ Nat {i}
div .{↑ i} (zero {i}) n = zero {i}
div .{↑ i} (succ {i} m) n = succ {i} (div {i} (sub {i} m n) n)
data βŠ₯ : Set where
record ⊀ : Set where
notZero : Nat β†’ Set
notZero zero = βŠ₯
notZero _ = ⊀
We give division for nonzero denominators.
If the denominator is nonzero, then it is of the form, b+1. We then do
divPos a (b+1) = div a b
Since div a b returns ceiling (a/(b+1)).
divPos : {i : Size} β†’ Nat {i} β†’ (m : Nat) β†’ (notZero m) β†’ Nat {i}
divPos a (succ b) p = div a b
divPos a zero ()
As auxiliary:
div2 : {i : Size} β†’ Nat {i} β†’ Nat {i}
div2 n = divPos n (succ (succ zero)) (record {})
Now we can define a divide and conquer method for computing the n-th Fibonacci number.
fibd : {i : Size} β†’ Nat {i} β†’ Nat
fibd zero = zero
fibd (succ zero) = succ zero
fibd (succ (succ zero)) = succ zero
fibd (succ n) with even (succ n)
fibd .{↑ i} (succ {i} n) | true =
let
-- When m=n+1, the input, is even, we set k = m/2
-- Note, ceil(m/2) = ceil(n/2)
k = div2 {i} n
fib[k-1] = fibd {i} (pred {i} k)
fib[k] = fibd {i} k
fib[k+1] = fib[k-1] + fib[k]
in
(fib[k+1] * fib[k]) + (fib[k] * fib[k-1])
fibd .{↑ i} (succ {i} n) | false =
let
-- When m=n+1, the input, is odd, we set k = n/2 = (m-1)/2.
k = div2 {i} n
fib[k-1] = fibd {i} (pred {i} k)
fib[k] = fibd {i} k
fib[k+1] = fib[k-1] + fib[k]
in
(fib[k+1] * fib[k+1]) + (fib[k] * fib[k])
You cannot do this directly: Agda's termination checker only considers recursion ok on arguments that are syntactically smaller. However, the Agda standard library provides a few modules for proving termination using a well-founded order between the arguments of the functions. The standard order on natural numbers is such an order and can be used here.
Using the code in Induction.*, you can write your function as follows:
open import Data.Nat
open import Induction.WellFounded
open import Induction.Nat
s≀′s : βˆ€ {n m} β†’ n ≀′ m β†’ suc n ≀′ suc m
s≀′s ≀′-refl = ≀′-refl
s≀′s (≀′-step lt) = ≀′-step (s≀′s lt)
proof : βˆ€ n β†’ ⌊ n /2βŒ‹ ≀′ n
proof 0 = ≀′-refl
proof 1 = ≀′-step (proof zero)
proof (suc (suc n)) = ≀′-step (s≀′s (proof n))
f : β„• β†’ β„•
f = <-rec (Ξ» _ β†’ β„•) helper
where
helper : (n : β„•) β†’ (βˆ€ y β†’ y <β€² n β†’ β„•) β†’ β„•
helper 0 rec = 0
helper (suc n) rec = rec ⌊ n /2βŒ‹ (s≀′s (proof n))
I found an article with some explanation here. But there may be better references out there.
A similar question appeared on the Agda mailing-list a few weeks ago and the consensus seemed to be to inject the Data.Nat element into Data.Bin and then use structural recursion on this representation which is well-suited for the job at hand.
You can find the whole thread here : http://comments.gmane.org/gmane.comp.lang.agda/5690
You can avoid using well-founded recursion. Let's say you want a function, that applies ⌊_/2βŒ‹ to a number, until it reaches 0, and collects the results. With the {-# TERMINATING #-} pragma it can be defined like this:
{-# TERMINATING #-}
⌊_/2βŒ‹s : β„• -> List β„•
⌊_/2βŒ‹s 0 = []
⌊_/2βŒ‹s n = n ∷ ⌊ ⌊ n /2βŒ‹ /2βŒ‹s
The second clause is equivalent to
⌊_/2βŒ‹s n = n ∷ ⌊ n ∸ (n ∸ ⌊ n /2βŒ‹) /2βŒ‹s
It's possible to make ⌊_/2βŒ‹s structurally recursive by inlining this substraction:
⌊_/2βŒ‹s : β„• -> List β„•
⌊_/2βŒ‹s = go 0 where
go : β„• -> β„• -> List β„•
go _ 0 = []
go 0 (suc n) = suc n ∷ go (n ∸ ⌈ n /2βŒ‰) n
go (suc i) (suc n) = go i n
go (n ∸ ⌈ n /2βŒ‰) n is a simplified version of go (suc n ∸ ⌊ suc n /2βŒ‹ ∸ 1) n
Some tests:
test-5 : ⌊ 5 /2βŒ‹s ≑ 5 ∷ 2 ∷ 1 ∷ []
test-5 = refl
test-25 : ⌊ 25 /2βŒ‹s ≑ 25 ∷ 12 ∷ 6 ∷ 3 ∷ 1 ∷ []
test-25 = refl
Now let's say you want a function, that applies ⌊_/2βŒ‹ to a number, until it reaches 0, and sums the results. It's simply
⌊_/2βŒ‹sum : β„• -> β„•
⌊ n /2βŒ‹sum = go ⌊ n /2βŒ‹s where
go : List β„• -> β„•
go [] = 0
go (n ∷ ns) = n + go ns
So we can just run our recursion on a list, that contains values, produced by the ⌊_/2βŒ‹s function.
More concise version is
⌊ n /2βŒ‹sum = foldr _+_ 0 ⌊ n /2βŒ‹s
And back to the well-foundness.
open import Function
open import Relation.Nullary
open import Relation.Binary
open import Induction.WellFounded
open import Induction.Nat
calls : βˆ€ {a b β„“} {A : Set a} {_<_ : Rel A β„“} {guarded : A -> Set b}
-> (f : A -> A)
-> Well-founded _<_
-> (βˆ€ {x} -> guarded x -> f x < x)
-> (βˆ€ x -> Dec (guarded x))
-> A
-> List A
calls {A = A} {_<_} f wf smaller dec-guarded x = go (wf x) where
go : βˆ€ {x} -> Acc _<_ x -> List A
go {x} (acc r) with dec-guarded x
... | no _ = []
... | yes g = x ∷ go (r (f x) (smaller g))
This function does the same as the ⌊_/2βŒ‹s function, i.e. produces values for recursive calls, but for any function, that satisfies certain conditions.
Look at the definition of go. If x is not guarded, then return []. Otherwise prepend x and call go on f x (we could write go {x = f x} ...), which is structurally smaller.
We can redefine ⌊_/2βŒ‹s in terms of calls:
⌊_/2βŒ‹s : β„• -> List β„•
⌊_/2βŒ‹s = calls {guarded = ?} ⌊_/2βŒ‹ ? ? ?
⌊ n /2βŒ‹s returns [], only when n is 0, so guarded = Ξ» n -> n > 0.
Our well-founded relation is based on _<β€²_ and defined in the Induction.Nat module as <-well-founded.
So we have
⌊_/2βŒ‹s = calls {guarded = Ξ» n -> n > 0} ⌊_/2βŒ‹ <-well-founded {!!} {!!}
The type of the next hole is {x : β„•} β†’ x > 0 β†’ ⌊ x /2βŒ‹ <β€² x
We can easily prove this proposition:
open import Data.Nat.Properties
suc-⌊/2βŒ‹-≀′ : βˆ€ n -> ⌊ suc n /2βŒ‹ ≀′ n
suc-⌊/2βŒ‹-≀′ 0 = ≀′-refl
suc-⌊/2βŒ‹-≀′ (suc n) = s≀′s (⌊n/2βŒ‹β‰€β€²n n)
>0-⌊/2βŒ‹-<β€² : βˆ€ {n} -> n > 0 -> ⌊ n /2βŒ‹ <β€² n
>0-⌊/2βŒ‹-<β€² {suc n} (s≀s z≀n) = s≀′s (suc-⌊/2βŒ‹-≀′ n)
The type of the last hole is (x : β„•) β†’ Dec (x > 0), we can fill it by _≀?_ 1.
And the final definition is
⌊_/2βŒ‹s : β„• -> List β„•
⌊_/2βŒ‹s = calls ⌊_/2βŒ‹ <-well-founded >0-⌊/2βŒ‹-<β€² (_≀?_ 1)
Now you can recurse on a list, produced by ⌊_/2βŒ‹s, without any termination issues.
I encountered this sort of problem when trying to write a quick sort function in Agda.
While other answers seem to explain the problem and solutions more generally, coming from a CS background, I think the following wording would be more accessible for certain readers:
The problem of working with the Agda termination checker comes down to how we can internalize the termination checking process.
Suppose we want to define a function
func : Some-Recursively-Defined-Type β†’ A
func non-recursive-case = some-a
func (recursive-case n) = some-other-func (func (f n)) (func (g n)) ...
In many of the cases, we the writers know f n and g n are going to be smaller than recursive-case n. Furthermore, it is not like the proofs for these being smaller are super difficult. The problem is more about how we can communicate this knowledge to Agda.
It turns out we can do this by adding a timer argument to the definition.
Timer : Type
Timer = Nat
measure : Some-Recursively-Defined-Type β†’ Timer
-- this function returns an upper-bound of how many steps left to terminate
-- the estimate should be tight enough for the non-recursive cases that
-- given those estimates,
-- pattern matching on recursive cases is obviously impossible
measure = {! !}
func-aux :
(timer : Timer) -- the timer,
(actual-arguments : Some-Recursively-Defined-Type)
(timer-bounding : measure actual-arguments ≀ timer)
β†’ A
func-aux zero non-recursive-case prf = a
-- the prf should force args to only pattern match to the non-recursive cases
func-aux (succ t) non-recursive-case prf = a
func-aux (succ t) (recursive-case n) prf =
some-other-func (func-aux t (f n) prf') (func-aux t (g n) prf'') ... where
prf' : measure (f n) ≀ t
prf' = {! !}
prf'' : measure (g n) ≀ t
prf'' = {! !}
With these at hand, we can define the function we want as something like the following :
func : Some-Recursively-Defined-Type β†’ A
func x with measure x
func x | n = func-aux n x (≀-is-reflexive n)
Caveat
I have not taken into account anything about whether the computation would be efficient.
While Timer type is not restricted to be Nat (but for all types with which we have a strong enough order relation to work with), I think it is pretty safe to say we don't gain much even if we consider such generality.

Resources