开发者

code wrong haskell Couldn't match expected type `[(Key, Value)]'

what is wrong with this piece of code, its in a case statement

loop :: Table -> IO ()
loop table = do 
        putStr "Command: " 
        x <- getLine
        case x of
              "add" -> do putStr "Key: "; y <- getLine; putStr "Value: ";  z <- getLine; a开发者_高级运维dd y z table; loop table    

add :: Key -> Value -> Table -> Table
add key v table  | table == empty   = [(key, v)]
                 | otherwise        = ((key, v) : remove key table)

type Table = [(Key,Value)]
type Key = String
type Value = String
remove :: Key -> Table -> Table
remove key ((a, b) :table) 
        | key ==a                   = table
        | ((a, b) :table) == empty  = empty
        | otherwise                 = ((a, b) : remove key table)


Here's your function again (reformatted a bit):

loop table = do 
        putStr "Command: " 
        x <- getLine
        case x of "add" -> do 
            putStr "Key: " 
            y <- getLine
            putStr "Value: "
            z <- getLine
            add y z table
            loop table    

The problem is that add y z table isn't an IO action like the putStrs before. You seem to think that the call to add actually modifies the table, which it doesn't!

As for fixing it: try assigning the result of add to something in a let clause. I'm not going to spell it out, since this look like homework.


My guess is that value y table should be putStrLn (value y table).

As things stand, you are looking up the value but not doing anything with the answer you get back.


Assuming that you have

type Key = String

somewhere, your value function is quite obscure here:

| lookup key ((a,b) : table) == Just b  = b

This surely could be simplified to

| key == a = b


You also have some lingering bugs in remove

remove :: Key -> Table -> Table
remove key ((a, b) : etable)
  | key == a = table
  | ((a, b) : table) == empty = empty
  | otherwise = ((a, b) : remove key table)

Ask yourself what should be tested for empty? What happens if a doesn't appear in table?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