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
  • 4
    I would guess they explicitly wanted the if/then/else syntax which they can't get without mixfix functions like they have in agda. The function you refer to is structured as a ternary, which you could implement yourself though I presume they gave us if/then/else sugar (it's likely just sugar over a case) just because they could and it's harmless.. But I have nothing to back me up here, which is why I'm writing this in a comment. Commented Apr 22, 2013 at 14:12
  • 10
    This might be obvious to most of the readers, but I would like to point out that having îf/then/else as a function would not be a good solution in an eager language (e.g. scheme or sml) while it is reasonable in a lazy language like Haskell.
    – Giorgio
    Commented Apr 24, 2013 at 17:00

2 Answers 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.

  • 3
    I don't think the inlining is an actual issue. My understanding is that GHC is already exceptionally good at inlining small functions, because it's just such a common pattern in Haskell. Commented Apr 24, 2013 at 22:50
  • 1
    @TikhonJelvis Sure, but with if/then/else you don't need a special function that must always get inlined. You don't even need an inlining pass and still you can generate decent code. Not all the world is GHC.
    – Ingo
    Commented Apr 25, 2013 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.