Haskell 从Get monad读取位的一元方法
我需要从Get monad中读取一些位。现在我的代码看起来像Haskell 从Get monad读取位的一元方法,haskell,state-monad,Haskell,State Monad,我需要从Get monad中读取一些位。现在我的代码看起来像 readBits :: Int -> Int -> Get (Word32, Int) readBits count state = ... readValue :: Get (Word32, Word32) readValue = do -- read fst bit count (bits1, s0) <- readBits 5 0 -- read bits1 bits as fst
readBits :: Int -> Int -> Get (Word32, Int)
readBits count state = ...
readValue :: Get (Word32, Word32)
readValue = do
-- read fst bit count
(bits1, s0) <- readBits 5 0
-- read bits1 bits as fst
(fst, s1) <- readBits bits1 s0
-- read snd bit count
(bits2, s2) <- readBits 5 s1
-- read bits2 bits as snd
(snd, s3) <- readBits bits2 s2
-- flush incomplete byte
when (s3 /= 0) $ skip 1
return (fst, snd)
readBits::Int->Int->Get(Word32,Int)
读取位计数状态=。。。
readValue::Get(Word32,Word32)
readValue=do
--读取fst位计数
(bits1,s0)这是Monad变压器最典型的用例
您已经正确定义了大部分结构。回答你的问题
What functions should I implement?
- 首先需要将
Get
monad包装到StateT
转换器中,以获取位读取器
- 您需要使用
get
为readBits
实现正确的定义,以获取当前状态,并使用put
将状态保存回来
- 您需要运行用
位读取器
包装的代码,以在get
Monad中获取输出。因此,您需要使用runStateT
定义runBitReader
来回答你的下一个问题
How should they be implemented?
我已经给出了可能的实施方案。您仍然需要定义一些函数才能使其正常工作
import Control.Monad.State
import qualified Control.Monad.State as ST
import Data.Binary
type BitReader = StateT Int Get
readBits' :: Int -> Int -> Get (Word32, Int)
readBits' = undefined
readBits :: Int -> BitReader Word32
readBits n = do
s0 <- ST.get
(a,s1) <- lift $ readBits' n s0
ST.put s1
return a
runBitReader :: BitReader a -> Get a
runBitReader w = do
(a,s) <- runStateT w 0
return a
readValue = do
fst <- readBits 5
snd <- readBits 10
return (fst, snd)
import Control.Monad.State
导入合格的控件。单子状态为ST
导入数据。二进制
类型BitReader=StateT Int Get
readBits'::Int->Int->Get(Word32,Int)
readBits'=未定义
readBits::Int->BitReader Word32
读取位n=do
s0
import Control.Monad.State
import qualified Control.Monad.State as ST
import Data.Binary
type BitReader = StateT Int Get
readBits' :: Int -> Int -> Get (Word32, Int)
readBits' = undefined
readBits :: Int -> BitReader Word32
readBits n = do
s0 <- ST.get
(a,s1) <- lift $ readBits' n s0
ST.put s1
return a
runBitReader :: BitReader a -> Get a
runBitReader w = do
(a,s) <- runStateT w 0
return a
readValue = do
fst <- readBits 5
snd <- readBits 10
return (fst, snd)