Why does Haskell have a built-in if/then/else
, which is dependent on the Bool
type, instead of having a simple library function? Such as
if :: Bool -> a -> a -> a
if True x _ = x
if False _ y = y
2
It’s purely for the nice sugar of the if
, then
, and else
keywords; in fact, GHC (with the RebindableSyntax
extension enabled) will desugar the syntax by simply calling whatever ifThenElse
function is in scope.
It doesn’t matter much … to me it looks like if/then/else is not used very often nowadays. I find myself writing pattern guards instad of if .. then .. else.
From a syntactic point of view, though, it is nice to have
if expr1 then expr2 else expr3
So you can write
if foo a then bar b else baz c
instead of
if (foo a) (bar b) (baz c)
which looks a bit too LISPish to me.
For semantic analysis and code generation, it is nice to have this construct, which can easily be compiled to efficient machine code. Note that the code can skip the part that makes the thunk for the branch that is not reached, as opposed to a function call, where the (unevaluated) parameters must all be passed. But it also costs time (and memory, that must be reclaimed later) to create the thunk. To make good on this, one would have to inline the if function everywhere.
2