【问题标题】:In what does this simple do notation desugar to?这个简单的 do notation desugar 是为了什么?
【发布时间】:2021-08-17 04:00:23
【问题描述】:

我正在使用AesonNetwork.HTTP。我能够编码一个 json 并将其打印在屏幕上,执行以下操作:

getCode :: String -> IO ResponseCode
getCode url = simpleHTTP req >>= getResponseCode
    where req = getRequest url

main :: IO ()
main = do 
    x <- get "http://jsonplaceholder.typicode.com/todos/1"
    let y = encode x
    B.putStrLn y

但是我不明白这个do 表达式是什么意思。像这样的:

get "http://jsonplaceholder.typicode.com/todos/1" >>= (?)

? 中应该包含什么内容?

我只知道怎么脱糖:

do { x1 <- action1
   ; x2 <- action2
   ; mk_action3 x1 x2 }

到这里

action1 >>= (\ x1 -> action2 >>= (\ x2 -> mk_action3 x1 x2 ))

顺便问一下,action 是什么? https://en.m.wikibooks.org/wiki/Haskell/do_notation 解释的不是很准确。

【问题讨论】:

  • 请一次一个问题,谢谢。
  • B.putStrLn (encode x) 是一个 IO 操作,就像 action1mk_action3 x1 x2 一样。
  • 如果你想要精确的规则,去haskell.org/onlinereport/haskell2010/…
  • Action 是一个非正式的术语,指的是一个包含在 Monad 中的类型的东西,例如 getLine :: IO String 是一个获取一行输入的动作,或者 put :: s -&gt; State s () 是一个修改 State 的动作. IO 和 State 都是 Monad,所以我们可以调用这些动作。

标签: haskell do-notation


【解决方案1】:

get "http://jsonplaceholder.typicode.com/todos/1" &gt;&gt;= (\x -&gt; let y = encode x in B.putStrLn y)

【讨论】:

    【解决方案2】:

    put (x :: s)State s“动作”。

    put :: s -&gt; State s () 是一个从s 类型值到State s“actions”的函数,一个“action”构造函数。

    putStrLn "Hi" 是一个 IO 操作。 putStrLn :: String -&gt; IO () 是一个从 Strings 到 IO 动作的函数,一个“动作”构造函数。

    IO 是一个 Monad。 State s 是一个 Monad。

    “动作”是 M a 类型的任何值,其中 M 是 Monad。

    【讨论】:

      猜你喜欢
      • 2015-08-22
      • 2018-06-23
      • 2016-09-23
      • 1970-01-01
      • 2021-12-27
      • 2016-07-14
      • 2021-08-14
      • 2017-11-15
      • 2019-04-07
      相关资源
      最近更新 更多