Below is my haskell code.
readTableFile :: String -> (Handle -> IO a) -> IO [a]
readTableFile file func = do
fileHandle <- withFile file ReadMode (\handle -> do
contents <- readDataFrom handle
putStr contents)
where readDataFrom fileHandle = do
isFileEnd <- hIsEOF fileHandle
if isFileEnd
then
return ("")
else
do
info <- hGetLine fileHandle
putStrLn $ func info
readDataFrom fileHandle
But I get an error:
error: parse error on input ‘isFileEnd’
|
270 | isFileEnd <- hIsEOF fileHandle
| ^^^^^^^^^
I don't know why. Please help me
You've got a couple things going on that are contributing here. As the commenter above pointed out, when you get parse errors that look surprising, spacing is always the first thing to look for. However, we could take a look at a couple things that are contributing here:
Your readTableFile is really just one line long. You've got a do block in which the only thing you do is to assign to fileHandle the value from inside the IO monad that withFile ran in. Aside from the fact that withFile is going to return an IO action from your handler (and not the file handle that your naming might imply) your function isn't actually returning an IO action. Let's clean up some:
readTableFile file func = do
withFile file ReadMode (\handle -> do
contents <- readDataFrom handle
putStr contents)
where readDataFrom fileHandle = do
isFileEnd <- hIsEOF fileHandle
[...]
Now we're returning the right type, but you're still going to get a parse error from the isFileEnd <- assignment. Now that we've cleaned up, you can get your code to compile by moving that (and subsequent lines) to the right of the first character of the readDataFrom declaration:
where readDataFrom fileHandle = do
isFileEnd <- hIsEOF fileHandle
[...]
Your top level do is still redundant, but you'll be past your immediate problems.
Hello i was wondering how can you unwrap a value at a later time in the IO monad?
If a<-expression binds the result to a then can't i use (<-expression) as a parameter for a given method eg:
method (<-expression) where method method accepts the result of the evaluation?
Code
let inh=openFile "myfile" WriteMode
let outh=openFile "out.txt" WriteMode
hPutStrLn (<-outh) ((<-inh)>>=getLine)
I have not entered the Monad chapter just basic <- and do blocks but i suppose it has to do with monads.
Then if i want to pass the result if the evaluation to hGetLine can't i use something like:
(<-expression)=>>hGetLine
You already understand that <- operator kind of unwraps IO value, but it's actually the syntax of do notation and can be expressed like this (actually I'm not sure, which results you're trying to achieve, but the following example just reads the content from one file and puts the content to another file):
import System.IO
main = do
inh <- openFile "myfile" ReadMode
outh <- openFile "out.txt" WriteMode
inContent <- hGetLine inh
hPutStrLn outh inContent
hClose outh
According to documentation hGetLine, hPutStrlLn and hClose accept values of Handle type as an argument, but openFile returns IO Handle, so we need to unwrap it using <- operator
But if you want to use >>= function instead, then this is one of the options of doing it:
import System.IO
writeContentOfMyFile :: Handle -> IO ()
writeContentOfMyFile handler =
openFile "myfile" ReadMode >>= hGetLine >>= hPutStrLn handler
main =
withFile "out.txt" WriteMode writeContentOfMyFile
I have the following problem:
I want to read from a file line by line and write the lines to another file. However, I want to return the number of lines.
Therefore, inside a pure function I would use an accumulator like this:
function parameters=method 0 ......
method accu {end case scenario} =accu
method accu {not end case} = accu+1 //and other stuff
How can I achieve the same in a do-block without using another function?
Concrete example
module Main where
import System.IO
import Data.Char(toUpper)
main::IO()
main=do
let inHandle=openFile "in.txt" ReadMode
let outHandle=openFile "out.txt" WriteMode
inHandle>>= \a ->outHandle>>= \b ->loop a b 0>>=print . show
loop::Handle->Handle->Int->IO Int
loop inh outh cnt=hIsEOF inh>>= \l ->if l then return elem
else
do
hGetLine inh>>=hPutStrLn outh
loop inh outh (cnt+1)
Edit
Refactored the way loop gets its parameters
P.S 2 (after K. A. Buhr's thorough response)
I. What I really wanted to achieve, was the last expression of the main method. I wanted to take the multiple IO Actions and bind their results to a method. Specifically:
inHandle>>= \a ->outHandle>>= \b ->loop a b 0>>=print . show
What I do not understand in this case is:
If inHandle>>= is supplied to \a -> and then the result is passed to ...>>=\b, do the variables inside the outer scope get closured in \b?
If not, shouldn't it be >>=\a->..>>= \a b? Shouldn't the inner scope hold a parameter corresponding to the result of the outer scope?
Eliminating the do inside the helper method
What I wanted to know, is if there is a way to glue together multiple actions without them being in a do block.
In my case:
loop::Handle->Handle->Int->IO Int
loop inh outh cnt=hIsEOF inh>>= \l ->if l then return elem
else
do
hGetLine inh>>=hPutStrLn outh
loop inh outh (cnt+1)
Can't I say something like:
if ... then ... elsehPutStrLn=<<action1 [something] v2=<<action2 [something] loop inh outh (cnt+1)
where something could be an operator? I do not know, that is why I am asking.
It looks like the answer to your last question still left you confused.
tl;dr: stop using >>= and =<< until you master the do-block notation which you can do by Googling "understanding haskell io" and working through lots of examples from tutorials.
Long answer...
First, I would suggest avoiding the >>= and =<< operators for now. Even though they are sometimes named "bind", they don't bind variables or bind parameters to methods or anything else like that, and they seem to be tripping you up. You may also find the section about IO from "A Gentle Introduction to Haskell" helpful as a quick introduction to how IO works.
Here's a very short explanation of IO that may help you, and it'll provide a basis for answering your question. Google for "understanding haskell io" to get a more in-depth explanation:
Super short IO explanation in three paragraphs:
(1) In Haskell, any value of type IO a is an IO action. An IO action is like a recipe that can be used (by executing the action) to perform some actual input/output and then produce a value of type a. So, a value of type IO String is an action that, if executed, will perform some input/output and produce a value of type String, while an IO () is an action that, if executed, will perform some input/output and produce a value of type (). In the latter case, because values of type () are useless, actions of type IO () are normally executed for their I/O side effects, such as printing a line of output.
(2) The only way to execute an IO action in a Haskell program is to give it the special name main. (The interactive interpreter GHCi provides more ways to execute IO actions, but let's ignore that.)
(3) IO actions can be combined using do-notation into a larger IO action. A do block consists of lines of the following form:
act -- action to be executed, with the result
-- thrown away (unless it's the last line)
x <- act -- action to be executed, with the result
-- named #x# for later lines
let y = expr -- add a name #y# for the value of #expr#
-- for later lines, but this has nothing to
-- do with executing actions
In the above templates, act can be any expression that evaluates to an IO action (i.e., a value of type IO a for some a). It's important to understand that the do-block does not itself execute any IO actions. Instead, it builds a new IO action that -- when executed -- will execute the given set of IO actions in the order they appear in the do-block, either throwing away or naming the values produced by executing these actions. The value produced by executing the whole do-block will be the value produced by the last line of the do-block (which has to be a line of the first form above).
A simple exmple
Therefore, if a Haskell program includes:
myAction :: IO ()
myAction = do
putStrLn "Your name?"
x <- getLine
let stars = "***"
putStrLn (stars ++ x ++ stars)
then this defines a value myAction of type IO (), an IO action. By itself, it does nothing, but if it is ever executed, then it will execute each of the IO actions (values of type IO a for various types a) in the do-block in the order they appear. The value produced by executing myAction will be the value produced by the last line (in this case, the value () of type ()).
Applied to the problem of copying lines
Armed with this explanation, let's tackle your question. First, how do we write a Haskell program to copy lines from one file to another using a loop, ignoring the problem of counting lines? Here's one way that's fairly similar to your code example:
import System.IO
myAction :: IO ()
myAction = do
inHandle <- openFile "in.txt" ReadMode
outHandle <- openFile "out.txt" WriteMode
loop inHandle outHandle
hClose outHandle
hClose inHandle
Here, if we check the type of one of these openFile calls in GHCi:
> :t openFile "in.txt" ReadMode
openFile "in.txt" ReadMode :: IO Handle
>
we see that it has type IO Handle. That is, this is an IO action that, when executed, performs some actual I/O (namely an operating system call to open a file) and then produces a value of type Handle, which is the Haskell value representing the open file handle. In your original version, when you wrote:
let inHandle = openFile "in.txt" ReadMode
all this did was assign a name inHandle to an IO action -- it didn't actually execute the IO action and so didn't actually open the file. In particular, the value of inHandle of type IO Handle was not itself a file handle, just an IO action (or "recipe") for producing a file handle.
In the version of myAction above, we've used the notation:
inHandle <- openFile "in.txt" ReadMode
to indicate that, if and when the IO action named by myAction is ever executed, it will start by executing the IO action openFile "in.txt" ReadMode" (that is, the value of that expression which has type IO Handle), and that execution will produce a Handle which will be named inHandle. Ditto for the next line to produce and name an open outHandle. We will then pass these open handles to loop in the expression loop inHandle outHandle.
Now, loop can be defined like so:
loop :: Handle -> Handle -> IO ()
loop inHandle outHandle = do
end <- hIsEOF inHandle
if end
then return ()
else do
line <- hGetLine inHandle
hPutStrLn outHandle line
loop inHandle outHandle
It's worth taking a moment to explain this. loop is a fuction that takes two arguments, each Handle. When it's applied to two handles, as in the expression loop inHandle outHandle, the resulting value is of type IO (). That means it's an IO action, specifically, the IO action created by the outer do-block in the definition of loop. This do-block creates an IO action that -- when it is executed -- executes two IO actions in order, as given by the lines of the outer do-block. The first line is:
end <- hIsEOF inHandle
which takes the IO action hEof inHandle (a value of type IO Bool), executes it (which consists of asking the operating system if we've reached the end of file for the file represented by handle inHandle), and names the result end -- note that end will be a value of type Bool.
The second line of the do-block is the entire if statement. It produces a value of type IO (), so a second IO action. The IO action depends on the value of end. If end is true, the IO action will be the value of return () which, if executed, will perform no actual I/O and will produce a value () of type (). If end is false, the IO action will be the value of the inner do-block. This inner do-block is an IO action (a value of type IO ()) which, if executed, will execute three IO actions in order:
The IO action hGetLine inHandle, a value of type IO String that, when executed, will read a line from inHandle and produce the resulting String. As per the do-block, this result will be given the name line.
The IO action hPutStrLn outHandle line, a value of type IO () that, when exectued, will write line to outHandle.
The IO action loop inHandle outHandle, a recursive use of the IO action produced by the outer do-block, which -- when executed -- starts the whole process over again, starting with the EOF check.
If you put these two definitions (for myAction and loop) in a program, they won't do anything, because they're just definitions of IO actions. The only way to have them execute is to name one of them main, like so:
main :: IO ()
main = myAction
Of course, we could have just used the name main in place of myAction to get the same effect, as in the whole program:
import System.IO
main :: IO ()
main = do
inHandle <- openFile "in.txt" ReadMode
outHandle <- openFile "out.txt" WriteMode
loop inHandle outHandle
hClose inHandle
hClose outHandle
loop :: Handle -> Handle -> IO ()
loop inHandle outHandle = do
end <- hIsEOF inHandle
if end
then return ()
else do
line <- hGetLine inHandle
hPutStrLn outHandle line
loop inHandle outHandle
Take some time to compare this to your "concrete example" above, and see where it's different and where it's simliar. In particular, can you figure out why I wrote:
end <- hIsEOF inHandle
if end
then ...
instead of:
if hIsEOF inHandle
then ...
Copying lines with a line count
To modify this program to count lines, a fairly standard way to do it would be to make the count a parameter to the loop function, and have loop produce the final value of the count. Since the expression loop inHandle outHandle is an IO action (above, it's of type IO ()), to have it produce a count we need to give it type IO Int, as you've done in your example. It will still be an IO action but now -- when it is executed -- it'll produce a useful Int value instead of a useless () value.
To make this change, main will have to invoke loop with a starting counter, name the value it produces, and output that value to the user.
To make it absolutely clear: main's value is still an IO action created by a do-block. We're just modifying one of the lines of the do-block. It used to be:
loop inHandle outHandle
which evaluated to a value of type IO () representing an IO action that -- when the whole do-block was executed -- would be executed when its turn came to copy the lines from one file to the other before producing a () value to be thrown away. Now, it's going to be:
count <- loop inHandle outHandle 0
where the right-hand side will evaluate to a value of type IO Int representing an IO action that -- when the whole do-block is executed -- will be executed when its turn comes to copy the lines from one file to the other before producing a count value of type Int to be named count for later do-block steps.
Anyway, the modified main looks like this:
main :: IO ()
main = do
inHandle <- openFile "in.txt" ReadMode
outHandle <- openFile "out.txt" WriteMode
count <- loop inHandle outHandle 0
hClose inHandle
hClose outHandle
putStrLn (show count) -- could just write #print count#
Now, we rewrite loop to maintain a count (taking the running count as a parameter through recursive calls and producing the final value when the IO action is executed):
loop :: Handle -> Handle -> Int -> IO Int
loop inHandle outHandle count = do
end <- hIsEOF inHandle
if end
then return count
else do
line <- hGetLine inHandle
hPutStrLn outHandle line
loop inHandle outHandle (count + 1)
The whole program is:
import System.IO
main :: IO ()
main = do
inHandle <- openFile "in.txt" ReadMode
outHandle <- openFile "out.txt" WriteMode
count <- loop inHandle outHandle 0
hClose inHandle
hClose outHandle
putStrLn (show count) -- could just write #print count#
loop :: Handle -> Handle -> Int -> IO Int
loop inHandle outHandle count = do
end <- hIsEOF inHandle
if end
then return count
else do
line <- hGetLine inHandle
hPutStrLn outHandle line
loop inHandle outHandle (count + 1)
The rest of your question
Now, you asked about how to use an accumulator within a do-block without using another function. I don't know if you meant without using another function besides loop (in which case the answer above satisfies the requirement) or if you meant without using any explicit loop at all.
If the latter, there are a couple of approaches. First, there are monadic loop combinators available in the monad-loops package that can allow you to do the following (to copy without counting). I've also switched to using withFile in place of explicit open/close calls:
import Control.Monad.Loops
import System.IO
main :: IO ()
main =
withFile "in.txt" ReadMode $ \inHandle ->
withFile "out.txt" WriteMode $ \outHandle ->
whileM_ (not <$> hIsEOF inHandle) $ do
line <- hGetLine inHandle
hPutStrLn outHandle line
and you can count lines with a state monad:
import Control.Monad.State
import Control.Monad.Loops
import System.IO
main :: IO ()
main = do
n <- withFile "in.txt" ReadMode $ \inHandle ->
withFile "out.txt" WriteMode $ \outHandle ->
flip execStateT 0 $
whileM_ (not <$> liftIO (hIsEOF inHandle)) $ do
line <- liftIO (hGetLine inHandle)
liftIO (hPutStrLn outHandle line)
modify succ
print n
With respect to removing the last do block from the definition of loop above, there's no good reason to do this. It's not like do blocks have overhead or introduce some extra processing pipeline or something. They're just ways of constructing IO action values. So, you could replace:
else do
line <- hGetLine inHandle
hPutStrLn outHandle line
loop inHandle outHandle (count + 1)
with
else hGetLine inHandle >>= hPutStrLn outHandle >> loop inHandle outHandle (count + 1)
but this is a purely syntactic change. The two are otherwise identical (and will almost certainly compile to equivalent code).
I'm having some trouble understanding a slice of code.
In Real World Haskell Chapter 7 in the section "Working With Files and Handles" the author uses the following piece of code to iterate through a text file and writing every line to a new text file in upper case: (full credit to the author for this code)
-- file: ch07/toupper-imp.hs
import System.IO
import Data.Char(toUpper)
main :: IO ()
main = do
inh <- openFile "input.txt" ReadMode
outh <- openFile "output.txt" WriteMode
mainloop inh outh
hClose inh
hClose outh
mainloop :: Handle -> Handle -> IO ()
mainloop inh outh =
do ineof <- hIsEOF inh
if ineof
then return ()
else do inpStr <- hGetLine inh
hPutStrLn outh (map toUpper inpStr)
mainloop inh outh
The part I don't understand is: How does Haskell know which line to write to the other file?
From what I gather from the code the position in the input file never changes, so by my c-influenced logic, mainloop would be called again with the same input handle, and as such it would read the same line every time, never progressing.
What am I missing here?
The handle that openFile returns is associated with a pointer to the current position in the file. From the docs:
Most handles will also have a current I/O position indicating where the next input or output operation will occur.
Whenever you read a line from that handle via hGetLine this pointer will be advanced to the next line. IIRC that is the same behavior as with C file-handles.
I'm attempting to use the encodeFile and decodeFile functions in Data.Binary to save a very large datastructure so that I don't have to recompute it every time I run this program. The relevant encoding- and decoding-functions are as follows:
writePlan :: IO ()
writePlan = do (d, _, bs) <- return subjectDomain
outHandle <- openFile "outputfile" WriteMode
((ebsP, aP), cacheData) <- preplanDomain d bs
putStrLn "Calculated."
let toWrite = ((map pseudofyOverEBS ebsP, aP),
pseudofyOverMap cacheData) :: WrittenData
in do encodeFile preplanFilename $ encode toWrite
putStrLn "Done."
readPlan :: IO (([EvaluatedBeliefState], [Action]), MVar HeuCache)
readPlan = do (d, _, _) <- return subjectDomain
inHandle <- openFile "outputfile" ReadMode
((ebsP, aP), cacheData) <- decodeFile preplanFilename :: IO WrittenData
fancyCache <- newMVar (M.empty, depseudofyOverMap cacheData)
return $! ((map depseudofyOverEBS ebsP, aP), fancyCache)
The program to calculate and write the file (using writePlan) executes without error, outputting a gigantic binary file. However, when I run the program which takes in this file, executing readPlan results in the error (the program name is "Realtime"):
Realtime: demandInput: not enough bytes
I can't make head nor tail of this, and scouring Google has turned up no substantial documentation or discussion of this message. Any insight would be appreciated!
I am very late to the party, but found this while looking for help with a similar issue. I'm working with the incremental interface for Data.Binary.Get. As you can see in here, the function is defined in Data.Binary.Get.Internal. Now I am guessing, but your decodeFile function probably does some sort of parsing and the error is thrown because the file does not parse completely (i.e. the parser thinks that there must be something else in the file but it reaches EOF already).
Hope that helps anyone with this/similar issues!