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

typeは、実行時に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 に答える
4

の型は でputStrLnはありString -> IO ()ませんString -> IO String

于 2013-01-07T19:35:14.757 に答える