在Haskell中,当使用XStrict语言扩展时,是否短路?

Log*_*ins 9 haskell

Standard Haskell是惰性评估的,因此if myCondition then someValue else doSomeLargeComputation x y z将避免评估doSomeLargeComputation x y z是否myCondition为真。我的问题是,如果启用语言扩展,XStrict那么doSomeLargeComputation x y z即使myCondition为true,现在也将对其进行评估?

如果是这样,除了明确标记doSomeLargeComputation x y z为惰性以外,是否还有控制流构造可用于避免对其进行计算(例如,严格语言中的if语句短路)?

Tho*_*son 10

不,不评估未采用的分支。

例如:

{-# LANGUAGE Strict #-}
import Debug.Trace

main :: IO ()
main = print (f (fib 3))

f i =
    if i < 5
        then trace "then" 0
        else trace "else" 1

-- Using fib to avoid inlining or optimization from messing up or test.
fib :: Int -> Int
fib 1 = 1
fib n  = n + fib (n-1)
Run Code Online (Sandbox Code Playgroud)

印刷品:

*Main> main
else
1
Run Code Online (Sandbox Code Playgroud)

但是,如果我们解除分支以让绑定生效,那么是的,将严格评估它们:

f :: Int -> Int
f i =
    let f1 = trace "then" 1 in
    let f2 = trace "else" 2 in
    if i < 5
        then f1
        else f2
Run Code Online (Sandbox Code Playgroud)

产量:

% ./LogicChains
then
else
2
Run Code Online (Sandbox Code Playgroud)