Haskell:了解if-else语句的表示法

cen*_*980 2 monads haskell functional-programming equivalence do-notation

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

data Direction = Left | Right
forward    :: IO ()
blocked :: IO Bool
turn       :: Direction -> IO ()
Run Code Online (Sandbox Code Playgroud)

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

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

-- 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
Run Code Online (Sandbox Code Playgroud)

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

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

bra*_*drn 7

您正确地说这两个程序是等效的。更一般地,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)您将获得单子的等效性。

  • 请注意,为方便起见,您提到的法律仅适用于_strict_`f`。例如`cond = undefined`和`f = \ _-&gt;()`违反法律。就是说,在IO monad中,`f =(&gt;&gt; action)`是严格的,因此一切正常。 (2认同)