Haskell Program to Convert Boolean to String


In Haskell, we can convert Boolean to String by using user-defined function along with guards and if-else statements. In the first example, we are going to use (boolToString True = "True" and boolToString False = "False") function and in the second example, we are going to use (boolToString b | b = "True" | otherwise = "False") as function definition. And in the third example, we are going to use (boolToString b = if b then "True" else "False").

Algorithm

  • Step 1 − Define the Boolean 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.

  • Step 3 − The variable named, “b” is being initialized. It will hold the boolean value that is to be converted to respective string.

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

Example 1

In this example, the function is defined using user-defined boolToString function to convert the boolean value to a string.

boolToString :: Bool -> String
boolToString True = "True"
boolToString False = "False"

main :: IO ()
main = do
   let b = True
   putStrLn ("The string value is: " ++ boolToString b)

Output

The string value is: True

Example 2

In this example, the function is defined using user-defined boolToString function using guards to convert the boolean value to a string.

boolToString :: Bool -> String
boolToString b
   | b = "True"
   | otherwise = "False"

main :: IO ()
main = do
   let b = True
   putStrLn ("The string value is: " ++ boolToString b)

Output

The string value is: True

Example 3

In this example, the function is defined using user-defined boolToString function using if-else to convert the boolean value to a string.

boolToString :: Bool -> String
boolToString b = if b then "True" else "False"

main :: IO ()
main = do
   let b = True
   putStrLn ("The string value is: " ++ boolToString b)

Output

The string value is: True

Example 4

In this example, the function is defined using user-defined boolToString function using if-else with a lambda function to convert the boolean value to a string.

boolToString :: Bool -> String
boolToString = \b -> if b then "True" else "False"

main :: IO ()
main = do
   let b = True
   putStrLn ("The string value is: " ++ boolToString b)

Output

The string value is: True

Conclusion

In Haskell, a boolean is converted to string using user-defined function along with guards and if-else statement.

Updated on: 13-Mar-2023

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements