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)?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With