# Haskell Program to get the numerator from a rational number

In Haskell, we can use numerator, div, quot and gcd functions to find the numerator from a given rational number. In the first example we are going to use numerator (r) function and in the second example, we are going to use (n div gcd n d) function. And in third example, we are going to use (numerator r quot gcd (numerator r) (denominator r)) function.

### Algorithm

• Step 1 − The Data.Ratio module is imported to use numerator function.

• Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. It calls the numerator function with the rational number and prints the numerator.

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

• Step 4 − The resultant numerator value is printed to the console using ‘putStrLn’ statement after the function is called.

### Example 1

In this example, we are going to see that how we can get the numerator from the rational number. This can be done by using numerator function.

import Data.Ratio

main :: IO ()
main = do
let r = 3 % 4
let num = numerator r


### Output

The numerator of 3 % 4 is: 3


### Example 3

In this example, we are going to see that how we can get the numerator from the rational number. This can be done by using quot and gcd function.

import Data.Ratio

getNumerator :: Rational -> Integer
getNumerator r = numerator r quot gcd (numerator r) (denominator r)

main :: IO ()
main = do
let r = 3 % 4
let num = getNumerator r
putStrLn \$ "The numerator of " ++ show r ++ " is: " ++ show num


### Output

The numerator of 3 % 4 is: 3


## Conclusion

The numerator of a rational number is the top part of the fraction. In other words, it is the number that is being divided by the denominator.

In Haskell, to get the numerator of the given rational numbers, we can use the gcd functions along with div or quot functions. It can also be obtained using numerator function.

Updated on: 13-Mar-2023

58 Views