Parsing/Shunting-yard algorithm: Difference between revisions

m
→‎{{header|Haskell}}: Applied hlint, ormolu. Added type signatures.
m (Removed useless "sequtils" import.)
m (→‎{{header|Haskell}}: Applied hlint, ormolu. Added type signatures.)
Line 2,237:
<lang Haskell>import Text.Printf
 
prec :: String -> Int
prec "^" = 4
prec "*" = 3
Line 2,243 ⟶ 2,244:
prec "-" = 2
 
leftAssoc :: String -> Bool
leftAssoc "^" = False
leftAssoc _ = True
 
isOp (t:[]): =String t `elem` "-+/*^"> Bool
isOp _[t] = t `elem` = False"-+/*^"
isOp _ = False
 
simSYA xs:: =[String] final-> ++[([String], [lastStepString], String)]
simSYA xs where= final =<> scanl f ([lastStep],[],"") xs
where
lastStep = (\(x,y,_) -> (reverse y ++ x, [], "")) $ last final
final = scanl f (out[],st [],_ "") t | isOp t =xs
lastStep =
(reverse (takeWhile testOp st) ++ out
, (t:) $ \(dropWhilex, testOpy, st_), t)->
| t == "("reverse y =<> (outx, [], "(":st, t)
)
| t == ")" = (reverse (takeWhile (/="(") st) ++ out,
$ last final
tail $ dropWhile (/="(") st, t)
| otherwise =f (t:out, st, _) t)
where testOp x =| isOp x && (leftAssoc t && prec t == prec x
( (reverse (takeWhile testOp st) ++<> out,
|| prec t < prec x)
(t :) (dropWhile testOp st),
t
)
| t == "(" = (out, "(" : st, t)
| t == ")" =
( | t == ")" = (reverse (takeWhile (/= "(") st) ++<> out,
tail $ dropWhile (/= "(") st, t)
t
)
| otherwise = (t : out, st, t)
where
testOp x =
isOp x
&& ( leftAssoc t && prec t == prec x
|| prec t < prec x)
)
 
main :: IO ()
main = do
a <- getLine
printf "%30s%20s%7s" "Output" "Stack" "Token"
mapM_
mapM_ (\(x,y,z) -> printf "%30s%20s%7s\n"
( \(x, y, z) ->
(unwords $ reverse x) (unwords y) z) $ simSYA $ words a</lang>
printf
mapM_ (\(x,y,z) -> printf "%30s%20s%7s\n"
(unwords $ reverse x) (unwords y) z) $ simSYA $ words a</lang>
(unwords y)
z
)
$ simSYA $ words a</lang>
 
Output:
9,655

edits