I am a Haskell noob feeling stuck on a rather simple function I am attempting to perform. Ultimately my goal is to read a strict ByteString
, use the Get
monad with a decoder to retrieve the first Word32
from the ByteString
, and perform specific functions where Data.Bits.testBit
evaluates to True on various parts of the Word32
.
Here is my example code:
import Data.List
import Data.Char
import Data.Function
import System.Random
import Data.Bits
import Data.Either
import Data.Binary.Strict.Get
import System.IO as SIO
import Data.ByteString.Char8 as B
import Data.Word (Word32)
import Data.ByteString.UTF8 as BU
dateTemplate = "YYMMDDhhmmss"
convertFromString :: String -> ByteString
convertFromString s = BU.fromString s
mahDecoder :: Get Word32
mahDecoder = do
first32Bits <- getWord32be
return first32Bits
main :: IO ()
main = do
let a = runGet mahDecoder (convertFromString dateTemplate)
SIO.putStrLn $ show a
-- When I uncomment these lines I get the problem
--case a of
-- Left val -> SIO.putStrLn "Communist!"
-- Right val -> SIO.putStrLn $ "Fascist!"
When I run the runGet
function on the decoder and pass my ByteString
in main, I can see it returns an Either instance like so:
(Right 1499024717,"DDhhmmss")
When I attempt to case on Left or Right then it fails with the following error:
HSStackOverflowExamp.hs:31:5:
Couldn't match expected type `(Either String Word32, ByteString)'
with actual type `Either t0 t1'
In the pattern: Left val
In a case alternative: Left val -> SIO.putStrLn "Communist!"
In a stmt of a 'do' block:
case a of {
Left val -> SIO.putStrLn "Communist!"
Right val -> SIO.putStrLn $ "Fascist!" }
Any ideas what I am doing wrong here? I get the feeling like I am supposed to read all bytes from the ByteString with the decoder. To be honest I am not entirely sure what the type of a
is here. I still have a very limited understanding of Monads and Monad Transformers. I was hoping that I didn't need to master every one of the Haskell dark arts before I could implement even simple use cases for practice. If the answer is to keep reading then I accept that.