我有以下用于操纵机器人的 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/