
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Character to String in Haskell
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.