TExcelTAD
Home › Haskell › Haskell Strings & Char

Haskell Strings & Char

A Char is a single Unicode character, written in single quotes: 'a', '7', 'λ'. A String is simply a list of characters: type String = [Char]. So "hi" is the same value as ['h', 'i'], and every list function from the Lists lesson works on strings too.

haskell · try it yourself
main :: IO ()
main = do
  let word = "functional"
  print (length word)
  print (head word, last word)
  print (reverse word)
  print (take 3 word)
  print (word == ['f','u','n','c','t','i','o','n','a','l'])
  putStrLn (word ++ " programming")
10
('f','l')
"lanoitcnuf"
"fun"
True
functional programming

Escape sequences

Escape Meaning
\n newline
\t tab
\\ backslash
\" double quote inside a string
\' single quote inside a Char
\955 or \x3bb a character by its code point (here λ)
haskell · try it yourself
main :: IO ()
main = do
  putStrLn "Name:\tAda\nRole:\t\"engineer\""
  putStrLn "C:\\Users\\ada"
  print "tab\there"
  print '\''
Name:	Ada
Role:	"engineer"
C:\Users\ada
"tab\there"
'\''

putStrLn writes the characters themselves, while print (via show) writes a string literal with the escapes visible, which is useful for debugging invisible characters.

Working with characters: Data.Char

The module Data.Char has functions to classify and convert characters. Import it at the top of the file:

haskell · try it yourself
import Data.Char (toUpper, toLower, isDigit, isAlpha, isSpace, isUpper, ord, chr, digitToInt)

main :: IO ()
main = do
  print (map toUpper "shout")
  print (map toLower "QUIET")
  print (filter isDigit "Order 66, room 101")
  print (all isAlpha "Haskell", any isSpace "no-spaces")
  print (length (filter isUpper "Hello World From Haskell"))
  print (ord 'A', chr 97)
  print (sum (map digitToInt "2026"))
"SHOUT"
"quiet"
"66101"
(True,False)
4
(65,'a')
10
Function Type Example
toUpper, toLower Char -> Char toUpper 'q' is 'Q'
isDigit, isAlpha, isAlphaNum Char -> Bool isDigit '7' is True
isSpace, isUpper, isLower, isPunctuation Char -> Bool isSpace '\t' is True
ord, chr Char -> Int, Int -> Char ord 'a' is 97
digitToInt Char -> Int digitToInt 'f' is 15 (hex works too)

Splitting and joining

The Prelude has four functions for the most common text jobs:

haskell · try it yourself
main :: IO ()
main = do
  let sentence = "  the quick   brown fox  "
  print (words sentence)            -- split on any whitespace
  print (unwords ["one", "two"])    -- join with single spaces
  let text = "line one\nline two\nline three"
  print (lines text)                -- split on newlines
  putStr (unlines ["a", "b"])       -- join, adding a newline after each
["the","quick","brown","fox"]
"one two"
["line one","line two","line three"]
a
b

Data.List adds more: isPrefixOf, isSuffixOf, isInfixOf, intercalate (join with any separator) and sortOn:

haskell · try it yourself
import Data.List (intercalate, isPrefixOf, isSuffixOf, isInfixOf)
import Data.Char (toUpper)

capitalize :: String -> String
capitalize "" = ""
capitalize (c : rest) = toUpper c : rest

main :: IO ()
main = do
  let fileName = "report-2026.csv"
  print ("report" `isPrefixOf` fileName, ".csv" `isSuffixOf` fileName)
  print ("2026" `isInfixOf` fileName)
  putStrLn (intercalate ", " ["red", "green", "blue"])
  putStrLn (unwords (map capitalize (words "learn you some haskell")))
(True,True)
True
red, green, blue
Learn You Some Haskell

capitalize uses a pattern (c : rest) to split a string into its first character and the rest. Pattern matching gets its own lesson soon.

Converting to and from strings

show turns a value into a String; read parses a String into a value of the type you ask for:

haskell · try it yourself
main :: IO ()
main = do
  let price = 4.5 :: Double
      qty = read "3" :: Int
  putStrLn ("Total: " ++ show (price * fromIntegral qty))
  print (read "[1,2,3]" :: [Int])
  print (show 42 ++ "!")
  print (concatMap show [1, 2, 3])
Total: 13.5
[1,2,3]
"42!"
"123"

Warning: read crashes the program if the text is not valid (read "abc" :: Int). For input you don't control, use readMaybe from Text.Read, which returns Nothing instead. It appears in the Maybe lesson.

String performance

Because String is a linked list of characters, it uses a lot of memory and is slow for large texts. It is perfect for learning and for small strings. Real applications use Data.Text (from the text package bundled with GHC) for text and Data.ByteString for binary data. There is a whole lesson on Text later.

Test yourself

What is String in Haskell?

  1. A built-in array type
  2. [Char], a list of characters
  3. A Text value
  4. An Int array of code points

What does words " a b c " return?

  1. ["", "a", "b", "c"]
  2. ["a","b","c"]
  3. [" a b c "]
  4. "abc"

Which function joins a list of strings with a custom separator like ", "?

  1. unwords
  2. concat
  3. intercalate
  4. unlines