Nested datatype for square matrices

混江龙づ霸主 提交于 2019-12-04 04:29:55

Let's introduce some informal notation to guide intuition. Write T :> U to denote that T is a sum type having one or more subcases, and U is one of them (at least modulo some isomorphism). We'll also use = between types to denote isomorphism.

So, by definition, we have

Square a = Square' Nil a
:> { taking the Zero branch }
Nil (Nil a)
=
()

So, this case denotes the empty "0x0" matrix.

Square a = Square' Nil a
:> { taking the Succ branch }
Square' (Cons Nil) a
:> { taking the Zero branch }
Cons Nil (Cons Nil a)
=  { def of Cons }
(Cons Nil a, Nil (Cons Nil a))
=  { def of Cons }
((a, Nil a), Nil (Cons Nil a))
=  { def of Nil }
((a, ()), ())
=
a

So, this is the 1x1 matrix.

Square a = Square' Nil a
:> { taking the Succ branch }
Square' (Cons Nil) a
:> { taking the Succ branch again }
Square' (Cons (Cons Nil)) a
:> { taking the Zero branch }
Cons (Cons Nil) (Cons (Cons Nil) a)
=
Cons (Cons Nil) (a, Cons Nil a)
=
Cons (Cons Nil) (a, a, Nil a)
=
Cons (Cons Nil) (a, a, ())
=
Cons (Cons Nil) (a, a)
=
((a,a), Cons Nil (a, a))
=
((a,a), (a,a), Nil (a, a))
=
((a,a), (a,a), ())
=
((a,a), (a,a))

So, this is the 2x2 matrix.

We should now be able to spot some pattern. Taking the Succ branches, we end up with a type of the form

Square' (Cons (Cons (Cons (...(Cons Nil))))) a

Which becomes, with the final Zero,

F (F a)
  where F = (Cons (Cons (Cons (...(Cons Nil)))))

Note that we considered all possible cases, so the final type must indeed be of the form F (F a) with some F of the form above.

Now, one can see that F a is isomorphic to (a,a,a,....) where the number N of as it exactly the number N of Conses in the definition of F. Hence, F (F a) will produce a square matrix (an N-tuple of N-tuples = square matrix).

Let's prove that by induction on the number of Conses. For the zero case, we have F = Nil, and indeed, as we wanted, zero as appear:

Nil a = ()

For the induction case, assume F a with N Conses is (a,a,...) with N as. The N+1 case to prove would state that (Cons F) a is (a,a,...,a), having N+1 as. Indeed:

Cons F a
=
(a, F a)
=
(a, (a,a....))   { 1 + N a's , as wanted }

QED.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!