Atomic Type Theory and Renouncing Forest Terms
An idea I’ve been interested in is stripping out the features of type theory to try and finitize them.
One version of this I think is interesting to consider “Atomic Type Theory”.
If you really strip out all constructions in your type theory, the only term left that you really can’t get rid of is Var(int). A substitution is “merely” picking in some ordering and multiplicity the items in the domain context.
There isn’t much to it, but that’s the point. And it nevertheless had some surprises for me.
Substitutions are King
I’ve been in a reading group of Angiuli and Gratzer’s Principles of Dependent Type Theory https://www.danielgratzer.com/papers/type-theory-book.pdf . It’s been fun! This post is just an elaboration / playing around with section 2.3
Because of the thinning e-graph https://arxiv.org/abs/2606.22734 https://www.youtube.com/watch?v=h1CzZguA6DE stuff, I’ve been pretty enamored with trying to think about “context” more carefully.
What I’ve come to appreciate is that “context” is really a part of the term, and kind of a central object of consideration. You need the context to have semantics. Semantics brackets go around the entire judgement [[G |- t : A]], not around just the term [[t]]. Judgements mean some kind of function-y thing from the context space G.
As part of this, you want ot talk about mappings between contexts, aka substitutions. I have been writing about “forest terms” https://www.philipzucker.com/forest_term_proof_type/ which I think of as a less weird feeling way to motivate substitutions as central. Why not have multi rooted terms?
I have been thinking in basically untyped or simply typed thinking thus far, assuming the dependent typed version would just be some complexity to layer on.
I think I partially renounce “forest terms”, because it led me to think about substitutions in the wrong way. Forest terms made me thing that the codomain context would reference variables coming from the domain context, because that is what a tuple of terms would look like. The G |- t : A judgement of a typed term does allow A to use variables from G
Untyped Atomic Type Theory
This is my starting point. Why even have types? It is less to type (on a keyboard).
Even here there are some interesting subcategories
- Thinnings https://www.philipzucker.com/thin1/ which require you to pick the variables in order while possibly skipping some
x,y,z,w |- x,w. Strictly monotonic maps between finite sets - Permutations which require you to pick everything exactly once
x,y,z,w |- y,z,x,w. Bijections between finite sets - Thinning duplications where you have to pick in order but you can pick the same thing multiple times.
x,y,z,w |- x,x,x,w. Non strict monotonic maps. https://en.wikipedia.org/wiki/Simplex_category
This can be represented in a nameless way de bruijn level- way as as simple datatype.
from dataclasses import dataclass
@dataclass
class FinMap:
ctx : int
ts : list[int] #
def __post_init__(self):
assert all(0 <= t < self.ctx for t in self.ts)
@staticmethod
def thin(t : list[bool]):
return FinMap(ctx=len(t), ts=[i for i, b in enumerate(t) if b])
@staticmethod
def id(ctx : int):
return FinMap(ctx=ctx, ts=list(range(ctx)))
@staticmethod
def perm(p : list[int]):
ctx = len(p)
assert sorted(p) == list(range(ctx))
return FinMap(ctx=ctx, ts=p)
@property
def cod(self):
return len(self.ts)
def __matmul__(self, other: "FinMap"):
assert self.ctx == other.cod
return FinMap(other.ctx, ts=[other.ts[i] for i in self.ts])
def __repr__(self):
return f"{list(range(self.ctx))} |- {self.ts}"
FinMap.id(3)
[0, 1, 2] |- [0, 1, 2]
A Thinning that drops variable 1 from the context
FinMap.thin([True, False, True])
[0, 1, 2] |- [0, 2]
A permutation composed with a thinning.
FinMap.perm([1,0]) @ FinMap.thin([True, False, True])
[0, 1, 2] |- [2, 0]
Simply Typed Atomic Type Theory
If we want to add simple types it doesn’t change much. The context becomes a list of types which here I represent as str. A list like list[str] is kind of just a slightly richer int
type Ty = str
@dataclass
class Subst:
ctx : list[Ty]
ts : list[int]
def __post_init__(self):
assert all(0 <= t < len(self.ctx) for t in self.ts)
@property
def cod(self):
return [self.ctx[i] for i in self.ts]
Subst(ctx=["Nat", "Bool", "Int"], ts=[0, 2]).cod
['Nat', 'Int']
Dependent Atomic Type Theory I
But if we want to add dependent types things get a bit stickier.
One very surprising thing that happens is that the codomain is no longer uniquely inferrable from ctx and ts
One way we might try to do so leads to something that is a bit more like polymorphism. We can have type variables and term variables of those type variables.
We can say that a variable in the context has the type of
The context a : Type, x : a is represented as ["Type", 0] where 0 is the back reference. Or another example a : Type, b : Type, x : a, y : b, z : a would be ["Type", "Type", 0, 1, 0]
Or a : Type2, b : a, c : b would be ["Type2", 0, 1]
type Ctx = list[int | str]
def is_ctx(ctx: list[int | str]) -> bool:
# Could enforce type variables point to "Type".
return all(isinstance(x, (int, str)) for x in ctx) and all(0 <= x < n for n, x in enumerate(ctx) if isinstance(x, int))
@dataclass
class Subst:
ctx : list[int | str] # None is Kind, int is reference to previous typevar, str is a concrete type
ts : list[int]
cod : list[int | str]
def __post_init__(self):
assert all(0 <= t < len(self.ctx) for t in self.ts)
assert is_ctx(self.ctx), self.ctx
assert is_ctx(self.cod), self.cod
assert len(self.ts) == len(self.cod)
for t,A in zip(self.ts, self.cod):
B = self.ctx[t]
assert B == (self.ts[A] if isinstance(A, int) else A)
def __matmul__(self, other: "Subst"):
assert self.ctx == other.cod
return Subst(other.ctx, [other.ts[t] for t in self.ts], self.cod)
@staticmethod
def id(ctx: list[int | str]) -> "Subst":
return Subst(ctx, list(range(len(ctx))), ctx)
def __repr__(self):
return f"{self.ctx} |- {self.ts} : {self.cod}"
def extend(self, v : int, ty : int | str) -> "Subst":
# v is index into domain, ty is index in codomain. Easy to get wrong maybe
# Subst.__post_init__ will check some sanity
return Subst(self.ctx, self.ts + [v], self.cod + [ty])
def ty_subst(ty : int | str, subst: Subst) -> int | str:
# pull ty in codomain indexing to domain indexing
return subst.ts[ty] if isinstance(ty, int) else ty
# The codomain is _not_ derivable from context and ts!!!
Subst(["Type", 0], [0,0,1], ["Type", "Type", 0])
Subst(["Type", 0], [0,0,1], ["Type", "Type", 1])
['Type', 0] |- [0, 0, 1] : ['Type', 'Type', 1]
Subst(["Type", 0], [1,0], [1, "Type"]) # This is invalid because invalid dependency occurs
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[112], line 1
----> 1 Subst(["Type", 0], [1,0], [1, "Type"])
File <string>:6, in __create_fn__.<locals>.__init__(self, ctx, ts, cod)
2 'Could not get source, probably due dynamically evaluated source code.'
Cell In[111], line 14, in Subst.__post_init__(self)
11 def __post_init__(self):
12 assert all(0 <= t < len(self.ctx) for t in self.ts)
13 assert is_ctx(self.ctx), self.ctx
---> 14 assert is_ctx(self.cod), self.cod
15 assert len(self.ts) == len(self.cod)
16 for t,A in zip(self.ts, self.cod):
17 B = self.ctx[t]
AssertionError: [1, 'Type']
Dependent Atomic Type Theory II
A slightly richer feeling version can be made by allowing Type families that apply to values, like n : Nat |- Fin n Type. But to keep things from getting too hairy, I allow types families to only apply to variables and don’t have other kinds of terms available.
It took some fiddling, but I eventually was fairly happy with what I got. I think having the separated notion of PreTy which doesn’t know about it’s context and Ty which does cleaned things up. It is somewhat interesting and possibly no coincidence that this reflects how we like to pretty print. The way things are pretty printed is also roughly the way we’ll like to type things in. By making Ctx = list[PreTy] rather than a verbosely telescoped Ctx = list[Ty] makes it way easier to just manually construct Subst rather than via the extend combinators.
@dataclass
class PreTy: # PreType? ctx |- F(x,x,y,z) Type
#ctx : list[Ty]
f : str
args : list[int] # previous vars
def __repr__(self):
return f"{self.f}({', '.join(map(str, self.args))})"
type Ctx = list[PreTy]
def is_ctx(ctx : Ctx):
return all(isinstance(ty, PreTy) for ty in ctx) and all(0 <= t < i for i, ty in enumerate(ctx) for t in ty.args)
@dataclass
class Subst: # Delta |- gamma : Gamma
dom : list[PreTy] # Ctx
ts : list[int]
cod : list[PreTy] # Ctx
def __post_init__(self):
assert is_ctx(self.dom), self.dom
assert is_ctx(self.cod), self.cod
assert all(0 <= t < len(self.dom) for t in self.ts)
assert len(self.ts) == len(self.cod)
for t,A in zip(self.ts, self.cod):
B = self.dom[t]
assert B.f == A.f
assert B.args == [self.ts[i] for i in A.args]
def __matmul__(self, other: "Subst") -> "Subst":
assert self.dom == other.cod, (self.dom, other.cod)
return Subst(
dom=other.dom,
ts=[other.ts[t] for t in self.ts],
cod=self.cod
)
def extend(self, v : Var, ty : Ty) -> "Subst":
assert self.cod == ty.ctx, (self.cod, ty.ctx) # ty is in the codomain context. It _has_ to be, because that's where it's getting added
assert self.dom == v.ctx, (v.ctx, self.dom) # Note that v is in the domain context
assert v.ty == ty.subst(self), (v.ty, ty.subst(self))
return Subst(
dom=self.dom,
ts=self.ts + [v.i],
cod=self.cod + [ty.ty]
)
def __repr__(self):
return f"{self.dom} |- {self.ts} : {self.cod}"
type Ctx = list[PreTy]
Nat = PreTy("Nat", [])
Unit = PreTy("Unit", [])
Bool = PreTy("Bool", [])
Fin = lambda n: PreTy("Fin", [n])
[Nat, Nat, Fin(0)]
[Nat, Nat, Fin(3)]
Subst([Nat, Nat, Fin(1)], [0, 1, 2], [Nat, Nat, Fin(1)])
def id_(ctx: Ctx) -> Subst:
return Subst(
dom=ctx,
ts=list(range(len(ctx))),
cod=ctx
)
def term(ctx: Ctx) -> Subst: # G |- ! : 1
return Subst(ctx, [], [])
def star(subst : Subst) -> Callable[[Subst], Subst]:
return lambda other: other @ subst # Or the other way
@dataclass
class Ty:
ctx : Ctx
ty : PreTy
def __post_init__(self):
assert is_ctx(self.ctx), self.ctx
assert all(0 <= t < len(self.ctx) for t in self.ty.args), self.ty
def subst(self, subst: Subst) -> "Ty":
assert self.ctx == subst.cod, (self.ctx, subst.cod)
return Ty(
ctx=subst.dom,
ty=PreTy(
f=self.ty.f,
args=[subst.ts[i] for i in self.ty.args]
)
)
def __repr__(self):
return f"{self.ctx} |- {self.ty} Type"
@dataclass
class Var:
ctx : Ctx
i : int
@property
def ty(self) -> Ty:
return Ty(self.ctx, self.ctx[self.i])
def __post_init__(self):
assert is_ctx(self.ctx), self.ctx
assert 0 <= self.i < len(self.ctx), self.i
def subst(self, subst: Subst) -> "Var":
assert self.ctx == subst.cod, (self.ctx, subst.cod)
return Var(
ctx=subst.dom,
i=subst.ts[self.i]
)
def __repr__(self):
return f"{self.ctx} |- {self.i} : {self.ty.ty}"
#def q(ctx : Ctx) -> Var: # The last one in the context. Or ctx, A and extend the initial context?
# return Var(ctx, len(ctx) - 1)
def q(A : Ty) -> Var: # This matches the inference rule better.
return Var(A.ctx + [A.ty], len(A.ctx))
def p(A : Ty) -> Subst:
return Subst(
dom=A.ctx + [A.ty],
ts=list(range(len(A.ctx))),
cod=A.ctx
)
def lift(subst: Subst, A : Ty) -> Subst: # gamma.A.
assert A.ctx == subst.cod, (A.ctx, subst.cod)
return (subst @ p(A.subst(subst))).extend(q(A.subst(subst)), A)
assert p(Ty([Nat], Nat)) @ p(Ty([Nat,Nat],Nat)) == Subst([Nat,Nat,Nat], [0], [Nat])
assert Subst([Bool, Unit], [1], [Unit]) @ Subst([Unit, Unit, Bool], [2,1], [Bool, Unit]) == Subst([Unit,Unit, Bool], [1], [Unit])
assert Ty([Nat, Bool], Unit).subst(Subst([Nat,Fin(0),Bool], [0,2], [Nat, Bool])) == Ty([Nat,Fin(0),Bool], Unit)
assert q(Ty([Nat], Unit)) == Var([Nat, Unit], 1)
assert Var([Nat,Unit], 1).ty == Ty([Nat,Unit], Unit)
assert Var([Nat, Unit],0).ty == Ty([Nat, Unit], Nat)
assert lift(Subst([Nat,Unit], [0], [Nat]), Ty([Nat], Bool)) == Subst([Nat,Unit,Bool], [0,2], [Nat,Bool])
Bits and Bobbles
Another direction that is really interesting is mixed prefix unification substitutions. We alternative between blocks of metavars and rigid/object vars. Rigid vars can be thinned but not instantiated. Metavariables can only be instantited to metas or rigids that are earlier in the context.
It might be interesting to try and add some terms to this. GATs
FOLDS?
Maybe forest terms still makes sense if you talk about relative telescopes. G |- ts : D in the forest term sense is roughly G,D |- ts : D in the subsitution / context mapping sense
If we introduce more terms than just var but have careful stratificaiton, we could keep the possible terms and judgements finite. This would be like EPR for types? Effectively Propositional Type Theory?
You can enumerate all codomain contexts in the above cases. Kind of interesting.
Substitutions kind of correspond to homomorphisms between the dpeendency graphs of the domain and codomain
pavel
https://pavpanchekha.com/blog/against-recursion.html https://pavpanchekha.com/blog/batches.html Hmm. Forest terms as a layout concept? Arenas could have intentional layouts instead of being kind of chaotic (history dependent). Arenas are usually accidentally a preorder traversal, but it could be abother one A forest term could kind of be the analog of a slice? Recusrive block decompositions (F) . (G) . (H) more ordered by term layer?
https://dl.acm.org/doi/pdf/10.1145/3314221.3314626 tree traversal fusion
Forest terms kind of expose parallelism of tree processing. Using pair vs kron could be interpreted as aparalelism point
slices of arenas exposing parallelism via kron One could interpret
monoidal categories symmettric monoidal - include permutations
GATs
https://www.youtube.com/watch?v=imz9UkdQBdI&t=1959s how to define type theories - throsten
https://www.youtube.com/watch?v=tTZFKkyJEtw&t=6074s depednetly sorted syntax and semantics - angiuli
Some good examples f : x -> List (x^2 + x + 1) f(3) : ? does it normalize or not
List(3^2 + 3 + 1) =? List(13) type equality
Streicher - Smeantics of Type Theory https://link.springer.com/book/10.1007/978-1-4612-0433-6 Initiality theorem
https://arxiv.org/pdf/1406.3219 natural models of type theor y awodey
Theory of signatures. One simple (dependent) type theory to define others in. An LF. El
Some pretty interesting operations in PODTT
subst extensions gamma . A := add an identity Basically kron(gamma, id) except dependency makes that more complicated
Sigma_subst ? No such thing as a term. Only Forest Terms of cod 1
invlam is uncurry lam is curry
invlam -> app Make modal types make more sense
Forking operation
What operations does the book actually have https://github.com/codyroux/podtt/blob/main/Podtt/Basic.lean https://www.danielgratzer.com/papers/type-theory-book.pdf#page=47&zoom=100,70,689
Quotient types. If quotient comes with normlaizer or is quotienting by finite set,
def lift(self, f): res = map(f, equiv(self.v)) assert all(x = res[0]) # has to respect the equality assert f(x) == f(norm(x)) # a weaker test.. Or maybe norm outputs a traces [x,y,z,…] all(f(x) == f(y) for y in norm_trace(x)) return res[0]
Atomic Type Theory Effectively Propositional Type Theory
| x,y,z | - y,x |
System F a:Type, x : a, y : a |- x, y, a, a
Thinning as a small category of substitutions
Thinnings, duplication, permutation rigid and flex mixing
from dataclasses import dataclass
@dataclass
class Subst:
ctx : int # total vars
ts : list[int] # vs only
def __post_init__(self):
assert all(0 <= t < self.ctx for t in self.ts)
def is_perm(self):
return self.ctx == len(self.ts) and sorted(self.ts) == list(range(self.ctx))
def is_thin(self): # strictly increasing
start = -1
for t in self.ts:
if t <= start:
return False
start = t
return True
@staticmethod
def proj(d, n):
return Subst(d, [n])
@staticmethod
def perm(t : list[int]):
return Subst(len(t), t)
@staticmethod
def thin(t : list[bool]):
return Subst(len(t), [i for i, b in enumerate(t) if b])
@staticmethod
def id_(n):
return Subst(n, list(range(n)))
def __matmul__(self, other):
assert len(self.ts) == other.ctx
return Subst(self.ctx, [self.ts[t] for t in other.ts])
assert Subst.id_(3) @ Subst.id_(3) == Subst.id_(3)
assert Subst.perm([2,0,1]).is_perm
assert Subst.thin([True, False, True]).is_thin()
class FSubst: # type and terms kept seperate
tyctx : int
ctx : list[int] # which type
tyts : list[int] # which type
ts : list[int] # which var
class FSubst:
# type and term all kind of the same.
ctx : list[int | None] # None if :Type
ts : list[int] # which var
a b c : Ob f : Hom(a,b) g : Hom(b,c) h : Hom(a,c) t : Triangle(a,b,c,f,g,h)
FOLDs
explicit destination telescope?
Bruno - ctx as identity substitutions. That’s an interesting point
UnitSubst
autosubst sigma calculus https://github.com/john-ml/cs7480-categories-for-pl/releases/tag/explainers agda software foundatyions
parallel substitutions
x : A, y : B (x) |- f(x) : C(x,y)
x : A, y : B (x) |- f(x) : C(x,y), g(x,y) : D(x,y)
Dis association — 11:00 AM
D |- g : G
x: A, y: B(x) |- g : z : U, w : V(z)
Bruno Martinez — 11:02 AM
x:A |-y:B(x), z:C(y)
p… — 11:11 AM
x:A |-t:B(x), s:C(t)
x:A |-x + 1:B(x), x * 2:C(x + 1)
x : Nat |- x + 1 : Fin x, 2*x : Fin (x + 1)
Bruno Martinez — 11:15 AM
x : Nat |- y : Vec x String, z : Nat -> y
Ok. so I’m totally off base.
So a identity extension is kind of isomorphic to a term
There might be a coherent system where you automatically include everyting on the left of turnstile into output context. But then you can never shrink the context. But why would you want to D |-inc gamma : G := D |- (id . gamma) : D,G Or the implicit thing would be to always shrink into the minimal context G needs. D |-thin gamma : G := D |- (thin, gamma) : min(D,G), G
Forest terms are maybe like synth and Subst is check or well formed. Forest terms as well scoped preforests
def synth(f: Forest) -> Ctx: ...
def check(f: Forest, cod: Ctx) -> Subst: ...
(x : Nat, y : Fin x) |- (x, x, y) : (z : Nat, w : Nat, v : Fin z) and (x : Nat, y : Fin x) |- (x, x, y) : (z : Nat, w : Nat, v : Fin w) are two different substitutions?
so “variable” isn’t synth anymore.
So forest terms are busted.
The Term judgement x,y,z |- t : A(x,y,z) and single subsitution judgement x,y,z |- (t,) : (A,) are radically different because A(x,y,z) vs A has no dependence
So substitutions aren’t telescopic. They are self contained mappings. Mobius strip to mobvious strip Terms are telescoped though.
@dataclass
class Ty: # PreType?
# ctx : Ctx ?
f : str
args : list[int] # previous vars
# don't even bother
class Term:
ctx : Ctx
term : int
ty : Ty
x : Sphere, y : Sphere, z : Tan(x), w : Tan(y) two points, two tangent spaces
Dependency graph homomorphisms are subsitutions. Hmm. (from target to domain)
https://proofassistants.stackexchange.com/questions/2213/how-to-encode-and-manipulate-parallel-substitutions category of renamings
Do networkx visualization of Subst, graph homomorphism
def to_graph(self):
G = DiGraph()
G.add_vertex(("dom", n)) # -n?
G.add_vertex(("cod", n)) for n in range(len(self.cod))
for n, ty in enumertae(self.cod):
G.add_attribtue(n, ty.f)
for arg in ty.args:
G.add_edge(((n, arg))
for n,ty in enumerate(self.cod)
for n,t in enumerate(self.ts):
G.add_edge(-n, t)
G.add_vertex((True, ))
So the PreTy idea actually makes snese because of how we want to pretty print stuff. PreTy is often what I want printed inside of a judgement. Is there actually something there?
Just atomic subsitutions can’t do enough interesting? Stratified Types and functions to finitize. But does finitization matter here? Not really.
#class PreTerm: ...
class App
f : str
args : PreTerm
#class PreVar
# idx : int
type PreTerm = App | int # var
class Term:
ctx : Ctx
t : PreTerm
ty : PreTy # Ty?
@dataclass
class App:
f : str
args : list[PreTerm]
type PreTerm = App | int
type Ctx = list[PreTerm] #?
@dataclass
class Term:
ctx : Ctx
t : PreTerm
from graphviz import Digraph
def draw(self):
g = Digraph(node_attr={"shape": "box"})
for side, ctx in [("dom", self.dom), ("cod", self.cod)]:
with g.subgraph(name=f"cluster_{side}") as c:
c.attr(label=side)
for i, ty in enumerate(ctx):
c.node(f"{side}{i}", f"{i}: {ty}")
for j, a in enumerate(ty.args):
c.edge(f"{side}{a}", f"{side}{i}",
dir="back", label=str(j))
for i, t in enumerate(self.ts):
g.edge(f"cod{i}", f"dom{t}",
style="dashed", constraint="false")
return g
draw(Subst([Nat,Fin(0),Bool], [0,2], [Nat, Bool]))
draw(Subst([Nat,Fin(0)], [0,0,1], [Nat, Nat, Fin(0)]))
draw(Subst([Nat,Fin(0)], [0,0,1], [Nat, Nat, Fin(1)]))
from dataclasses import dataclass
type Ctx = list[Ty]
type PreTerm = int # ?
emp = []
def is_ctx(ctx : Ctx): # is_telescope
return all(ty.ctx == ctx[:i] for i, ty in enumerate(ctx))
assert is_ctx(emp)
@dataclass
class Ty: # PreType? ctx |- F(x,x,y,z) Type
ctx : list[Ty]
f : str
args : list[int] # previous vars
def __post_init__(self):
assert is_ctx(self.ctx), self.ctx
def subst(self, subst : Subst) -> "Ty": # Delta |- A[gamma] type
assert subst.cod == self.ctx
return Ty(subst.dom, self.f, [subst.ts[i] for i in self.args])
@dataclass
class Subst: # Delta |- gamma : Gamma
dom : list[Ty] # Ctx
ts : list[int]
cod : list[Ty] # Ctx
def __post_init__(self):
assert is_ctx(self.dom), self.dom
assert is_ctx(self.cod), self.cod
assert all(0 <= t < len(self.dom) for t in self.ts)
for t,A in zip(self.ts, self.cod):
B = self.dom[t]
assert B.f == A.f
assert B.args == [self.ts[i] for i in A.args]
#for t in zip(self.ts, self.cod):
# self.dom[t].subst(?) == A.subst(?) for t,A in zip(self.ts, self.cod)
def __getitem__(self, i): ...
# get G |- t:A? or only prefix slices ?
@staticmethod
def id_(ctx: list[Ty]) -> "Subst":
return Subst(ctx, list(range(len(ctx))), ctx)
@staticmethod
def prefix(ctx : Ctx, n : int): # p^n . n-fold composition of weakening (drop last). p^0 = id
assert 0 <= n <= len(ctx)
return Subst(ctx, list(range(n)), ctx[:n])
def __matmul__(self, other): # reverse it?
assert self.dom == other.cod
return Subst(other.dom, [other.ts[i] for i in self.ts], self.cod)
@staticmethod
def thin(ctx: list[Ty], th : list[bool]) -> "Subst":
assert len(ctx) == len(th)
cod = [] # hmm. We need to shift Ty
return Subst(ctx, )
@staticmethod
def perm(ctx : list[Ty], p : list[int]) -> "Subst": # exchange I guess
assert sorted(p) == list(range(len(ctx)))
# shift Ty and confirm dependency structure is ok
def weak(self, A : Ty): ...
# hmm. Maybe A should have ctx
#assert A.ctx == self.ctx
#
def extend(self, a : int, A : Ty):
# self = D |- gam : G
assert A.ctx == self.cod # G |- A type
Ag = A.subst(self)
assert 0 <= a <= len(self.dom)
assert self.dom[a] == Ag # Del |- a : A[gamma]
return Subst(self.dom + [A], self.ts + [len(self.dom)], self.cod + [A])
@staticmethod
def term(ctx : Ctx): # G |- ! : 1
assert is_ctx(ctx), ctx
return Subst(ctx, [], [])
Unit0 = Ty(emp, "Unit", [])
U : Ctx = [Unit0]
Nat0 = Ty(emp, "Nat", [])
N : Ctx = [Nat0]
Fin1 = Ty([Nat0], "Fin", [0])
Nat1 = Ty(N, "Nat", [])
NN : Ctx = [Nat0, Nat1]
Fin2 = Ty([Nat0, Nat1], "Fin", [1])
#Subst(NN,[0], U) # This should fail
Subst([Nat0, Nat0], [0], [Nat0])
#Subst(N, [])
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[26], line 91
87 Fin2 = Ty([Nat0, Nat1], "Fin", [1])
88
89
90 #Subst(NN,[0], U) # This should fail
---> 91 Subst([Nat0, Nat0], [0], [Nat0])
92 #Subst(N, [])
93
94
File <string>:6, in __create_fn__.<locals>.__init__(self, dom, ts, cod)
2 'Could not get source, probably due dynamically evaluated source code.'
Cell In[26], line 30, in Subst.__post_init__(self)
29 def __post_init__(self):
---> 30 assert is_ctx(self.dom), self.dom
31 assert is_ctx(self.cod), self.cod
32 assert all(0 <= t < len(self.cod) for t in self.ts)
33 for t,A in zip(self.ts, self.cod):
AssertionError: [Ty(ctx=[], f='Nat', args=[]), Ty(ctx=[], f='Nat', args=[])]
@dataclass
class Ty:
# ctx?
f : str
args : list[int] # previous vars
def subst(self, s: Subst) -> "Ty":
return Ty(self.f, [s.ts[i] for i in self.args])
type Ctx = list[Ty]
@dataclass
class Subst:
ctx : list[Ty]
ts : list[int] # which var
@staticmethod
def id_(ctx: list[Ty]) -> "Subst":
return Subst(ctx, list(range(len(ctx))))
def cod(self) -> list[Ty]:
return [self.ctx[i] for i in self.ts]
def __matmul__(self, other: "Subst") -> "Subst":
assert self.cod() == [A.subst(self) for A in other.ctx]
return Subst(self.ctx, [self.ts[i] for i in other.ts])
@staticmethod
def thin(ctx : list[Ty], th : list[bool]) -> "Subst":
assert len(ctx) == len(th)
ts = [i for i, keep in enumerate(th) if keep]
return Subst(ctx, ts)
def weak(self, A : Ty) -> "Subst":
assert all(0 <= a < len(self.ctx) for a in A.args)
return Subst(self.ctx + [A], self.ts)
def lift(self, A: Ty) -> Subst: # G . A |- gamma . A # A is in the output context. But why?
return Subst(
self.ctx + [A.subst(self)],
self.ts + [len(self.ctx)]
)
# I guess Term is effectively just Var
# n : Nat, v : Vec n |- v, v
Subst(
[Ty("Nat", []), Ty("Vec", [0])],
[1, 1]
)
Ob = Ty("Ob", [])
Hom = lambda a,b : Ty("Hom", [a, b])
Subst([Ob, Ob, Ob, Hom(0, 1), Hom(1,2)], [0, 1, 2, 3])
Subst(ctx=[Ty(f='Ob', args=[]), Ty(f='Ob', args=[]), Ty(f='Ob', args=[]), Ty(f='Hom', args=[0, 1]), Ty(f='Hom', args=[1, 2])], ts=[0, 1, 2, 3])
import functools
type Ctx = dict[str, Ty]
emp : Ctx = {}
def ctx_union(ctx1: Ctx, ctx2: Ctx) -> Ctx:
common_keys = set(ctx1.keys()) & set(ctx2.keys())
assert all(ctx1[k] == ctx2[k] for k in common_keys)
return {**ctx1, **ctx2}
class Ty:
f : str
args : Subst
def min_ctx(self) -> Ctx:
return self.args.min_ctx()
@dataclass
class Subst:
subst : dict[str, tuple[Term, Ty]]
def min_dom(self) -> set[str]:
functools.reduce(ctx_union, [ctx_union(t.min_ctx(), ty.min_ctx()) for (t, ty) in self.substs.values()])
def min_cod(self) -> Ctx:
return {k: v[1] for k, v in self.dict.items()}
def min_ctx(self) -> Ctx:
return self.dom()
class Term: ...
@dataclass
class Var(Term):
name: str
ty : Ty # but why?
def min_ctx(self) -> Ctx:
return {self.name: self.ty}
type STy = str # simple type
class Ctx: ...
class UntypedCtx(Ctx):
ctx : int
class SCtx(Ctx):
ctx : STy
class DCtx(Ctx):
ctx : list[Ty]
class Ty:
ctx : DCtx
f : str
args : Subst
class Subst
ctx : Ctx
ts : list[UnitSubst]
class UnitSubst: ...
class App(UnitSubst):
ctx : Ctx
f : str
args : Subst
ty : Ty
class Var(UnitSubst):
ctx : Ctx
idx : int
ty : Ty # obviously redudnant. Do we want full redudnant junk or no? Maximal pruning?
class App:
thin : list[bool] # which ones we actually need. But Appg
ctx : Ctx # The smaller context. You know if we have both, just a bool list is probably ok even in dependent setting. This is "just" a cache
# or maybe you could think of it as a polymorphic 'a, 'b, Int, 'c, 'd |- t : A kind of context
from dataclasses import dataclass
# type Ctx = list[Ty] is a wrapper worth it? Or is even the synonym worth it?
@dataclass
class Ctx:
ctx : list[Ty]
def __add__(self, other):
if isinstance(other, Ty):
assert other.ctx == self, (other.ctx, self)
return Ctx(self.ctx + [other])
elif isinstance(other, Ctx):
acc = self
for ty in other.ctx:
acc += ty
return acc
def str_min(self):
return "|-" + ", ".join(ty.str_min() for ty in self.ctx) + " cx"
def __str__(self):
return ", ".join(ty.f for ty in self.ctx)
def var(self, idx: int):
return Var(self, idx)
@dataclass
class Ty:
ctx : Ctx # I guess this is redudnant because it is in Subst?
f : str
args : Subst
# Bulk weakening does kind of make sense. if we have lists
def weak(self, ctx : Ctx): # I'd probably reverse this. I'd weaken B to put an A in context. G, A |- B[p]
assert self.ctx == ctx.ctx[:len(self.ctx.ctx)]
return Ty(self.ctx, self.f, self.args.weak(ctx))
def subst(self, s : Subst): ... # G |- a[subst] : A[subst]
def str_min(self):
return f"{self.f}"
def __str__(self):
return f"{str(self.ctx)} |- {self.f} Type"
class Term: ...
@dataclass
class Var(Term): # Yes every Term has Ctx and ty. Should I repeat them or no? There is a beutiy to being verbose
ctx : Ctx
idx : int
@property
def ty(self):
return self.ctx.ctx[self.idx]
def subst(): ...
def __str__(self):
return f"{str(self.ctx)} |- v{self.idx} : {self.ty.str_min()}"
@dataclass
class Subst:
ctx : Ctx # I guess ctx is reudnant too?
ts : list[Term]
def __post_init__(self):
assert all(t.ctx == self.ctx for t in self.ts)
@staticmethod
def id(ctx : Ctx):
return Subst(ctx, [ctx.var(n) for n in range(len(ctx.ctx))])
def __matmul__(self, other):
assert self.cod == other.ctx
...
def __str__(self):
return f"{str(self.ctx)} |- " + ", ".join(f"{t} : {ty.str_min()}" for t, ty in zip(self.ts, self.cod))
emp : Ctx = Ctx([])
semp : Subst = Subst(emp, [])
Unit : Ty = Ty(emp, "Unit", semp)
G : Ctx = emp + Unit
Flum = Ty(G, "Flum", Subst.id(G))
str(Flum)
'Unit |- Flum Type'
from dataclasses import dataclass
# type Ctx = list[Ty] is a wrapper worth it? Or is even the synonym worth it?
@dataclass
class Ctx:
ctx : list[Ty]
def __add__(self, other):
if isinstance(other, Ty):
assert other.ctx == self, (other.ctx, self)
return Ctx(self.ctx + [other])
elif isinstance(other, Ctx):
acc = self
for ty in other.ctx:
acc += ty
return acc
def str_min(self):
return "|-" + ", ".join(ty.str_min() for ty in self.ctx) + " cx"
def __str__(self):
return ", ".join(ty.f for ty in self.ctx)
@dataclass
class Ty:
ctx : Ctx
f : str
args : Subst
def weak(self, A): # I'd probably reverse this. I'd weaken B to put an A in context. G, A |- B[p]
assert self.ctx == A.ctx
return Ty(self.ctx + A, self.f, self.args)
def subst(self, s : Subst): ... # G |- a[subst] : A[subst]
def str_min(self):
return f"{self.f}"
def __str__(self):
return f"{str(self.ctx)} |- {self.f} Type"
class Term: ...
@dataclass
class Var(Term): # Yes every Term has Ctx and ty. Should I repeat them or no? There is a beutiy to being verbose
ctx : Ctx
idx : int
ty : Ty
def __post_init__(self):
assert self.ty.ctx == self.ctx
@staticmethod
def this(ctx : Ctx, A : Ty):
assert A.ctx == ctx # Well then why bother?
return Var(ctx + A, len(ctx.ctx), A.weak(A))
def weak(self, A : Ty):
assert self.ctx == A.ctx
return Var(self.ctx + A, self.idx, self.ty.weak(A))
def weak_n(self, As : list[Ty]):
acc = self
for A in As:
acc = acc.weak(A)
return acc
def subst(self, s : Subst): ...
def __str__(self):
return f"{str(self.ctx)} |- v{self.idx} : {self.ty.str_min()}"
@dataclass
class Subst:
ctx : Ctx
ts : list[Term]
cod : Ctx # implicit in ts
def __post_init__(self):
assert len(self.ts) == len(self.cod)
#assert all(t.ctx == self.ctx for t in self.ts) # or should it be telescoping?
acc = self.ctx
for t, ty in zip(self.ts, self.cod.ctx):
assert t.ctx == acc
assert t.ty == ty
acc += ty
@staticmethod
def id(ctx : Ctx):
return Subst(ctx, [Var.this(A.ctx, A).weak_n(ctx.ctx[n:]) for n, A in enumerate(ctx.ctx)], ctx.ctx)
def __matmul__(self, other):
assert self.cod == other.ctx
...
def __str__(self):
return f"{str(self.ctx)} |- " + ", ".join(f"{t} : {ty.str_min()}" for t, ty in zip(self.ts, self.cod))
emp = Ctx([]) # |- 1 cx
emp + emp
Unit = Ty(emp, "Unit", None)
u = emp + Unit
uu = u + Unit.weak(Unit)
str(uu)
#((emp + Unit) + Unit.weak(Unit)) +
str(Unit.weak(Unit).weak(Unit.weak(Unit)))
str(Var.this(emp, Unit).weak(Unit.weak(Unit)))
str(Var.this(emp + Unit, Unit.weak(Unit)))
str(Subst.id(emp))
str(Subst.id(emp + Unit))
# How far can we get with just Var?
# Call Unit Nat, I don't give a shit.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[6], line 94
90
91 str(Var.this(emp, Unit).weak(Unit.weak(Unit)))
92 str(Var.this(emp + Unit, Unit.weak(Unit)))
93
---> 94 str(Subst.id(emp))
95 str(Subst.id(emp + Unit))
96 # How far can we get with just Var?
97 # Call Unit Nat, I don't give a shit.
Cell In[6], line 75, in Subst.id(ctx)
73 @staticmethod
74 def id(ctx : Ctx):
---> 75 return Subst(ctx, [Var.this(A.ctx, A).weak_n(ctx.ctx[n:]) for n, A in enumerate(ctx.ctx)], ctx.ctx)
File <string>:6, in __create_fn__.<locals>.__init__(self, ctx, ts, cod)
2 'Could not get source, probably due dynamically evaluated source code.'
Cell In[6], line 68, in Subst.__post_init__(self)
64 assert len(self.ts) == len(self.cod)
65
66 #assert all(t.ctx == self.ctx for t in self.ts) # or should it be telescoping?
67 acc = self.ctx
---> 68 for t, ty in zip(self.ts, self.cod.ctx):
69 assert t.ctx == acc
70 assert t.ty == ty
71 acc += ty
AttributeError: 'list' object has no attribute 'ctx'
@dataclass
class Term: # UnitSubst
# App vs TT vs true vs false
class Subst:
@staticmethod
def id_(ctx : Ctx): ...
@staticmethod
def p(ty : Ty): ... # thin. Gamma,A |- v0, v1,v2,v3 ... : Gamma
def __matmul__(self, other):
@dataclass
class Sbst:
cod : list[]
dom : list[]
ts : list[]
@dataclass
class Ty:
ctx :
t :
@dataclass
class
# mutlisorted first
type Sort = str
@dataclass
class TermSeq:
ctx : list[Sort]
terms : list[Term]
@dataclass
class App(Term):
ctx : list[Sort]
f : Term
args : TermSeq
# x : Int, y : Bool, z : Bool |- x : Int
# I guess terms should carry their types on the output also?
# But obviously it can be inferred / synthed
@dataclass
class Var(Term):
ctx : list[Sort]
n : int
# sort : Sort ?
Mutually defining sure. In what sense am I quotienting? smart constructors? The implementation of subst?
class Term: ...
type Sort = Term
@dataclass
class Ctx:
ctx : list[Sort] # Term are Sorts
def extend(self, term: Term) -> "Ctx":
assert self == term.ctx
return Ctx(self.ctx + [term])
@dataclass
class TermSeq: # Sbst, Forest
ctx : Ctx
terms : list[Term]
@dataclass
class App(Term):
ctx : Ctx
f : str # Term? TermSeq?
args : TermSeq
@dataclass
class Var(Term):
ctx : Ctx
n : int