just curious how to rewrite the following function to be called only once during program’s lifetime ?
getHeader :: FilePath -> IO String
getHeader fn = readFile fn >>= return . take 13
Above function is called several times from various functions.
How to prevent reopening of the file if function gets called with the same parameter, ie. file name ?
I would encourage you to seek a more functional solution, for example by loading the headers you need up front and passing them around in some data structure like for example a
Map. If explicitly passing it around is inconvenient, you can use aReaderorStatemonad transformer to handle that for you.That said, you can accomplish this the way you wanted using by using
unsafePerformIOto create a global mutable reference to hold your data structure.I used an
MVarhere for thread safety. If you don’t need that, you might be able to get away with using anIORefinstead.Also, note the
NOINLINEpragma onmemoto ensure that the reference is only created once. Without this, the compiler might inline it intogetHeader, giving you a new reference each time.