hugs File I/O problem 
Author Message
 hugs File I/O problem

Hi,

I've got another problem that I've worked at for a while and can't seem to
crack which should be pretty simple. ( I think)

I need to read a file and manipulate it's contents like a string. How does
one convert IO() to String?
If I could get this function to work I think I should be able to get to
concept.

Quote:
> lineCount :: FilePath -> Int
> lineCount fp = (length.lines.readFile) fp

The error from this is that lines can't take IO, it needs a string.

Thanks for any help

Sam



Wed, 07 Feb 2001 03:00:00 GMT  
 hugs File I/O problem
Hello!


Quote:

>I need to read a file and manipulate it's contents like a string. How does
>one convert IO() to String?

One cannot (frankly, one *can* in some Haskell implementations with
a function called unsafePerformIO :: IO a -> a, but as the name indicates,
it is unsafe).

Quote:
>If I could get this function to work I think I should be able to get to
>concept.
>> lineCount :: FilePath -> Int
>> lineCount fp = (length.lines.readFile) fp
>The error from this is that lines can't take IO, it needs a string.

Because reading a file is an interaction with the outside world,
counting the number of lines in the file is, too. So
lineCount should have this type signature:
  lineCount :: FilePath -> IO Int
(lineCount maps a file path to an IO action yielding an Int when
it is eventually performed).

Because IO is a functor, you can lift a function of type
  a -> b
to type
  IO a -> IO b
with map.

So, you can define this:

lineCount :: FilePath -> IO Int
lineCount = map (length . lines) . readFile

Or you can use the do notation like this:

lineCount path = do
    content <- readFile path
    return $ (length . lines) content

The type signature is the same.

Regards,

Felix.



Thu, 08 Feb 2001 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Reading lines from file in Hugs 1.4

2. small hugs problem

3. Hugs Graphics Library problem

4. hugs 98 Float problems - can anyone help?

5. Int(eger) conversion problem in Haskell/HUGS?

6. small hugs problem

7. Problems with HUGS...

8. Clean 1.0 Unzip file (was problem in OS/2 installation)

9. Possible file open problem - OS/2 classic Rexx

10. File I/O problems in OS/2 REXX

11. Problem opening files while using os.path.walk

12. OS/2: Rexx Script from Win-OS file manager

 

 
Powered by phpBB® Forum Software