Paste: AOC day 18
Author: | chunes |
Mode: | factor |
Date: | Fri, 18 Dec 2020 10:36:56 |
Plain Text |
USING: assocs combinators.short-circuit
compiler.tree.propagation.call-effect eval io.encodings.ascii
io.files kernel listener literals make math prettyprint qw
sequences sets splitting.extras ;
IN: aoc.2020.18
CONSTANT: input $[ "input.txt" ascii file-lines ]
CONSTANT: precedence
{
{ "(" 0 }
{ ")" 0 }
{ "+" 2 }
{ "*" 1 }
}
: tokenize "( )" split* { " " } without ;
: %s % " " % ;
: op? qw{ * + } member? ;
: (valid-stack?)
{ [ last "(" = ] [ last2 [ precedence at ] bi@ < ] } 1|| ;
: valid-stack?
dup length 2 < [ drop t ] [ (valid-stack?) ] if ;
: slurp
dup pop drop [ dup pop dup "(" = ] [ %s ] until drop ;
DEFER: ?op%
: collapse
dup [ pop ] [ pop ] bi %s suffix! ?op% ;
: pop-op
dup last ")" = [ slurp ] [ collapse ] if ;
: ?op%
dup valid-stack? [ pop-op ] unless ;
: handle-token
dup op? [ suffix! ?op% ] [ %s ] if ;
: infix>postfix
V{ } clone swap tokenize [ [ handle-token ] each ] "" make
swap reverse " " join append ;
: main
input
[ infix>postfix [ (eval) ] with-interactive-vocabs ]
map-sum . ;
New Annotation