Haskell:理解 do 符号与 if-else 语句

标签 haskell functional-programming monads equivalence do-notation

我有以下用于操纵机器人的 API 代码:

data Direction = Left | Right
forward    :: IO ()
blocked :: IO Bool
turn       :: Direction -> IO ()

我试图理解两个程序,它们将使机器人向前移动,除非它被障碍物阻挡,在这种情况下,机器人应该转向正确的方向。

但是,我不确定以下两个程序之间有什么区别:

-- program 1
robot = do
  detected <- blocked
  if detected 
    then turn Right
    else forward
  robot

-- program 2
robot = do
  detected <- blocked
  if detected
    then turn Right
         robot
    else forward
         robot

detected <- blocked从 IO 中取出 bool 值。如果条件if detected评估为真,则机器人向右转,否则机器人向前移动。在程序 1 中,机器人向右或向前移动后再次调用功能机器人。程序2右转或前进后直接调用函数机器人。

我不确定在 if-else 之后调用机器人之间有什么区别语句(在程序 1 中)与在 then 中调用它和 else程序 2 中的案例。我说这两个程序是等价的是否正确?任何见解都值得赞赏。

最佳答案

你说这两个程序是等价的是对的。更一般地,if cond then (x >> action) else (y >> action) 等同于 (if cond then x else y) >> action。这是因为 f (if cond then x else y) = if cond then (f x) else (f y);如果你采取 f = (>> action) 你会得到 monads 的等价物。

关于Haskell:理解 do 符号与 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57213260/

相关文章:

c++ - 连接 Haskell 和 C++

haskell - 访问 'data' 的下一个元素

haskell - 为什么嵌套永远泄漏内存?

Haskell - 有没有办法限制给定函数的执行时间?

javascript - 是否有任一个 (R.either) 的可变参数版本?

clojure - Rebol 中与 Clojure 映射/应用表达式最接近的匹配是什么?

functional-programming - 当我需要多次存储(当前秒)时避免可变状态

haskell - 将 IO (Maybe (IO (Maybe a))) 减少到 IO (Maybe a)

haskell - 了解 >>= 中的 "Monad m"

haskell - haskell中公平并发 `map`函数?