Char, String and Bool
Char and its escapes
A character is written in single quotes: 'a',
'Z', '0'. The quotes are
part of the literal, and a character is not a one-letter string: the two have
different types.
Some characters have no visible form, so they are written with a backslash:
'\n' for a newline, '\t'
for a tab, '\\' for a backslash, and
'\'' for a single quote, because the plain one
would end the literal. Inside a string the same escapes work, plus
\" for a double quote.
A character is a Unicode code point, so a letter from any alphabet fits in
one. Two functions move between the character and its number:
ord gives the code point and
chr builds the character back:
module Main (main) where
import Data.Char (chr, ord)
main :: IO ()
main = print (ord 'A', chr 66)
(65,'B')
Both come from Data.Char, not from Prelude, so the file needs the import. The result is a pair, and print shows it with the quotes and the parentheses that would rebuild the value.
String
A string is written in double quotes, and it is a list of characters:
"abc" is ['a', 'b', 'c']
written the short way. The
lesson on
signatures showed the definition the compiler gives for the synonym.
Concatenation is ++, which walks the whole left list,
and length counts characters:
module Main (main) where
main :: IO ()
main = print ("ab" ++ "cd", length "abcd")
("abcd",4)
show of a string adds the quotes back, which is why
the first component prints as "abcd" and not as
abcd: print shows the value,
and the quotes are how a reader tells a string from a variable name.
Since a string is a list, every list function applies:
map toUpper "haskell" is a string of capitals,
reverse "abc" is "cba", and a
pattern (x : rest) splits the first character from
the rest. A character is a list of one element, but a list of one character is
not a literal: 'a' and
"a" are different types and cannot be mixed in a
list.
Bool and the operators
Bool has two values, True and
False, both written with a capital letter because
they are constructors of a type, not variables.
The operators are the ones you expect, with one difference: comparison
returns a Bool and is an ordinary function, so it can
be passed to filter or stored in a list.
- && is and, || is or, not negates.
- == and /= are equality and inequality; <, <=, >, >= compare.
- && and || are short-circuit: the right side is not evaluated when the left side decides the answer.
module Main (main) where
main :: IO ()
main = print ((1 :: Int) < 2, "ab" == "ab", not False)
(True,True,True)
The annotation (1 :: Int) is needed for the same
reason as before: without it the compiler would have to choose a numeric type
for the comparison, and -Wall would say so.
Equality works on any type whose values can be compared for sameness, which
includes numbers, characters, strings, lists and tuples of those. Functions
cannot be compared, and asking for f == g is a type
error rather than a false answer: the compiler has no way to decide it.
Data.Char
The module is a small toolkit for one character at a time, and most of it needs nothing but the import:
- toUpper, toLower: change the case of one character.
- isDigit, isAlpha, isSpace, isUpper, isLower: ask what kind of character it is.
- ord, chr: move between the character and its code point.
- digitToInt, intToDigit: move between a digit character and its value.
module Main (main) where
import Data.Char (toUpper)
main :: IO ()
main = putStrLn (map toUpper "haskell")
HASKELL
map toUpper applies the function to every character
of the string, which is the same as applying it to every element of a list.
The result is a string, because a list of characters is a string.
The predicates are the right way to validate input.
isDigit '7' is True and
isUpper 'x' is False;
isDigit 'x' would also be
False, which is what a parser wants to hear before it
calls digitToInt.
The three types in one program
module Main (main) where
import Data.Char (chr, isDigit, isUpper, ord, toUpper)
yes :: Bool
yes = True
no :: Bool
no = False
main :: IO ()
main = do
print ('a', "abc", yes && not no)
print (ord 'A', chr 66)
putStrLn (map toUpper "haskell")
print (isDigit '7', isUpper 'x')
print ("ab" ++ "cd", length "abcd")
print ((1 :: Int) < 2, "ab" == "ab", not no)
print (no || yes, yes && no)
print "a\tb"
ghc -Wall -O1 -o text Text.hs
./text
[1 of 2] Compiling Main ( Text.hs, Text.o )
[2 of 2] Linking text
('a',"abc",True)
(65,'B')
HASKELL
(True,False)
("abcd",4)
(True,True,True)
(True,False)
"a\tb"
The last line is the escape at work. The string holds a real tab, and
print uses show, which writes
a tab back as \t so that the output could be read
into a program again. putStrLn of the same string
would print the tab itself, and the cursor would jump.
The program builds with no warning under -Wall, and
hlint reports No hints.
Exercises
- Print ord 'a', ord 'A' and ord '0'. What is the distance between a lowercase letter and its uppercase form, and does it hold for every letter of the alphabet?
- Write isVowel :: Char -> Bool with a list of five characters and elem. Test it on 'a' and on 'b'.
- Build a string from a character with ('x' : "yz") and with ("x" ++ "yz"). Are the results the same type? Are the expressions the same?
- Count the vowels in "haskell course" with length and filter. Which function do you need next to filter to keep only the vowels?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which literal is a Char?
Answer
'a'
A Char is one character in single quotes; double quotes make a String and an unquoted name is a variable.
-
What does
"abc" ++ "de"give?Answer
"abcde"
++ concatenates two lists, and a String is a list of characters, so the result is the five-character string.
-
What does
not (True && False)give?Answer
True
True && False is False, and not turns it into True.
-
What does
map toUpper "abc"give?Answer
"ABC"
map applies toUpper to each character, and the resulting list of characters is a String, printed as "ABC".
-
Which module provides ord, chr and isDigit?
Answer
Data.Char
Those functions live in Data.Char, which is why the program imports them explicitly.
-
What does this program print?
module Main (main) where import Data.Char (chr, ord) main :: IO () main = print (ord 'A', chr 66)Answer
(65,'B')
The code point of A is 65, and 66 is the code of B, so the pair prints as (65,'B').
-
What does this program print?
module Main (main) where main :: IO () main = putStrLn ("ab" ++ "cd")Answer
abcd
The two strings are joined and putStrLn prints the result without quotes.
-
What does this program print?
module Main (main) where main :: IO () main = print (length "abcd", 2 + 2 :: Int)Answer
(4,4)
length counts four characters and 2 + 2 is 4, so the pair is (4,4).
-
A list is written
['a', "b"]. What does the compiler say?Answer
The elements have different types, Char and String, so the list has no type
Every element of a list must have the same type, and Char and String ([Char]) are different, so the list is rejected.
-
What is the first line of the compiler output for this program?
module Main (main) where main :: IO () main = putStrLn 'a'Answer
error: [GHC-83865]
putStrLn takes a String and a Char is not one, so the expected [Char] and the actual Char do not match, which GHC reports as GHC-83865.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev