0

私は、IO モナドを含む、do ブロックでの変数代入の仕組みに関する 2 つの場所で、言語について同様の誤解をしていると/思います。(1)それは同じ誤解ですか、(2)それを解決する方法を理解するのを手伝ってもらえますか(回答で、特にこの件に関するお気に入りの参照がある場合)?

すべてが 1 行の場合は操作を正常に実行できますが、読みやすくするために 2 つに分割しようとするとうまくいきません。

パート I: 1 行を 2 行にする

なぜこれが機能するのですか?

ipg :: IO ()
ipg = do
  conn <- connect defaultConnectInfo { connectHost = "0.0.0.0"}
  res <- execute conn "INSERT INTO test (num, data) VALUES (?, ?)" $ MyRecord (Just 200) (Just"Test")
  print res

しかし、これは機能しません

ipg :: IO ()
ipg = do
  conn <- connect defaultConnectInfo { connectHost = "0.0.0.0" }
  q <- "INSERT INTO test (num, data) VALUES (?, ?)" $ MyRecord (Just 200) (Just"Test")
  res <- execute conn q
  print res

私に与えます:

Couldn't match expected type ‘IO a0’
            with actual type ‘q0 -> IO GHC.Int.Int64’
Probable cause: ‘execute’ is applied to too few arguments
In a stmt of a 'do' block: res <- execute conn q

最初と 2 番目の違いは、クエリ部分を q に格納しようとしていることです。

パート II: 2 行を 1 行に

なぜこれが機能するのですか:

myinput :: IO ()
myinput = do
  putStrLn "Please input a number."
  mynum :: Int  <- readLn  
  print mynum

しかし、これは機能しませんか?

myinput :: IO ()
myinput = do
  mynum :: Int <- readLn $ putStrLn "Please input a number."
  print mynum

私に与えます

Couldn't match expected type ‘IO () -> IO Int’
            with actual type ‘IO a0’
The first argument of ($) takes one argument,
4

1 に答える 1