Parsing/RPN to infix conversion: Difference between revisions
→{{header|Haskell}}: Fixed typo which broke compilation. Added test in main(). Applied Hlint, Ormolu.
Alextretyak (talk | contribs) m (→{{header|11l}}) |
(→{{header|Haskell}}: Fixed typo which broke compilation. Added test in main(). Applied Hlint, Ormolu.) |
||
Line 1,911:
This solution is a rough translation of the solution provided on RubyQuiz, as linked above.
<lang Haskell>data Expression = Const String | Exp Expression String Expression▼
▲data Expression = Const String | Exp Expression String Expression
precedence :: Expression -> Int
precedence (Const _) = 5
precedence (Exp _ op _)
leftAssoc :: Expression -> Bool
leftAssoc (Const _) = False
leftAssoc (Exp _ op _) = op `notElem` ["^", "*", "+"]
rightAssoc :: Expression -> Bool
rightAssoc (Const _) = False
rightAssoc (Exp _ op _) = op
instance Show Expression where
where
left
| otherwise = show l
rightNeedParen = (rightPrec < opPrec) || ((rightPrec == opPrec) && (leftAssoc exp))▼
right
leftPrec = precedence l▼
leftNeedParen =
(leftPrec < opPrec)
|| ((leftPrec == opPrec) && rightAssoc exp)
rightNeedParen =
(rightPrec < opPrec)
rightPrec = precedence r
opPrec = precedence exp
buildExp :: [Expression] -> String -> [Expression]
buildExp stack x
where
main
main =
mapM_
</lang>▼
"1 4 + 5 3 + 2 3 * * *",
"1 2 + 3 4 +
▲ ]</lang>
▲1 4 + 5 3 + 2 3 * * *
{{Out}}
▲3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
( 1 + 4 ) * ( 5 + 3 ) * 2 * 3
1 * 2 * 3 * 4
1 + 2 + 3 + 4</pre>
=={{header|Icon}} and {{header|Unicon}}==
|