Madderote
Madderote

Reputation: 1137

Combining Maybe, IO and functions outside context result in error

Can't figure out how to make code below work. Tried all possible typesigs I think.

Code

type SerialNumber = (String, Int)
serialList :: Map.Map String SerialNumber
serialList = Map.fromList [("belt drive",("BD",0001))
                          ,("chain drive",("CD",0002))
                          ,("drive pulley",("DP",0003))
                          ,("drive sprocket",("DS",0004))
                          ]
findSerial :: Ord k => k -> Map.Map k a -> Maybe a
findSerial input = Map.lookup input
outOfContext (Just (a, b)) = (a, b)
getSerialFromUser :: IO ()
getSerialFromUser = do
                    putStr "Lookup part: "
                    input <- getLine
                    let output = findSerial input serialList
                    putStrLn "\nFound entry: " ++ output

Error

    • Couldn't match expected type ‘[()]’
                  with actual type ‘Maybe SerialNumber’
    • In the second argument of ‘(++)’, namely ‘output’
      In a stmt of a 'do' block: putStrLn "\nFound entry: " ++ output
      In the expression:
        do putStr "Lookup part: "
           input <- getLine
           let output = findSerial input serialList
           putStrLn "\nFound entry: " ++ output
   |
62 |                     putStrLn "\nFound entry: " ++ output

Trying my first steps in Haskell without the books so please be gentle.

Upvotes: 0

Views: 65

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

In Haskell function application is left associative, which means the expression:

putStrLn "\nFound entry: " ++ output

is parsed as

(putStrLn "\nFound entry: ") ++ output

But you probably expected it to be parsed as:

putStrLn ("\nFound entry: " ++ output)

That's why you need either to specify the parentheses explicitly or use $ operator:

putStrLn $ "\nFound entry: " ++ output

But notice, that output is of SerialNumber type, but (++) takes two lists as an argument. Therefore, you need to revise, which behaviour you want to specify to your program.

Upvotes: 3

Related Questions