Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -0,0 +1,39 @@
data Expression = Const String | Exp Expression String Expression
precedence :: Expression -> Int
precedence (Const _) = 5
precedence (Exp _ op _)
| op `elem` ["^"] = 4
| op `elem` ["*","/"] = 3
| op `elem` ["+","-"] = 2
| otherwise = 0
leftAssoc :: Expression -> Bool
leftAssoc (Const _) = False
leftAssoc (Exp _ op _) = op `notElem` ["^","*","+"]
rightAssoc :: Expression -> Bool
rightAssoc (Const _) = False
rightAssoc (Exp _ op _) = op `elem` ["^"]
instance Show Expression where
show (Const x) = x
show exp@(Exp l op r) = left++" "++op++" "++right
where left = if leftNeedParen then "( "++(show l)++" )" else show l
right = if rightNeedParen the "( "++(show r)++" )" else show r
leftNeedParen = (leftPrec < opPrec) || ((leftPrec == opPrec) && (rightAssoc exp))
rightNeedParen = (rightPrec < opPrec) || ((rightPrec == opPrec) && (leftAssoc exp))
leftPrec = precedence l
rightPrec = precedence r
opPrec = precedence exp
buildExp :: [Expression] -> String -> [Expression]
buildExp stack x
| not.isOp $ x = Const x : stack
| otherwise = Exp l x r : rest
where r:l:rest = stack
isOp = (`elem` ["^","*","/","+","-"])
main = do
contents <- getContents
mapM_ (print.head.(foldl buildExp []).words) (lines contents)