[英]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
的行detected <- blocked
將布爾值從IO中取出。 如果if detected
的條件評估為真,則機器人向右轉,否則機器人向前移動。 在程序1中,在向右或向前移動機器人之后再次調用功能機器人。 在程序2中,在向右轉或向前移動后直接調用功能機器人。
我不確定在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 (fx) else (fy)
的事實的結果; 如果你采用f = (>> action)
你就得到monad的等價。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.