I have started working my way through the Programming Language Foundations in Agda book and have become confused while attempting to perform the exercise which asks you to write an inc
function which increments a binary number represented by the following Bin
type:
data Bin : Set where
⟨⟩ : Bin
_O : Bin → Bin
_I : Bin → Bin
I started writing my inc
function as
inc_ : Bin → Bin
inc ⟨⟩ = ⟨⟩
inc (x O) = {!!}
inc (x I) = {!!}
and then thought: "How does Agda know if a value of type Bin
can be matched and destructed into x O
and x I
without ambiguity if the _O
and _I
constructors have the same type?". The more I thought about this the more confused I became, if we take the Nat
example:
data ℕ : Set where
zero : ℕ
succ : ℕ → ℕ
the zero
and succ
constructors both produce a value of type ℕ
, so how does Agda know whether some particular value of type ℕ
would match the patterns I have in place for functions such as _+_
?
_+_ : ℕ → ℕ → ℕ
zero + m = m
succ n-1 + m = succ (n-1 + m)
It seems to me the only way this could work is if Agda keeps track of the constructor used to create each value, and then allows for using that same constructor in pattern matching?
I am very new to Agda and trying to wrap my head around the relationship between types, values, constructors and pattern matching. I would very much appreciate an explanation of how these relate with reference to the Bin
and ℕ
examples in my question. I have tried reading some additional articles/books/lecture sides and the Agda docs but I could not find an answer to this question.