Haskell:理解 do 符号与 if-else 语句
Haskell: Understanding do notation with if-else statements
我有以下 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中取出布尔值。如果条件 if detected
评估为真,则机器人向右转,否则机器人向前移动。在程序 1 中,机器人向右或向前移动后再次调用功能机器人。程序2右转或前进后直接调用函数robot
我不确定在 if-else
语句之后调用机器人(在程序 1 中)与在程序 2 中的 then
和 else
情况下调用它有什么区别。我说这两个程序是等价的是对的吗?任何见解表示赞赏。
你说这两个程序是等价的是正确的。更一般地说,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)
你得到单子的等价物。
我有以下 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中取出布尔值。如果条件 if detected
评估为真,则机器人向右转,否则机器人向前移动。在程序 1 中,机器人向右或向前移动后再次调用功能机器人。程序2右转或前进后直接调用函数robot
我不确定在 if-else
语句之后调用机器人(在程序 1 中)与在程序 2 中的 then
和 else
情况下调用它有什么区别。我说这两个程序是等价的是对的吗?任何见解表示赞赏。
你说这两个程序是等价的是正确的。更一般地说,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)
你得到单子的等价物。