tags:

views:

111

answers:

2
+1  Q: 

Haskell Type error

I am getting a Couldn't match expected type error on this code and am not sure why. Would appreciate it if someone could point me in the right direction as to fixing it.

import qualified Data.ByteString.Lazy as S
import Data.Binary.Get
import Data.Word

getBinary :: Get Word16
getBinary = do
  a <- getWord16be "Test.class"
  return (a)

main :: IO ()
main = do
  contents <- S.getContents
  print getBinary contents

Specifically it cannot match expected type 'S.ByteString -> IO ()' to inferred type 'IO ()'

+5  A: 

Basic stuff, you're missing parenthesis:

print (getBinary contents)

But besides, you'll need to use runGet or something similar to run the code in the Get monad (the parser). Try asking for more detailed training and support in the #haskell IRC channel.

Don Stewart
Yeah, i have tried the final line as print (runGet getBinary contents) but then get the error Couldn't match expected type `bytestring-0.9.1.4:Data.ByteString.Lazy.Internal.ByteString' against inferred type `S.ByteString'which seems to be worse...
Jon
+2  A: 

1) You should tag it as homework, even when the question is small (imho)

2) print (runGet getBinary contents), as dons said.

3) getWord16be doesn't take an argument.

If you were intending to read a file "Test.class" then:

contents <- S.readFile "Test.Class" 

or if you really did want standard input then just eliminate the Test.class:

a <- getWord16be -- note there is no argument

I'm guessing you already know, but usually Get routines are used to get many data fields and pack them into an ADT:

data ExampleStruct = St { field1,field2 :: Word16
                        , field3 :: Word8 } deriving (Eq, Ord, Show)

-- Extract ExampleStruct
--    The data is formatted [Field1 | Field3 | Field2 ] on disk
getBinary = do
    f1 <- getWord16be
    f3 <- getWord8
    f2 <- getWord16be
    return (St f1 f2 f3)
TomMD