0

我/认为/我在两个地方对语言有类似的误解,涉及变量赋值在 do 块中的工作方式,涉及 IO monad。您能否帮助我理解(1)这是同样的误解,(2)如何清除它(在答案中,也许特别是如果您对此主题有最喜欢的参考资料)?

我发现当它都是一行时我可以成功执行操作,但当我尝试拆分为 2 以提高可读性时却不行。

第一部分:将 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

第一个和第二个之间的区别是尝试将查询部分存储在 q 中。

第二部分:将 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

4
于 2016-08-28T16:16:02.307 回答