Haskell Program to calculate the value from the given fraction and exponent


This haskell tutorial will help us in calculating the value from the given fraction and exponent of a number. To find this, the input is taken as fraction and exponent, and its corresponding value is computed.

Algorithm

  • Step 1 − The “Data.Ratio” is imported to work over fractions.

  • Step 2 − The calculateValue function is defined

  • 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 − The variables named, “fraction” and “exponent” are initialized. It will hold the fraction and exponent whose value is to be computed.

  • Step 5 − The result is printed to the console using ‘putStrLn’ statement under case.

Example 1

In this example, we are going to see that how we can calculate the value from the given fraction and exponent using fromRational function.

import Data.Ratio

calculateValue :: Rational -> Integer -> Double
calculateValue fraction exponent = (fromRational fraction)^exponent

main :: IO ()
main = do
   let fraction = 3 % 4
   let exponent = 2

   let value = calculateValue fraction exponent
   putStrLn ("The value is: " ++ show value)

Output

The value is: 0.5625

Example 2

In this example, we are going to see that how we can calculate the value from the given fraction and exponent using Maybe monad.

import Data.Ratio

calculateValue :: Rational -> Integer -> Maybe Double
calculateValue fraction exponent = (^ exponent) <$> (Just $ fromRational fraction)

main :: IO ()
main = do
  let fraction = 3 % 4
  let exponent = 2

  let result = calculateValue fraction exponent
  
  case result of
    Just value -> putStrLn ("The value is: " ++ show value)
    Nothing -> putStrLn "An error occured"

Output

The value is: 0.5625

Example 3

In this example, we are going to see that how we can calculate the value from the given fraction and exponent using Either monad.

import Data.Ratio

calculateValue :: Rational -> Integer -> Double
calculateValue fraction exponent = (fromRational fraction)^exponent

main :: IO ()
main = do
   let fraction = 3 % 4
   let exponent = 2

   let result = Right (calculateValue fraction exponent)
  
   case result of
      Right value -> putStrLn ("The value is: " ++ show value)
      Left error -> putStrLn error

Output

The value is: 0.5625

Conclusion

The value from the given fraction and exponent in Haskell, can be calculated by using the fromRational function, by using Maybe or Either monad.

Updated on: 01-Mar-2023

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements