Last active
April 5, 2016 06:03
-
-
Save PifyZ/e35535037a2ea7071917 to your computer and use it in GitHub Desktop.
Calculatrice
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
data Expr = | |
Num Float | |
| Add Expr Expr | |
| Sub Expr Expr | |
| Mul Expr Expr | |
| Div Expr Expr | |
deriving (Show) | |
a :: Expr | |
a = Div (Num 5) (Num 2.6) | |
eval :: Expr -> Float | |
eval (Num a) = a | |
eval (Add a b) = eval a + eval b | |
eval (Sub a b) = eval a - eval b | |
eval (Mul a b) = eval a * eval b | |
eval (Div a b) = eval a / eval b | |
parse :: String -> [String] | |
parse [] = [] | |
parse lst@(x:xs) | |
| x == ' ' = parse xs | |
| x `elem` "+-*/" = [[x]] ++ parse xs | |
| x `elem` ['0'..'9'] = [num] ++ parse (drop (length num) xs) | |
where num = parseNum lst | |
parseNum :: String -> String | |
parseNum [] = [] | |
parseNum (x:xs) = | |
if x `elem` ['0'..'9'] | |
then [x] ++ parseNum xs | |
else [] | |
main = | |
putStrLn $ show $ parse "223 + 6" -- [223, "+", 6] | |
{- | |
isAlpha, isNum, isAlphaNum, isIdent, isSymbol :: Char -> Bool | |
isAlpha c = c `elem` ['a'..'z'] || c `elem` ['A'..'Z'] | |
isNum c = c `elem` ['0'..'9'] | |
isAlphaNum c = isAlpha c || isNum c | |
isIdent c = isAlpha c || isNum c || c `elem` ['_'] | |
isSymbol c = c `elem` "+-*/=" | |
val :: Char -> String | |
val c | |
| isAlpha c = "Alpha" | |
| isNum c = "Num" | |
| otherwise = "Nothing" | |
parse :: String -> [String] | |
parse [] = [] | |
parse (x:xs) = if isSymbol x | |
then [[x]] ++ parse(xs) | |
else [parseNum xs] ++ parse(rst) | |
where (_, rst) = parseNum xs | |
parseNum :: String -> String -> (String, String) | |
parseNum [] accum = accum | |
parseNum (x:xs) accum = if isNum x | |
then parseNum xs $ accum ++ [x] | |
else (accum, xs) | |
parseSymbol :: String -> String -> String | |
parseSymbol (x:_) a = a | |
main = | |
-- putStrLn $ val $ parse "9+9" | |
putStrLn $ show $ parseNum "231 + 42" -- ["231", "+", "42"] | |
parseString :: String -> String -> String | |
parseString [] accum = accum | |
parseString (x:xs) accum = if x == '"' | |
then accum | |
else parseString xs $ accum ++ [x] | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment