Haskell calculator - haskell

Here is my new main with the error: parse error on input '->'
I commented where the error is. Could it be an indentation error somewhere?
main :: IO()
main = do
expression <- evaluate_input
putStrLn $ show $ compute expression
evaluate_input :: IO ()
evaluate_input = do
args <- getArgs
case args of
a:s -> return a
-> do putStrLn "Enter Expression or 'end' to exit calculator"
hFlush stdout
getLine
unless (expression -> "end") $ showExpr expression --error here
where
showExpr expression = do putStrLn $ evaluateExpr expression
evaluate_input
evaluateExpr :: String -> String
evaluateExpr = show

Few problems with your code
until is not used correctly. I find it better to recurse when I have to repeat same action again and again. You can write the monadic version of until and use that.
It is better to use getArgs inside main once. You don't need to repeat it every time.
A corrected version is here. I haven't implemented all the functions so you still need to do the hard work of parsing and evaluating expressions.
import Control.Monad (unless)
main :: IO ()
main = evaluate
evaluate :: IO ()
evaluate = do
putStrLn "Enter Expression"
expr <- getLine
unless (expr == "end") $ showExpr expr
where
showExpr expr = do putStrLn $ evaluateExpr expr
evaluate
evaluateExpr :: String -> String
evaluateExpr = show

Related

Haskell: Handling resulting Either from computations

