[Haskell-beginners] Lost in binary input

Moritz Tacke take at informatik.uni-freiburg.de
Sat Nov 8 04:38:46 EST 2008


I'm desperately trying to read a binary file into a list of Word16s.
After heavily borrowing from the
http://www.haskell.org/haskellwiki/DealingWithBinaryData - tutorial
(which accounts for the only few working lines of my code), I am still
left totally lost.
What I need is a piece of code that reads these Word16s and gives them
to me in a way that I can apply usual functions on it - should be
easy, was my first thought some hours ago...

Here is my code:

module BinFileReader
import qualified Data.ByteString.Lazy as ByteString
import Data.Binary.Get
import Data.Word

data FileData = FileData { source_filename::String,
                                     data = [Word16] }
             deriving (Show)

readBinaryString::FilePath -> IO ByteString.ByteString
readBinaryString filename =  do
 input_string <- ByteString.readFile filename
 putStrLn ((show (ByteString.length input_string) ) ++ " Bytes read")
 return input_string

-- Problems start here: Why the hell does the next function know where its
-- data come from? There are no parameters; if I wanted
-- to apply another function inside readAsWord that takes the
bytestring as well as
-- other items, how would I do that?

readAsWords::Get [Word16]
readAsWords = do
 empty <- isEmpty
 if empty
    then return []
    else do v <- getWord16be
            rest <- readAsWords
            return (v : rest)

readBinaryFile::FilePath -> IO FileData
readBinaryFile filename = (FileData filename raw_data)
   where raw_data = readBinaryString filename
         word_list = runGet readAsWords raw_data
         string_length = length word_list

-- And here, it ends... I've been trying my best to find a function
-- that glues all of the above together, but without any success.
-- It should be so trivial, but, somehow, it isn't

Any hints?


More information about the Beginners mailing list