[Haskell-beginners] Is this scope range problem?

Bastian Erdnüß earthnut at web.de
Tue Dec 14 15:13:33 CET 2010


On Dec 14, 2010, at 14:36, Luca Toscano wrote:

> On 12/14/2010 12:32 PM, Sok H. Chang wrote:
>> Thank you so much, Luca.
>> Mmm... I want to make a "List of Sentence" from some text file.
>> 
>> inputFile.txt is like this.
>> --------------------------------
>> This is a pen.
>> Is this a pen?
>> etc...many sentence. Each line, only one sentence.
>> 
>> How can I make a list of sentence?
>> How can I declared inpStr?
>> 
>> Thank you.
>> 
>> Sincerely, Sok Chang
>> 
> You're welcome! I am a beginner in haskell programming, it's interesting to work with others! By the way, this is the code:
> 
> import System.IO
> import System.Random
> import Data.List
> 
> main :: IO ()
> main = do
>    inh <- openFile "path_to_file" ReadMode
>    prova <- (mainloop inh [])
>    print prova
>    hClose inh
> 
> mainloop :: Handle -> [String] -> IO [String]
> mainloop inh list = do
>    ineof <- hIsEOF inh
>    if ineof
>        then
>            return list
>        else do
>            inpStr <- hGetLine inh
>            mainloop inh (list ++ [inpStr])

the "list ++ [inpStr]" is not very efficient for files with lot's of sentences.  (++) is implemented in a way that it goes through the whole "list" every time a new field is appended.  So, it does a lot of work a multiple times.  Instead you should consider to e.g. use "inpStr : list" and reverse the list in the end.

> This is my version, it works I think.. I hope this helps you!!

Another solution would be

  main = do
    input <- readFile "path_to_file"
    let prova = lines input
    print prova

Cheers,
Bastian




More information about the Beginners mailing list