How does Haskell remove list usage from this code?

I'm trying to learn Haskell and binary io

I try to read many word32 values and some word8 values (metadata) from a given file At present, I have written a program that only reads the word32 value in the file into the unboxed vector

The problem with this code is that it uses a list (via replicatem) when reading multiple word32 values from a file I want to get rid of the middle list (for efficiency reasons) and want to use bytestring to read data directly in the vector of the file

This is my complete working code

import Data.Word
import qualified Data.ByteString.Lazy as BIN
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.Vector.Un@R_538_2419@ed as V
import Control.Monad
import System.IO

main = do
  h_in  <- openFile "dat.bin" ReadMode
  v <- readInVector 10 h_in 
  putStrLn (show v)
  hClose h_in

readInVector n h_in = do
 bin1 <- BIN.hGet h_in (n*100)
 let ints1 = runGet (replicateM n getWord32le) bin1
 let v = V.fromList (ints1) :: V.Vector Word32
 return v

What should I do? I want a complete working code as the answer, not just a pointer to the document on Haskell's website, which has a lot of text and few working examples

Solution

Vector package has its own replicatemfunction for vectors. You can use it to initialize vectors directly without building an intermediate list

readInVector n h_in = do
  bin1 <- BIN.hGet h_in (n*100)
  return $runGet (V.replicateM n getWord32le) bin1
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>