entry #1
written by IFcoltransG
submitted at
0 likes
guesses
- IFcoltransG (by yui)
- LyricLy (by vspf)
- luatic (by olus2000)
- olus2000 (by Palaiologos)
- taswelll (by LyricLy)
- taswelll (by luatic)
- vspf (by taswelll)
comments 1
lisp.py ASCII text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | QUOTE = '"' QUASIQUOTE = '`' UNQUOTE = ',' std_env = { '+': sum, 'list': list, 'let': {'macro': 'let'}, 'fun': {'macro': 'lambda'}, 'macro': {'macro': 'macro'}, 'select': {'macro': 'select'}, 'eval': {'macro': 'eval'}, 'case': {'macro': 'case'}, 'true': [[]], # just empty binding 'false': [], # no bindings QUOTE: {'macro': 'quote'}, QUASIQUOTE: {'macro': 'quasiquote'}, } def run(exprs, env=std_env): env = dict(env) env_stack = [] value_stack = [] command_stack = list(exprs) while command_stack: match command_stack.pop(): case int(num): value_stack.append(num) case str(ident): value_stack.append(env[ident]) case list([]): value_stack.append([]) case list([func, *args]): command_stack.append({'apply': args}) command_stack.append(func) case {'apply': args}: # when 'apply' runs, func eval'd onto val stack # args not eval'd match value_stack.pop(), args: case func, args if callable(func): command_stack.append( {'call': func, 'arity': len(args)}) for arg in args: command_stack.append(arg) case { 'params': patterns, 'lambda_body': _, 'env': dict(_), } as func, args: # lambda if len(args) != len(patterns): raise ValueError( f'expected parameters {patterns}, found args {args}' ) command_stack.append( {'call': func, 'arity': len(args)}) for arg in args: command_stack.append(arg) case { 'params': patterns, 'macro_body': _, 'env': dict(_), } as func, args: # user macro if len(args) != len(patterns): raise ValueError( f'expected parameters {patterns}, found args {args}' ) # eval result of macro command_stack.append( {'call': {'macro': 'eval'}, 'arity': 1}) command_stack.append( {'call': func, 'arity': len(args)}) while args: # reverse order, args never popped from cmd stack value_stack.append(args.pop()) case {'macro': 'eval'} as func, args: command_stack.append( {'call': func, 'arity': len(args)}) for arg in args: command_stack.append(arg) case {'macro': 'quote'}, [arg]: value_stack.append(arg) case {'macro': 'quasiquote'}, [arg]: match arg: case list([quasiquote, quoted] as arg) if quasiquote == QUASIQUOTE: value_stack.append(arg) case list([unquote, unquoted]) if unquote == UNQUOTE: command_stack.append(unquoted) case list(quoted_list): command_stack.append( [ 'list', *( [QUASIQUOTE, element] for element in quoted_list ), ] ) case _: value_stack.append(arg) case {'macro': 'let'}, [*patterns, body]: command_stack.append({'restore_env': None}) command_stack.append(body) for key, value in patterns: command_stack.append({'set': key}) command_stack.append(value) command_stack.append({'enter_env': {}}) case {'macro': 'lambda'}, [patterns, body]: value_stack.append( {'params': patterns, 'lambda_body': body, 'env': dict(env)} ) case {'macro': 'macro'}, [patterns, body]: value_stack.append( {'params': patterns, 'macro_body': body, 'env': dict(env)} ) case {'macro': 'select'}, list( [(condition, body), *clauses, otherwise] ): command_stack.append( {'select': clauses, 'body': body, 'otherwise': otherwise} ) command_stack.append(condition) case {'macro': 'case'}, list([*patterns, expr] as args): command_stack.append( {'call': {'macro': 'case'}, 'arity': len(args)}) for pattern in patterns: value_stack.append(pattern) command_stack.append(expr) case {'macro': name}, args: raise TypeError( f'expected {name} macro parameters, found {args}' ) case _: raise TypeError(f'expected callable, found {func}') case {'call': func, 'arity': int(arity)}: # func eval'd, args eval'd args = [value_stack.pop() for _ in range(arity)] match func: case { 'params': patterns, 'lambda_body': body, 'env': dict(saved_env), }: # lambda command_stack.append({'restore_env': None}) command_stack.append( { 'apply': [ *([pattern, [QUOTE, arg]] for pattern, arg in zip(patterns, args)), body, ] } ) value_stack.append({'macro': 'let'}) command_stack.append({'enter_env': saved_env}) case { 'params': patterns, 'macro_body': body, 'env': dict(saved_env), }: # user macro command_stack.append({'restore_env': None}) command_stack.append( { 'apply': [ *([pattern, [QUOTE, arg]] for pattern, arg in zip(patterns, args)), body, ] } ) value_stack.append({'macro': 'let'}) command_stack.append({'enter_env': saved_env}) case {'macro': 'eval'}: for arg in args: command_stack.append(arg) case {'macro': 'case'}: [expr, *patterns] = args command_stack.append( {'cases': 'or', 'arity': len(patterns)}) patterns.reverse() for pattern in patterns: command_stack.append( {'case': pattern, 'expr': expr}) case func if callable(func): value_stack.append(func(args)) case func: raise ValueError(f'expected call, found {func}') case {'select': clauses, 'body': body, 'otherwise': otherwise}: match value_stack.pop(): case list([bindings, *_]): # success command_stack.append({'restore_env': None}) command_stack.append(body) command_stack.append( {'enter_env': {key: value for [ key, value] in bindings}} ) case _: match clauses: case []: # no clauses left command_stack.append(otherwise) case [(condition, body), *clauses]: command_stack.append( { 'select': clauses, 'body': body, 'otherwise': otherwise, } ) command_stack.append(condition) case {'case': pattern, 'expr': expr}: match pattern, expr: case list([unquote, str(ident)]), expr if unquote == UNQUOTE: # can bind wildcard value_stack.append([[[ident, expr]]]) case int(pattern), int(expr) if pattern == expr: value_stack.append([[]]) case list(patterns), list(exprs) if len(patterns) == len(exprs): # bind elements command_stack.append( {'cases': 'and', 'arity': len(patterns)}) for pattern, expr in zip(patterns, exprs): command_stack.append( {'case': pattern, 'expr': expr}) case _: value_stack.append([]) case {'cases': 'and', 'arity': arity}: patterns = [value_stack.pop() for _ in range(arity)] matches = [[]] for pattern in patterns: new_matches = [] for match in matches: for option in pattern: new_match = match + option idents = [ident for ident, _ in new_match] if len(idents) == len(set(idents)): new_matches.append(new_match) matches = new_matches value_stack.append(matches) case {'cases': 'or', 'arity': arity}: patterns = [value_stack.pop() for _ in range(arity)] value_stack.append( [pattern for match in patterns for pattern in match]) case {'enter_env': new_env}: env_stack.append(dict(env)) env |= new_env case {'restore_env': None}: env = env_stack.pop() case {'set': key}: env[key] = value_stack.pop() case command: raise ValueError(f'expected command, found {command}') return value_stack def read(s): o = [[]] for symbol in '()[]`,"': s = s.replace(symbol, f' {symbol} ') for t in s.split(): match t: case '(' | '[': o.append([]) case ')' | ']': tmp = o.pop() o[-1].append(tmp) case str(num) if num.isnumeric(): o[-1].append(int(num)) case str(ident): o[-1].append(ident) [o] = o return o tutorials = [ ('(+ 1 2 3)', 6), ('(let (a 1) (b 2) (c 3) (d 4) b)', 2), ('((fun (x) x) 0)', 0), ('((fun (a b c d) b) 1 2 3 4)', 2), ('(select (false 1) (true 2) (true 3) 4)', 2), ('(select (false 1) (false 2) (false 3) 4)', 4), ('true', [[]]), ('false', []), ('(case 1 (+ 1 1))', []), ('(case 2 (+ 1 1))', [[]]), ('(case (, x) (+ 1 1))', [[['x', 2]]]), ('(case [[(,x) (,y) 3] (,z)] (" ((1 2 3) (4 5 6))))', [[['x', 1], ['y', 2], ['z', [4, 5, 6]]]]), ('(select ((case (, x) 1) (+ x 2)) 0)', 3), ('(select ((case ((, x) (, y)) (" (1 2))) (+ x y)) 0)', 3), ('(let (no []) (select (no 0) 1))', 1), ('(let (bind-a (` [[(a (, 0))]])) (select (bind-a a) 1))', 0), ('(case 1 2 3 (,x) (,y) (+ 1 1))', [[], [['x', 2]], [['y', 2]]]), ('(` (1 2 (+ 3 4) (, (+ 5 6))))', [1, 2, ['+', 3, 4], 11]), ('(` (` (, (+ 1 1))))', ['`', [',', ['+', 1, 1]]]), ('((fun () (" (+ 1 1))))', ['+', 1, 1]), ('((macro () (" (+ 1 1))))', 2), ('((macro (x) (` (+ 2 (, x)))) 1)', 3), ('((macro (x y z) (` ((,x) (,y) (,z)))) + 2 3)', 5), ('(let (if (macro (c t f) (` (select ((, c) (, t)) (, f))))) (if true 1 2))', 1), ('(let (x 0) (select [(case 0 x) (" zero)] [(case 1 x)] (" one) (" big)))', 'zero'), ('(let (car (fun (pair) (select [(case [(,car) (,cdr)] pair) car] (" error)))) (car (" [1 2])))', 1), ('(let (cdr (fun (pair) (select [(case [(,car) (,cdr)] pair) cdr] (" error)))) (cdr (" [1 2])))', 2), ] if __name__ == "__main__": for (tutorial, answer) in tutorials: print(tutorial) [o] = run(read(tutorial)) if o != answer: print(f'expected {answer}') print(f'found {o}') print() |
Interesting that line 314 uses double quotes.
post a comment