Created
June 3, 2016 23:16
-
-
Save IvantheTricourne/39fbdccb44a4c7c1fcc4b7193fc9b9f0 to your computer and use it in GitHub Desktop.
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
module AST where | |
data AST = Val String | |
| Fun [AST] | |
deriving (Show) | |
takeWord :: String -> String -> (AST,String) | |
takeWord "" acc = (Val acc,"") | |
takeWord (' ':cs) acc = (Val acc,cs) | |
takeWord (c:cs) acc = takeWord cs (acc++[c]) | |
toLastParen :: String -> String -> Int -> (String,String) | |
toLastParen "" acc _ = (acc,"") | |
toLastParen (')':s) acc n | |
| n == 0 = (acc,s) | |
| otherwise = toLastParen s (acc++[')']) (n-1) | |
toLastParen ('(':s) acc n = toLastParen s (acc++['(']) (n+1) | |
toLastParen (c:s) acc n = toLastParen s (acc++[c]) n | |
parse :: String -> AST | |
parse s = Fun $ parse' s [] where | |
parse' "" acc = acc | |
parse' ('(':s) acc = parse' rst' (acc ++ [parse s']) | |
where (s',rst) = toLastParen s "" 0 | |
rst' = case rst of -- | |
[] -> [] | |
_ -> tail rst | |
parse' s acc = parse' s' (acc ++ [word]) | |
where (word,s') = takeWord s "" | |
main :: IO () | |
main = do putStrLn "Enter a Lisp expression." | |
lisp <- getLine | |
case lisp of | |
('(':rst) -> -- | |
putStrLn $ show $ parse exp where | |
(exp,_) = toLastParen rst "" 0 | |
_ -> | |
putStrLn $ show $ fst $ takeWord lisp "" | |
-- testing purposes | |
-- putStrLn "" | |
-- main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment