Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 57 ยท Types and values

Strings, Chars and Text

Understand Haskell String as a list of Char, use Data.Char, show and read, words and lines, and learn when to reach for Data.Text instead.

Text in Haskell starts from one simple idea: a String is a list of Char. Everything you learned about lists applies to text, which is both pleasant (every list function works) and a little dangerous (a linked list of characters is not an efficient way to store a large document).

In this lesson you will use Char and Data.Char, convert values to and from text with show and read, split text with words and lines, and get a first look at Data.Text, the type most real programs use for serious text work.

Haskell is not installed on this site, so the Haskell code here is read-only. The editors use JavaScript stand-ins to imitate the list-of-characters view of text.

Char and String

A Char is one Unicode code point, written in single quotes. A String is written in double quotes and is exactly [Char].

HASKELL
letter :: Char
letter = 'h'

greeting :: String
greeting = "hello"

same :: Bool
same = greeting == ['h', 'e', 'l', 'l', 'o']   -- True

Since a string is a list, the usual functions work directly:

HASKELL
length "haskell"          -- 7
reverse "stressed"        -- "desserts"
take 3 "haskell"          -- "has"
'x' : "yz"                -- "xyz"
"ab" ++ "cd"              -- "abcd"
map succ "HAL"            -- "IBM"
filter (/= 'a') "banana"  -- "bnn"

Escape sequences work as in other languages: "\n" is a newline, "\t" a tab, "\"" a double quote and "\\" a backslash. A multi-line literal uses a backslash gap, or you can join lines with unlines.

Data.Char

The module Data.Char has functions for single characters. Import it at the top of the file.

HASKELL
import Data.Char (toUpper, toLower, isDigit, isAlpha, isSpace, ord, chr, digitToInt)

toUpper 'a'        -- 'A'
isDigit '7'        -- True
isAlpha '!'        -- False
isSpace '\t'       -- True
ord 'A'            -- 65
chr 97             -- 'a'
digitToInt '7'     -- 7

Combine them with map and filter to transform whole strings:

HASKELL
shout :: String -> String
shout = map toUpper

onlyDigits :: String -> String
onlyDigits = filter isDigit

shout "hello"                 -- "HELLO"
onlyDigits "tel: 555-0199"    -- "5550199"

The first definition has no argument written out: shout is map toUpper, a partially applied function. That style is explained in Currying and Partial Application.

show and read

show turns a value into a String. read goes the other way and needs to know the target type.

HASKELL
show 42            -- "42"
show 3.5           -- "3.5"
show True          -- "True"
show [1, 2, 3]     -- "[1,2,3]"
show "hi"          -- "\"hi\""
show 'x'           -- "'x'"

read "42" :: Int            -- 42
read "[1,2,3]" :: [Int]     -- [1,2,3]

Two details trip up newcomers:

  1. show on a string adds quotes and escapes. putStrLn (show "hi") prints "hi" with the quotes. To print text without quotes use putStrLn "hi" directly. Non-ASCII characters are escaped as numbers too: show "cafรฉ" gives "caf\233", while putStrLn "cafรฉ" prints the accent correctly.
  2. read is partial. read "oops" :: Int crashes with Prelude.read: no parse. Use readMaybe from Text.Read for user input:
HASKELL
import Text.Read (readMaybe)

readMaybe "42"   :: Maybe Int   -- Just 42
readMaybe "4x2"  :: Maybe Int   -- Nothing
readMaybe "3.5"  :: Maybe Double -- Just 3.5

The type annotation matters: without it, the compiler cannot tell which Read instance to use. This is a type class feature, covered in Type Classes. The Maybe result is explored in Maybe and Either.

Text conversions

show Value to String. Strings gain quotes.
read String to value. Crashes on bad input.
readMaybe Safe version. Gives Nothing on failure.

Prefer readMaybe for anything a user typed.

1 / 2

words, lines and friends

Four Prelude functions cover a lot of everyday text work.

HASKELL
words "  the quick   brown fox "    -- ["the","quick","brown","fox"]
unwords ["a", "b", "c"]            -- "a b c"
lines "one\ntwo\nthree\n"          -- ["one","two","three"]
unlines ["one", "two"]             -- "one\ntwo\n"

words treats any run of whitespace as a single separator and drops empty pieces. lines splits on '\n', and a final newline does not produce an extra empty line. unlines adds a newline after every line, including the last. Because of that, unlines (lines s) is not always equal to s: a missing final newline gets added.

Here is a word-frequency helper built from those pieces, plus Data.Char for normalising case:

HASKELL
import Data.Char (toLower, isAlpha)
import Data.List (sort, group)

wordCounts :: String -> [(String, Int)]
wordCounts text =
  map (\ws -> (head ws, length ws))
    . group
    . sort
    . words
    . map toLower
    . filter (\c -> isAlpha c || c == ' ')
    $ text

The pipeline reads from the bottom up: filter out punctuation, lower-case it, split into words, sort, group equal words, then count each group. The . and $ operators are the topic of Lambdas, Composition and the $ Operator.

A stand-in you can run

JavaScript strings are not lists of characters, but spreading one gives an array of code points, which is a close cousin. The editor below imitates words, lines, unwords and unlines and the quirks described above. It is a stand-in: real words is lazy and works on [Char].

JS words, lines and their inverses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last two lines show the quirk from above: the round trip adds a newline, so it is not the identity for text without a trailing newline.

The next stand-in imitates readMaybe with null for Nothing, and a word counter in the same pipeline shape as the Haskell version.

JS readMaybe and word counts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The Haskell readMaybe "3.5" :: Maybe Int also gives Nothing, because 3.5 is not a valid Int literal, which matches the stand-in.

Data.Text: the right tool for real text

A String costs several machine words per character and is slow to index or concatenate in bulk. The text package provides Data.Text: a compact, packed, Unicode-aware type with fast operations. Most libraries that deal with text (JSON, web frameworks, databases) use Text, not String.

HASKELL
# LANGUAGE OverloadedStrings #

import qualified Data.Text as T
import qualified Data.Text.IO as TIO

main :: IO ()
main = do
  let t = "  Hello, Haskell  " :: T.Text
  TIO.putStrLn (T.strip t)                 -- Hello, Haskell
  TIO.putStrLn (T.toUpper (T.strip t))     -- HELLO, HASKELL
  print (T.splitOn "," "a,b,c")            -- ["a","b","c"]
  print (T.length t)                       -- 18
  putStrLn (T.unpack (T.replace "l" "L" t)) --   HeLLo, HaskeLL

Key points:

  • import qualified Data.Text as T is the standard way to import it, because many names (length, map, words) clash with the Prelude. Modules are covered in Modules and Imports.
  • The OverloadedStrings extension lets the literal "..." mean either String or Text, depending on what is expected. See GHC Extensions.
  • T.pack :: String -> Text and T.unpack :: Text -> String convert between the two. Use them at the edges, not in a loop.
  • Text is not a list, so head, : and pattern matching with (c:cs) do not work directly. Use T.uncons or functions from Data.Text.

A good rule: use String while learning and for small tools, switch to Text for anything that handles large input, speaks to libraries, or does heavy processing. Binary data is a third type, ByteString, covered in Essential Libraries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type String an alias for?

    String is a type synonym for a list of Char, so all list functions work on it.
  2. 2. What does putStrLn (show "hi") print?

    show produces a string that looks like Haskell source, so quotes are added. Use putStrLn "hi" to print without them.
  3. 3. What is the safe way to turn user input into an Int?

    read crashes with no parse on bad input. readMaybe returns Nothing instead.
  4. 4. What does words " a b " return?

    words splits on runs of whitespace and discards empty pieces.
  5. 5. Why do most Haskell libraries use Text instead of String?

    Text stores characters compactly and has efficient operations. String is a linked list, which is fine for small data but heavy for large documents. It supports Unicode and is not removed.

Summary

  • String is [Char], so every list function works on text.
  • Data.Char provides toUpper, isDigit, ord, chr and more for single characters.
  • show adds quotes and escapes to strings; read crashes on bad input, so use readMaybe from Text.Read.
  • words, unwords, lines and unlines split and join text; unlines always adds a final newline.
  • Data.Text is the efficient, packed alternative, imported qualified and often used with OverloadedStrings.

Next, start writing your own functions with several cases: Pattern Matching.