This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
optimizeAdd :: ExprR Expr -> Expr | |
optimizeAdd op@(Op Add _) = optimizeOp op 0 (+) | |
optimizeAdd e = Fix e | |
optimizeMul :: ExprR Expr -> Expr | |
optimizeMul op@(Op Mul xs) | |
| not (null (dropWhile (/= cst 0) xs)) = cst 0 | |
| otherwise = optimizeOp op 1 (*) | |
optimizeMul e = Fix e | |
optimizeOp :: ExprR Expr -> Int -> (Int -> Int -> Int) -> Expr | |
optimizeOp (Op optType xs) neutral combine = | |
let (constants, vars) = partition isCst xs | |
constantsVal = map (\(Fix (Cst x)) -> x) constants | |
sumCst = foldl' combine neutral constantsVal | |
in case vars of | |
[] -> cst sumCst | |
[y] | sumCst == neutral -> y | |
ys | sumCst == neutral -> Fix (Op optType ys) | |
ys -> Fix (Op optType (cst sumCst : ys)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment