Syntactic Sugar II: let and where

Learn how to split complex expressions into reusable subexpressions.

Let’s continue discovering some of the syntactic sugar that Haskell offers us. In this lesson, we focus on bindings for subexpressions.

Sometimes when writing functions, the expressions on the right hand side of equations can become quite complex, especially when they involve repeated subexpressions. For example, consider the task to write a function which solves the quadratic equation

x2+px+q=0x^2 + px + q = 0

We know that this equation has solutions as long as

(p2)2q0\left(\frac{p}{2}\right)^2 - q \geq 0

and these solutions are equal to

p2±(p2)2q-\frac{p}{2} \pm \sqrt{\left(\frac{p}{2}\right)^2 - q}

Let’s translate this into a Haskell function, ignoring for now the case where there are no solutions.

Get hands-on with 1200+ tech skills courses.