# Haskell Program to initialize and print a complex number

This tutorial will help us in initializing and printing a complex number. In Haskell, the Data.Complex library provides a Complex type to represent complex numbers.

## Method 1: Using Complex data type

This method defines a Complex data type that holds the real and imaginary parts of a complex number, and an instance of the Show type class for Complex, which allows it to be printed using the putStrLn function.

In the main function, it creates a complex number object with real part and imaginary part. Then it prints the complex number using the putStrLn function and the show function.

### Algorithm

• Step 1 − Complex data type is defined, that will hold the real and imaginary parts of the complex number.

• Step 2 − Show instance is defined to represent the complex number.

• Step 3 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do.

• Step 4 − A variable named, “c” is being initialized. It will have the real and imaginary number value that is to be represented as a complex number.

• Step 5 − Final resultant complex number value is displayed by using ‘putStrLn’ statement.

### Example

Program to initialize and print a complex number by using Complex data type.

data Complex = Complex { real :: Double, imag :: Double }
instance Show Complex where
show (Complex r i) = (show r) ++ " + " ++ (show i) ++ "i"
main :: IO ()
main = do
let c = Complex { real = 3.0, imag = 4.0 }


### Output

The complex number is: 3.0 + 4.0i

### Example 2

In this example, a tuple is used to represent a complex number, with the first element being the real part and the second element being the imaginary part. The putStrLn function is used to print the complex number, which is automatically converted to a string using the show function.

type Complex = (Double, Double)
main :: IO ()
main = do
let c = (3.0, 4.0)
putStrLn \$ "The complex number is: " ++ (show c)


### Output

The complex number is: (3.0,4.0)


## Conclusion

In Haskell, the number can be initialized and printed as a complex number by various methods including Complex data type, Custom data type with constructor and type class or by using tuple, etc.

In every approach, the real and imaginary parts are passed that needs to be represented in the form of complex number.

Updated on: 19-Jan-2023

130 Views