aoc2020/18.rkt

53 lines
1.4 KiB
Racket
Raw Normal View History

#lang curly-fn racket
(require "scripts/aoc.rkt" parser-tools/lex parser-tools/yacc (prefix-in : parser-tools/lex-sre))
;; solution for day 18
(define-tokens nums [number])
(define-empty-tokens syms [+ * lp rp eof])
2020-12-18 05:40:03 +00:00
(define oo-lexer
(lexer
2020-12-18 05:40:03 +00:00
[whitespace (oo-lexer input-port)]
["+" (token-+)]
["*" (token-*)]
["(" (token-lp)]
[")" (token-rp)]
[(:+ (char-set "0123456789")) (token-number (string->number lexeme))]
[(eof) (token-eof)]))
2020-12-18 05:40:03 +00:00
(define-simple-macro (make-oo-parser/precs needed-precs ...)
(parser
[start exp]
[end eof]
2020-12-18 05:40:03 +00:00
[error (lambda args (error "not shonks:" args))]
[tokens nums syms]
2020-12-18 05:40:03 +00:00
[precs needed-precs ...
(left lp rp)]
[grammar
(exp [(lp exp rp) $2]
[(exp + exp) (+ $1 $3)]
[(exp * exp) (* $1 $3)]
[(number) $1])]))
2020-12-18 05:40:03 +00:00
(define (parse/string oo-parser str)
(let ([input (open-input-string str)])
2020-12-18 05:40:03 +00:00
(oo-parser (thunk (oo-lexer input)))))
(define-simple-macro (define-part name:id needed-precs ...)
(define (name input)
(for/sum ([line (in-list input)])
(parse/string (make-oo-parser/precs needed-precs ...) line))))
(define-part part1 (left + *))
(define-part part2 (left *) (left +))
(define parse file->lines)
(module+ main
(define input (parse "inputs/18"))
(answer 18 1 (time (part1 input)))
(answer 18 2 (time (part2 input)))
(displayln "meow"))