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