Skip to content

Instantly share code, notes, and snippets.

(defn ptvkegely [c j m n t u y] (+ -64 m c t y n j u))
=> #'user/ptvkegely
(ptvkegely 1 2 3 4 5 6 7)
=> -36
countNodes :: Expr -> Int
countNodes = cata countAlg where
countAlg (Op _ xs) = 1 + sum xs
countAlg _ = 1
e <- generate (genExpr 30)
print e
> "(* (+ s) (+ 14) 30 (* u) -28 (* 16) -24 2 13 w j 27 7 -28 n x (* k) 7 (* h) (* -27))"
countNodes e
> 28
length (prn e)
> 84
para :: (ExprR (a, Expr) -> a) -> Expr -> a
para alg = alg . fmap (para alg &&& id) . unFix
prnInfix :: Expr -> String
prnInfix = para infixAlg where
infixAlg (Op Add xs) = concat (intersperse " + " (map fst xs))
infixAlg (Op Mul xs) = concat (intersperse " * " (map parensPlus xs))
infixAlg (Cst n) = show n
infixAlg (Var v) = v
parensPlus (s, Fix (Op Add _)) = "(" ++ s ++ ")"
parensPlus (s, _) = s
let e = add [ cst(1)
, cst(2)
, mul [cst(0), var("x"), var("y")]
, mul [cst(1), var("y"), add [cst(2), var("x")]]
, add [cst(0), var("x") ]]
prn e
> "(+ 1 2 (* 0 x y) (* 1 y (+ 2 x)) (+ 0 x))"
prnInfix e
data ContestResult = ContestResult {
prefixScore :: Int ,
infixScore :: Int }
deriving (Show)
runContest :: Int -> IO ()
runContest size = do
expressions <- generate (replicateM 1000 (genExpr size))
let run printer = sum $ map (length . printer . optimize) expressions
print $ ContestResult (run prn) (run prnInfix)
runContest 30
> ContestResult {prefixScore = 31951, infixScore = 42293}
runContest 100
> ContestResult {prefixScore = 87662, infixScore = 125822}
prnInfix :: Expr -> String
prnInfix = cata infixAlg where
infixAlg (Op Add xs) = concat (intersperse " + " xs)
infixAlg (Op Mul xs) = concat (intersperse " * " (map parens xs))
infixAlg (Cst n) = show n
infixAlg (Var v) = v
parens x = "(" ++ x ++ ")"
let e = add [ cst(1)
, cst(2)
, mul [cst(0), var("x"), var("y")]
, mul [cst(1), var("y"), add [cst(2), var("x")]]
, add [cst(0), var("x") ]]
prn e
> "(+ 1 2 (* 0 x y) (* 1 y (+ 2 x)) (+ 0 x))"
prnInfix e