# Haskell Program to get the Magnitude of the given number

Haskell has internal functions like negate, abs and signum functions that can be used to get magnitude of the given number. In the first example we are going to use (negate n) function and in the second example, we are going to use (abs) function. In third example, we are going to use (signum x) function.

### Algorithm

• Step 1 − Define the magnitude function

• Step 2 − Program execution will be started from main function. The main() function has whole control of the program.

• Step 3 − The variable named, “num” is being initialized. It will hold the number value whose magnitude is to be printed.

• Step 4 − The resultant magnitude (absolute) value is printed to the console using ‘print’ function after the function is called.

### Example 1

In this example, we are going to see that how we can get the magnitude of the given number by using negate function.

magnitude :: (Ord a, Num a) => a -> a
magnitude x
| x < 0     = negate x
| otherwise = x

main :: IO ()
main = do
let num = -5
print (magnitude num)


### Output

5


### Example 2

In this example, we are going to see that how we can get the magnitude of the given number by using abs function.

magnitude :: (Ord a, Num a) => a -> a
magnitude = abs

main :: IO ()
main = do
let num = -5
print (magnitude num)


### Output

5


### Example 3

In this example, we are going to see that how we can get the magnitude of the given number by using abs function and fromIntegral function.

magnitude :: (Integral a) => a -> a
magnitude x = fromIntegral \$ abs x

main :: IO ()
main = do
let num = -5
print (magnitude num)


### Output

5


### Example 4

In this example, we are going to see that how we can get the magnitude of the given number by using signum function.

magnitude :: (Num a) => a -> a
magnitude x = x * (signum x)

main :: IO ()
main = do
let num = -5
print (magnitude num)


### Output

5


## Conclusion

The magnitude of a number is always positive or zero, regardless of the sign of the original number.

Updated on: 13-Mar-2023

98 Views 