haskell - Closing the Handle in desugared code -


does matter if don't close both handles safe how in desugared real world haskell example

import system.io import data.char(toupper)  main :: io () main =         inh <- openfile "input.txt" readmode        outh <- openfile "output.txt" writemode        mainloop inh outh        hclose inh        hclose outh  mainloop :: handle -> handle -> io () mainloop inh outh =      ineof <- hiseof inh        if ineof            return ()            else inpstr <- hgetline inh                    hputstrln outh (map toupper inpstr)                    mainloop inh outh 

to

capitalize = openfile "input.txt" readmode >>=              \x -> hgetcontents x >>=              \y -> openfile "output2.txt" writemode >>=              \z -> hputstrln z (fmap toupper y) 

everything works except "output2.txt" file has ^m character @ end of each line.

you're closing handles in happy path. must use withfile or bracket instead handles closed when exception thrown.

for example:

capitalize = withfile "input.txt" readmode $              \x -> hgetcontents x >>=              \y -> withfile "output2.txt" writemode $              \z -> hputstrln z (fmap toupper y) 

without withfile:

capitalize = openfile "input.txt" readmode >>=              \x -> hgetcontents x >>=              \y -> openfile "output2.txt" writemode >>=              \z -> hputstrln z (fmap toupper y) >>              hclose x >>              hclose z 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -