mates.
I need help with the following code in haskell which is a basic calculator with a basic user interface, however I still can’t get it to run let alone allow me to do the operations that in theory it should do. Can anyone help me by giving me some guidance or telling me where the code is wrong or if it needs anything else? The code:
import System.IO
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Control.Monad
-- Definiciones de parser
expr :: Parser Int
expr = term `chainl1` addop
term :: Parser Int
term = factor `chainl1` mulop
factor :: Parser Int
factor = try (parens expr) <|> integer
addop, mulop :: Parser (Int -> Int -> Int)
addop = (char '+' >> return (+)) <|> (char '-' >> return (-))
mulop = (char '*' >> return (*)) <|> (char '/' >> return div)
parens :: Parser a -> Parser a
parens p = do
char '('
x <- p
char ')'
return x
integer :: Parser Int
integer = do
x <- many1 digit
return (read x)
-- Definiciones de la interfaz de usuario
box :: [String]
box = [ "+---------------+"
, "| |"
, "+---+---+---+---+"
, "| q | c | d | = |"
, "+---+---+---+---+"
, "| 1 | 2 | 3 | + |"
, "+---+---+---+---+"
, "| 4 | 5 | 6 | - |"
, "+---+---+---+---+"
, "| 7 | 8 | 9 | * |"
, "+---+---+---+---+"
, "| 0 | ( | ) | / |"
, "+---+---+---+---+"
]
buttons :: [Char]
buttons = "qcd=123+456-789*0()/"
-- Funciones de la interfaz de usuario
display :: String -> IO ()
display xs = do
cls
showbox
goto (3, 2)
putStr xs
getCh :: IO Char
getCh = do
hSetEcho stdin False
c <- getChar
hSetEcho stdin True
return c
calc :: String -> IO ()
calc xs = do
display xs
c <- getCh
if elem c buttons
then process c xs
else do
beep
calc xs
process :: Char -> String -> IO ()
process c xs
| elem c "qQESC" = quit
| elem c "dDBSDEL" = delete xs
| elem c "=n" = eval xs
| elem c "cC" = clear
| otherwise = press c xs
quit :: IO ()
quit = goto (1, 14)
delete :: String -> IO ()
delete "" = calc ""
delete xs = calc (init xs)
eval :: String -> IO ()
eval xs = case parse expr "" xs of
Left _ -> do
beep
calc xs
Right n -> calc (show n)
clear :: IO ()
clear = calc ""
press :: Char -> String -> IO ()
press c xs = calc (xs ++ [c])
-- Funciones auxiliares para la interfaz de usuario
cls :: IO ()
cls = putStr "ESC[2J"
goto :: (Int,Int) -> IO ()
goto (x,y) = putStr ("ESC[" ++ show y ++ ";" ++ show x ++ "H")
showbox :: IO ()
showbox = mapM_ ((y, xs) -> writeat (1, y) xs) (zip [1..13] box)
writeat :: (Int,Int) -> String -> IO ()
writeat (x,y) xs = do
goto (x,y)
putStr xs
beep :: IO ()
beep = putStr "BEL"
-- Función principal para ejecutar la calculadora
run :: IO ()
run = do
cls
showbox
clear
main :: IO ()
main = run
I have tried mofidicating the libraries and functions, but to no avail.
I need help with the code 🙁
New contributor