1

我想实现一个根据性别提出不同问题的功能。但是我没有给它正确的类型。

askDifferentQuestion :: String -> IO String
askDifferentQuestion sex = do
  putStrLn "ciao"

main = do
  sex <- getLine
  askDifferentQuestion sex

如果我执行我得到

test.hs:3:3:
    Couldn't match expected type `String' with actual type `()'
    Expected type: IO String
      Actual type: IO ()
    In the return type of a call of `putStrLn'
    In a stmt of a 'do' block: putStrLn "ciao"
Failed, modules loaded: none.

为什么我做错了?

4

2 回答 2

4

的类型putStrLn不是。String -> IO ()String -> IO String

于 2013-01-07T19:35:14.757 回答
4

类型IO String表示运行时产生的输入/输出操作String。照原样,askDifferentQuestion结果为(),这通常表示一个无关紧要的值。这是因为要运行的唯一操作是putStrLn其类型为IO (),您运行它只是为了它的副作用。

假设您的类型是正确的,请将 的定义更改为askDifferentQuestion提示用户 return响应。例如

askDifferentQuestion :: String -> IO String
askDifferentQuestion sex = putStrLn (q sex) >> getLine
  where q "M" = "What is the airspeed velocity of an unladen swallow?"
        q "F" = "How do you like me now?"
        q "N/A" = "Fuzzy Wuzzy wasn’t fuzzy, was he?"
        q "N" = "Why do fools fall in love?"
        q "Y" = "Dude, where’s my car?"
        q _ = "Why do you park on a driveway and drive on a parkway?"
于 2013-01-07T20:41:19.753 回答