I have revisited Haskell lateley and constructed a toy programming language parser/interpreter. Using Parsec for lexing and parsing and a separate interpreter. I'm running in to some issues with feeding the result from the parser to my interpreter and handle the potential error from both the interpreter and parser. I end up with something like this:
main = do
fname <- getArgs
input <- readFile (head fname)
case lparse (head fname) input of
Left msg -> putStrLn $ show msg
Right p -> case intrp p of
Left msg -> putStrLn $ show msg
Right r -> putStrLn $ show r
This dosn't look pretty at all. My problem is that lparse returns Either ParseError [(String, Stmt)] and itrp returns the type Either ItrpError Stmt so I'm having a real hard time feeding the Right result from the parser to the interpreter and at the same time bail and print the possible ParseError or IntrpError.
The closest to what i want is something like this
main = do
fname <- getArgs
input <- readFile (head fname)
let prog = lparse (head fname) input
(putStrLn . show) (intrp <$> prog)
But this will not surprisingly yield a nested Either and not print pretty either.
So are there any nice Haskell ideomatic way of doing this threading results from one computation to another and handling errors (Lefts) in a nice way without nesting cases?
Edit
adding types of lparse and itrp
lparse :: Text.Parsec.Pos.SourceName -> String -> Either Text.Parsec.Error.ParseError [([Char], Stmt)]
intrp :: [([Char], Stmt)] -> Either IntrpError Stmt
While not perfect, I'd create a helper function for embedding any Showable error from Either into MonadError:
{-# LANGUAGE FlexibleContexts #-}
import Control.Monad.Except
strErr :: (MonadError String m, Show e) => Either e a -> m a
strErr = either (throwError . show) return
Then if you have a computation that can fail with errors, like
someFn :: ExceptT String IO ()
someFn = strErr (Left 42)
you can run it (printing errors to stdout) as
main :: IO ()
main = runExceptT someFn >>= either putStrLn return
In your case it'd be something like
main = either putStrLn return <=< runExceptT $ do
fname <- liftIO getArgs
input <- liftIO $ readFile (head fname)
prog <- strErr $ lparse (head fname) input
r <- strErr $ interp prog
print r
Well, if you want to chain successful computations, you can always use >>= to do that. For instance in your case:
lparse (head fname) input >>= intrp
And if you want to print out either your error message you can use the either class that takes two handler functions, one for the case when you have Left a (error in your case) and another for Right b (in your case a successful thing). An example:
either (putStrLn . show) (putStrLn . show) (lparse (head fname) input >>= intrp)
And if anything fails in your chain (any step of your monadic chain becomes Left a) it stops and can for instance print out the error message in the above case.

type of main function doesn't mean to my application

As we know main function has type IO ().
However, it is problem for me, because my program may return error. It means that I am executing from main function something like that:
ErrorT String IO ()
Of course, at this moment I have problem with type errors.
What should I do ?
args <- getArgs
s <- readFile $ head args
myFoo s
Where myFoo :: String -> ErrorT String IO ()
You need to run it with runErrorT:
runErrorT :: ErrorT e m a -> m (Either e a)
Since myFoo returns a ErrorT String IO () this will evaluate to an IO (Either String ()) which you execute in main and match on the result:
args <- getArgs
s <- readFile $ head args
result <- runErrorT (myFoo s)
case result of
Right _ -> putStrLn "ok!"
Left(err) -> putStrLn $ "Error: " ++ err
To expand on #Lee's answer, you can then use exitFailure and exitSuccess from System.Exit to return an appropriate error code to the calling process:
module Main (main) where
import Control.Monad.Error
import System.Environment
import System.Exit
myFoo :: String -> ErrorT String IO ()
myFoo = undefined
main :: IO ()
main = do
args <- getArgs
s <- readFile $ head args
result <- runErrorT (myFoo s)
case result of
Right _ -> do
putStrLn "OK"
exitSuccess
Left (e) -> do
putStrLn $ "Error: " ++ e
exitFailure

Perform simple IO in Haskeline, inside InputT monad, without having to resort to unsafePerformIO

Given the proof of concept code below I'd like to be able to somehow perform my foo function with the ability to output the string Paul! and the possibility of getting its return value inside the InputT monad-transformer without using unsafePerformIO to remove the IO wrapper after runExceptT.
import Control.Monad.Except
import System.IO.Unsafe (unsafePerformIO)
import System.Console.Haskeline
type ErrorWithIO = ExceptT String IO
foo :: String -> ErrorWithIO String
foo "paul" = do liftIO $ putStrLn "Paul!"
return "OK!"
foo _ = throwError "ERROR!"
runRepl :: IO ()
runRepl = runInputT defaultSettings $ loop
loop :: InputT IO ()
loop = do
line <- getInputLine "> "
case line of
Nothing -> return ()
Just input -> do return $ putStrLn "asd"
case unsafePerformIO $ runExceptT $ foo input of
Left err -> outputStrLn err >> loop
Right res -> do
x <- outputStrLn . show $ res
loop
main :: IO ()
main = runRepl >> putStrLn "Goodbye!"
Am I missing something obvious here?
Since InputT IO is a MonadIO, you can use liftIO with this type:
liftIO :: IO a -> InputT IO a
So,
do ...
x <- liftIO $ runExceptT $ foo input
case x of
Left err -> ...
Right res -> ...
Alternatively, use Control.Monad.Trans.lift instead.

Couldn't match expected type - Haskell Code

I'm trying to learn Haskell, but the small bit of sample code I tried to write is running into a fairly large amount of "Couldn't match expected type" errors. Can anyone give me some guidance as to what I'm doing wrong/how I should go about this?
These are the errors, but I'm not really sure how I should be writing my code.
toDoSchedulerSimple.hs:6:14:
Couldn't match expected type `[t0]' with actual type `IO String'
In the return type of a call of `readFile'
In a stmt of a 'do' block: f <- readFile inFile
In the expression:
do { f <- readFile inFile;
lines f }
toDoSchedulerSimple.hs:27:9:
Couldn't match expected type `[a0]' with actual type `IO ()'
In the return type of a call of `putStr'
In a stmt of a 'do' block: putStr "Enter task name: "
In the expression:
do { putStr "Enter task name: ";
task <- getLine;
return inFileArray : task }
toDoSchedulerSimple.hs:34:9:
Couldn't match expected type `IO ()' with actual type `[a0]'
In a stmt of a 'do' block:
putStrLn "Your task is: " ++ (inFileArray !! i)
In the expression:
do { i <- randomRIO (0, (length inFileArray - 1));
putStrLn "Your task is: " ++ (inFileArray !! i) }
In an equation for `getTask':
getTask inFileArray
= do { i <- randomRIO (0, (length inFileArray - 1));
putStrLn "Your task is: " ++ (inFileArray !! i) }
toDoSchedulerSimple.hs:41:9:
Couldn't match expected type `[a0]' with actual type `IO ()'
In the return type of a call of `putStr'
In a stmt of a 'do' block:
putStr "Enter the task you would like to end: "
In the expression:
do { putStr "Enter the task you would like to end: ";
task <- getLine;
filter (endTaskCheck task) inFileArray }
toDoSchedulerSimple.hs:60:53:
Couldn't match expected type `IO ()'
with actual type `[String] -> IO ()'
In a stmt of a 'do' block: schedulerSimpleMain
In the expression:
do { (getTask inFileArray);
schedulerSimpleMain }
In a case alternative:
"get-task"
-> do { (getTask inFileArray);
schedulerSimpleMain }
This is the code itself. I think it's fairly straightforward, but the idea is to run a loop, take input, and perform actions based off of it by calling other functions.
import System.Random (randomRIO)
import Data.List (lines)
initializeFile :: [char] -> [String]
initializeFile inFile =
do f <- readFile inFile
let parsedFile = lines f
return parsedFile
displayHelp :: IO()
displayHelp =
do putStrLn "Welcome to To Do Scheduler Simple, written in Haskell."
putStrLn "Here are some commands you might find useful:"
putStrLn " 'help' : Display this menu."
putStrLn " 'quit' : Exit the program."
putStrLn " 'new-task' : Create a new task."
putStrLn " 'get-task' : Randomly select a task."
putStrLn " 'end-task' : Mark a task as finished."
putStrLn " 'view-tasks' : View all of your tasks."
quit :: IO()
quit =
do putStrLn "We're very sad to see you go...:("
putStrLn "Come back soon!"
createTask :: [String] -> [String]
createTask inFileArray =
do putStr "Enter task name: "
task <- getLine
return inFileArray:task
getTask :: [String] -> IO()
getTask inFileArray =
do i <- randomRIO (0, (length inFileArray - 1))
putStrLn "Your task is: " ++ (inFileArray !! i)
endTaskCheck :: String -> String -> Bool
endTaskCheck str1 str2 = str1 /= str2
endTask :: [String] -> [String]
endTask inFileArray =
do putStr "Enter the task you would like to end: "
task <- getLine
return filter (endTaskCheck task) inFileArray
viewTasks :: [String] -> IO()
viewTasks inFileArray =
case inFileArray of
[] -> do putStrLn "\nEnd of tasks."
_ -> do putStrLn (head inFileArray)
viewTasks (tail inFileArray)
schedulerSimpleMain :: [String] -> IO()
schedulerSimpleMain inFileArray =
do putStr "SchedulerSimple> "
input <- getLine
case input of
"help" -> displayHelp
"quit" -> quit
"new-task" -> schedulerSimpleMain (createTask inFileArray)
"get-task" -> do (getTask inFileArray); schedulerSimpleMain
"end-task" -> schedulerSimpleMain (endTask inFileArray)
"view-tasks" -> do (viewTasks inFileArray); schedulerSimpleMain
_ -> do putStrLn "Invalid input."; schedulerSimpleMain
main :: IO()
main =
do putStr "What is the name of the schedule? "
sName <- getLine
schedulerSimpleMain (initializeFile sName)
Thanks, and apologies if this isn't the correct place to be asking such a question.
There are several issues with your code, which require varying levels of work to fix. In the order that I discovered them, you have...
Incorrect Types
Lots of your type signatures are incorrect. If a function does any I/O at all, it needs to wrap its return type in IO. For example, instead of
createTask :: [String] -> [String]
you need to have
createTask :: [String] -> IO [String]
which reflects the fact that createTask does I/O (it asks the user for the name of a task).
Fortunately, the fix for this is easy - just delete all your type signatures! This sounds crazy, but it can be very helpful. GHC has a powerful type inference mechanism, which means that types can often be inferred without you specifying them explicitly. In your program, all the types are simple enough to be inferred, so you can delete all your type signatures, load the module in GHCi and type e.g. :t createTask, whereupon the interpreter will tell you the inferred type (which you can then add to the source).
Operator Precedence Issues
In Haskell, function application has the tightest binding. In particular, when you write
putStrLn "Your task is: " ++ (inFileArray !! i)
this is parsed by Haskell as
(putStrLn "Your task is: ") ++ (inFileArray !! i)
which doesn't type check, since the left hand side is of type IO () and the right-hand side is of type String. This is also easy to fix. You simply need to write what you intend, which is either
putStrLn ("Your task is: " ++ (inFileArray !! i))
or
putStrLn $ "Your task is: " ++ (inFileArray !! i)
where the operator $ means "function application with the lowest possible precedence", and is often used to avoid parentheses.
Incorrect List Concatenation
After adding parentheses, your code has the line
return (inFileArray:task)
where inFileArray is of type [String] and task is of type String. Presumably you intend to add task to the end of inFileArray.
The : operator is for adding a single item to the front of a list (an O(1) operation). You can't use it to add items to the end of a list (an O(n) operation). All lists in Haskell are linked lists, so adding an item to the front of the list is fundamentally different to adding it to the end. You want either
return (task:inFileArray)
which will add the task to the front of the list, or
return (inFileArray ++ [task])
which creates a new single-element list from task and uses the list concatenation operator ++ to add it to the end of the list.
Misunderstanding do notation and >>=
This is the most fundamental misunderstanding in your code, and will require the most work to explain. Let's look at the following (highly edited) code snippet:
schedulerSimpleMain :: [String] -> IO () -- 1
schedulerSimpleMain inFileArray = -- 2
do input <- getLine -- 3
case input of -- 4
"new-task" -> schedulerSimpleMain (createTask inFileArray) -- 5
_ -> do putStrLn "Invalid input."; schedulerSimpleMain -- 6
We already know that the type of createTask is [String] -> IO [String]. Therefore line 5 doesn't type check. The function schedulerSimpleMain expects a [String] but you are passing it an IO [String].
What you need to do is unwrap the IO layer from the result of createTask inFileArray, and pass the resulting [String] to schedulerSimpleMain (which re-wraps it in the IO layer). This is exactly what the operator >>= (pronounced bind) does. You can write this line as
createTask inFileArray >>= schedulerSimpleMain
where you can think of the >>= operator as "piping forward" the result (a bit like the Unix pipe operator) but also doing all the necessary unwrapping/rewrapping on the way.
It can be a bit tricky to use the bind operator correctly when you're just starting out, which is one of the reasons we're provided with do notation in the first place. You can write this snippet as
do newInFileArray <- createTask inFileArray
schedulerSimpleMain newInFileArray
which is simply syntactic sugar for the code I wrote above, but is a bit more readable if you're not comfortable with the bind operator.
In line 6, you have a different but related problem. The sequencing operator ; essentially means "do the computation on the left, ignore the result, then do the computation on the right". It requires the left computation to have the type IO a and the right computation to have the type IO b (for any a and b).
Unfortunately, your right computation has the type of [String] -> IO [String], so again this line doesn't typecheck. To correct it, you just need to make sure you feed the appropriate argument to schedulerSimpleMain:
do putStrLn "Invalid input."; schedulerSimpleMain inFileArray
which now typechecks. You have this kind of error all over your code. I'm not going to detail all of the fixes for you here. I think you should try and fix it yourself first. If you're still running into problems in a day or so, I can put the corrected code on hpaste for you to study.
I suggest you to break your program in smaller bits and test them one by one.
I've fixed a couple of your functions: you can do similarly for the others.
import System.Random (randomRIO)
import Data.List (lines)
-- ERROR
-- f.hs:6:14:
-- Couldn't match expected type `[t0]' with actual type `IO String'
-- In the return type of a call of `readFile'
-- In a stmt of a 'do' block: f <- readFile inFile
-- In the expression:
-- do { f <- readFile inFile;
-- let parsedFile = lines f;
-- return parsedFile }
-- WHY?
-- initializeFile reads a file, therefore it must live inside the IO monad
initializeFile :: String -> IO [String]
initializeFile inFile = do
f <- readFile inFile
let parsedFile = lines f
return parsedFile
quit :: IO()
quit = do
putStrLn "We're very sad to see you go...:("
putStrLn "Come back soon!"
-- ERROR
-- f.hs:76:44:
-- Couldn't match expected type `IO ()'
-- with actual type `[String] -> IO ()'
-- In a stmt of a 'do' block: schedulerSimpleMain
-- In the expression:
-- do { putStrLn "Invalid input.";
-- schedulerSimpleMain }
-- In a case alternative:
-- _ -> do { putStrLn "Invalid input.";
-- schedulerSimpleMain }
-- WHY?
-- in the "_" case, schedulerSimpleMain is called without parameters, but
-- it needs a [String] one.
schedulerSimpleMain :: [String] -> IO()
schedulerSimpleMain inFileArray = do
putStr "SchedulerSimple> "
input <- getLine
case input of
"quit" -> quit
_ -> do putStrLn "Invalid input."; schedulerSimpleMain inFileArray
main :: IO()
main = do
putStr "What is the name of the schedule? "
sName <- getLine
-- Extract the lines from the IO monad
ls <- initializeFile sName
-- Feed them to the scheduler
schedulerSimpleMain ls

Idiomatic way to conditionally process IO in Haskell

I'm writing a little shell script in Haskell which can take an optional argument. However, if the argument is not present, I'd like to get a line from stdin in which to ask for a value.
What would be the idiomatic way to do this in Haskell?
#!/usr/bin/env runhaskell
import Control.Applicative ((<$>))
import Data.Char (toLower)
import IO (hFlush, stdout)
import System.Environment (getArgs)
main :: IO ()
main = do args <- getArgs
-- here should be some sort of branching logic that reads
-- the prompt unless `length args == 1`
name <- lowerCase <$> readPrompt "Gimme arg: "
putStrLn name
lowerCase = map toLower
flushString :: String -> IO ()
flushString s = putStr s >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushString prompt >> getLine
Oh, and if there's a way to do it with something from Control.Applicative or Control.Arrow I'd like to know. I've become quite keen on these two modules.
Thanks!
main :: IO ()
main = do args <- getArgs
name <- lowerCase <$> case args of
[arg] -> return arg
_ -> readPrompt "Gimme arg: "
putStrLn name
This doesn't fit your specific use case, but the question title made me think immediately of when from Control.Monad. Straight from the docs:
when :: Monad m => Bool -> m () -> m ()
Conditional execution of monadic expressions.
Example:
main = do args <- getArgs
-- arg <- something like what FUZxxl did..
when (length args == 1) (putStrLn $ "Using command line arg: " ++ arg)
-- continue using arg...
You can also use when's cousin unless in similar fashion.

Resources