Haskell Program to Convert Character to String


In Haskell, we can convert Character to String by using user-defined function, show function, list comprehension and (:[]) notation. In the first example, we are going to use (charToString c = [c]) function and in the second example, we are going to use (charToString c = show c) function. Where as in third, we are going to use (charToString c = [x | x <- [c]]) and in fouth example, we are going to use (charToString c = c : []).

Algorithm

  • Step 1 − The function named charToString is defined

  • Step 2 − The 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, ‘myChar’ is initialized with a character value that is to be converted to respective string.

  • Step 4 − The resultant string value corresponding to the character value is printed to the console.

Example 1

In this example, Character is converted to String using charToString function.

charToString :: Char -> String
charToString c = [c]

main :: IO ()
main = do
  let myChar = 'a'
  let myString = charToString myChar
  putStrLn myString

Output

[1 of 1] Compiling Main             ( main.hs, main.o )
Linking main ...
a

Example 2

In this example, Character is converted to String using charToString function along with show function.

charToString :: Char -> String
charToString c = show c

main :: IO ()
main = do
  let myChar = 'a'
  let myString = charToString myChar
  putStrLn myString

Output

[1 of 1] Compiling Main             ( main.hs, main.o )
Linking main ...
'a'

Example 3

In this example, Character is converted to String using charToString function defined using list comprehension.

charToString :: Char -> String
charToString c = [x | x <- [c]]

main :: IO ()
main = do
  let myChar = 'a'
  let myString = charToString myChar
  putStrLn myString

Output

[1 of 1] Compiling Main             ( main.hs, main.o )
Linking main ...
a

Example 4

In this example, Character is converted to String using charToString function defined using (:[]) notation.

charToString :: Char -> String
charToString c = c : []

main :: IO ()
main = do
  let myChar = 'a'
  let myString = charToString myChar
  putStrLn myString

Output

[1 of 1] Compiling Main             ( main.hs, main.o )
Linking main ...
a

Conclusion

In Haskell, a character to string conversion is the process of converting a single Char value into a String that contains that character. In Haskell, a String is simply a list of Char values. Therefore, to convert a Char to a String, we can create a list that contains only that character. We can also use show function and (:[]) notation for this conversion.

Updated on: 28-Mar-2023

912 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements