Haskell program to find all roots of a quadratic equation

In this tutorial, we discuss writing a program to find the largest among the three numbers Haskell programming language. A quadratic equation is a second-degree algebraic equation.

Example − a quadratic equation is of the form ax^2 + bx + c, where a,b, and c are constants and x is variable. A quadratic equation has two roots.

Algorithm steps

  • Take a quadratic equation as input.

  • Implement the programming logic to compute the roots.

  • Display the roots.

Algorithm Logic

  • Take input or initialize values for a,b, and c. As the quadratic expression can be constructed with these values (ax^2 + bx + c).

  • Compute Discriminant D which is equal to b^2 - 4*a*c.

  • If Discriminant D is greater than or equal to zero then the roots are

    root1 = (-b + sqrt(D))/2*a

    root2 = (-b - sqrt(D))/2*a

    We will print the roots.

  • If Discriminant D is less than zero then the roots are imaginary and we print the root are imaginary

Note− If the Discriminant D is zero the roots are -b/2*a and -b/2*a.


Program to find all roots of a quadratic equation

-- function declaration for function printRoots printRoots :: Float->Float->Float->IO() -- function definition for function printRoots printRoots a b c = do print("a,b,c values =",a,b,c) let d = b^2 - 4*a*c -- let d = 1 if (d < 0) then do print ("This quadratic equation has imaginary roots") else do let root1 = (-(b) + sqrt (d))/2 * (a) let root2 = (-(b) - sqrt (d))/2 * (a) print ("The roots for this quadratic are:") print (root1) print (root2) main :: IO() main = do -- declaring and initializing constants in quadratic equation let a = 1 let b = 4 let c = 2 -- invoking the printRoots function printRoots (a) (b) (c)


("a,b,c values =",1.0,4.0,2.0)
"The roots for this quadratic are:"

In the above program, we declared a function printRoots as such it takes three floats as argument and returns an IO action. In its function definition, we are taking three arguments a, b, and c. We are computing the discriminant by the formula b^2 - 4*a*c and loading the discriminant into a variable d. We are checking if the discriminant is less than zero, we are printing the statement “roots are imaginary” as we know that if the discriminant is less than zero for a quadratic equation the roots are imaginary. If the discriminant is greater than zero, we are computing the roots using the formula (-b +/- sqrt(d))/2*a. We are loading the roots into variables root1 and root2. And finally, we printed the roots in the function. In the main function, we declared and initialized variables a, b and c. Finally, we invoked the function printRoots with the three numbers as the arguments.


In this tutorial, we discussed implementing a program to find the roots of a quadratic equation in Haskell programming Language.

Updated on: 24-Nov-2022


Kickstart Your Career

Get certified by completing the course

Get Started