Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Haskell, when using the XStrict language extension, is if short-circuiting?

Tags:

haskell

Standard Haskell is lazily evaluated, so if myCondition then someValue else doSomeLargeComputation x y z will avoid evaluating doSomeLargeComputation x y z if myCondition is true. My question is, if I enable the language extension XStrict then will doSomeLargeComputation x y z now be evaluated even when myCondition is true?

If so, is there a control flow construct other than explicitly marking doSomeLargeComputation x y z as lazy that can be used to avoid calculating it (like a short-circuiting if statement in a strict language)?

like image 946
LogicChains Avatar asked Aug 03 '19 16:08

LogicChains


1 Answers

No, the branch not taken is not evaluated.

For example:

{-# 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)

Prints:

*Main> main
else
1

However, if we lift the branches to let bindings then yes, those are strictly evaluated:

f :: Int -> Int
f i =
    let f1 = trace "then" 1 in
    let f2 = trace "else" 2 in
    if i < 5
        then f1
        else f2

Yields:

% ./LogicChains
then
else
2
like image 199
Thomas M. DuBuisson Avatar answered Nov 14 '22 01:11

Thomas M. DuBuisson