toSource.tri (2168B)
1 !import "prelude" !Local 2 3 main = toSource not? 4 -- Thanks to intensionality, we can inspect the structure of a given value 5 -- even if it's a function. This includes lambdas which are eliminated to 6 -- Tree Calculus (TC) terms during evaluation. 7 8 -- `triage` takes four arguments: the first three represent behaviors for each 9 -- structural case in Tree Calculus (Leaf, Stem, and Fork). 10 -- The fourth argument is the value whose structure is inspected. By evaluating 11 -- the Tree Calculus term, `triage` enables branching logic based on the term's 12 -- shape, making it possible to perform structure-specific operations such as 13 -- reconstructing the terms' source code representation. 14 -- triage = (\leaf stem fork : t (t leaf stem) fork) 15 16 -- Base case of a single Leaf 17 sourceLeaf = t (head "t") 18 19 -- Stem case 20 sourceStem = convert : (a rest : 21 t (head "(") -- Start with a left parenthesis "(". 22 (t (head "t") -- Add a "t" 23 (t (head " ") -- Add a space. 24 (convert a -- Recursively convert the argument. 25 (t (head ")") rest))))) -- Close with ")" and append the rest. 26 27 -- Fork case 28 sourceFork = convert : (a b rest : 29 t (head "(") -- Start with a left parenthesis "(". 30 (t (head "t") -- Add a "t" 31 (t (head " ") -- Add a space. 32 (convert a -- Recursively convert the first arg. 33 (t (head " ") -- Add another space. 34 (convert b -- Recursively convert the second arg. 35 (t (head ")") rest))))))) -- Close with ")" and append the rest. 36 37 -- Wrapper around triage 38 toSource_ = y (self arg : 39 triage 40 sourceLeaf -- `triage` "a" case, Leaf 41 (sourceStem self) -- `triage` "b" case, Stem 42 (sourceFork self) -- `triage` "c" case, Fork 43 arg) -- The term to be inspected 44 45 -- toSource takes a single TC term and returns a String 46 toSource = v : toSource_ v "" 47 48 exampleOne = toSource true -- OUT: "(t t)" 49 exampleTwo = toSource not? -- OUT: "(t (t (t t) (t t t)) (t t (t t t)))"