TExcelTAD
Home › Haskell › Haskell Text

Haskell Text

String is a linked list of characters: simple, and great for learning, but each character costs dozens of bytes of memory and most operations are slow. Real Haskell applications use Data.Text from the text package (bundled with GHC): a packed, immutable Unicode string with an efficient implementation and a rich API.

Getting started

Turn on the OverloadedStrings extension so that string literals can be Text directly, and import the module qualified, since many of its names clash with the Prelude:

haskell · try it yourself
{-# LANGUAGE OverloadedStrings #-}

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

greeting :: Text
greeting = "  Hello, Text!  "

main :: IO ()
main = do
  TIO.putStrLn greeting
  TIO.putStrLn (T.strip greeting)
  print (T.length greeting)
  TIO.putStrLn (T.toUpper (T.strip greeting))
  print (T.words "split   these words")
  print (T.pack "from String", T.unpack "to String")
  Hello, Text!  
Hello, Text!
16
HELLO, TEXT!
["split","these","words"]
("from String","to String")
Function Purpose
T.pack / T.unpack convert String → Text / Text → String
TIO.putStrLn, TIO.readFile, TIO.writeFile I/O with Text (from Data.Text.IO)
T.length, T.null size and emptiness
T.strip, T.stripStart, T.stripEnd remove surrounding whitespace
T.toUpper, T.toLower, T.toTitle change case (Unicode-aware)
<> concatenate (Text is a Monoid); T.concat, T.intercalate for lists

Splitting, searching and replacing

Data.Text has many functions that String code has to assemble by hand:

haskell · try it yourself
{-# LANGUAGE OverloadedStrings #-}

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

main :: IO ()
main = do
  let csvLine = "2026-03-14,Pi Day,3.14,celebration"
  print (T.splitOn "," csvLine)
  print (T.breakOn "," csvLine)
  print (T.isPrefixOf "2026" csvLine, T.isInfixOf "Pi" csvLine)
  TIO.putStrLn (T.replace "-" "/" (T.takeWhile (/= ',') csvLine))
  TIO.putStrLn (T.intercalate " | " ["one", "two", "three"])
  print (T.count "a" "banana", T.reverse "stressed")
  TIO.putStrLn (T.justifyLeft 10 '.' "name" <> T.justifyRight 6 ' ' "42")
["2026-03-14","Pi Day","3.14","celebration"]
("2026-03-14",",Pi Day,3.14,celebration")
(True,True)
2026/03/14
one | two | three
(3,"desserts")
name......    42

T.justifyLeft and T.justifyRight pad a text to a width, which is handy for tables.

Parsing numbers from Text

Data.Text.Read parses numbers and returns an Either with the number and the rest of the input:

haskell · try it yourself
{-# LANGUAGE OverloadedStrings #-}

import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Read as TR

parseInt :: Text -> Either String Int
parseInt t = case TR.signed TR.decimal (T.strip t) of
  Right (n, rest) | T.null rest -> Right n
  Right (_, rest) -> Left ("trailing input: " ++ T.unpack rest)
  Left err -> Left err

main :: IO ()
main = do
  print (parseInt " 42 ")
  print (parseInt "-17")
  print (parseInt "12abc")
  print (parseInt "abc")
  print (TR.double "2.5e3 km")
  print (sum <
gt; traverse parseInt (T.splitOn "," "10,20,30"))
Right 42
Right (-17)
Left "trailing input: abc"
Left "input does not start with a digit"
Right (2500.0," km")
Right 60

A word-frequency report with Text

Text combines nicely with Data.Map for text processing:

haskell · try it yourself
{-# LANGUAGE OverloadedStrings #-}

import Data.Char (isAlpha)
import Data.List (sortOn)
import Data.Ord (Down (..))
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified Data.Text.IO as TIO

report :: T.Text -> [(T.Text, Int)]
report =
  take 3
    . sortOn (\(w, n) -> (Down n, w))
    . Map.toList
    . Map.fromListWith (+)
    . map (\w -> (w, 1))
    . filter (not . T.null)
    . map (T.filter isAlpha . T.toLower)
    . T.words

main :: IO ()
main = do
  let text = "The rain in Spain stays mainly in the plain. In Spain, the rain is plain!"
  mapM_ (\(w, n) -> TIO.putStrLn (T.justifyLeft 8 ' ' w <> T.pack (show n))) (report text)
in      3
the     3
plain   2

Text, String and ByteString

Type What it is Use for
String [Char], a lazy linked list learning, tiny strings, show output
Text (strict) packed UTF-8 Unicode text almost all real text handling
Data.Text.Lazy.Text a lazy list of Text chunks very large or streaming text
ByteString packed raw bytes binary data, network protocols, files

Converting between Text and bytes requires choosing an encoding, which Data.Text.Encoding makes explicit:

haskell · try it yourself
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString as BS
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8, decodeUtf8)

main :: IO ()
main = do
  let word = "naïve café" :: T.Text
      bytes = encodeUtf8 word
  print (T.length word)        -- characters
  print (BS.length bytes)      -- bytes: ï and é take two bytes each in UTF-8
  print (BS.unpack (encodeUtf8 "é"))
  print (decodeUtf8 bytes == word)
10
12
[195,169]
True

Note: The program above only prints numbers and Booleans, on purpose. The playground's output channel is configured for ASCII, and writing a non-ASCII character such as é to it makes GHC stop with "invalid argument (cannot encode character)". On your own machine, with a UTF-8 terminal, TIO.putStrLn word works fine. A program can also choose the encoding itself with hSetEncoding stdout utf8 from System.IO:

haskell · try it yourself
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Text.IO as TIO
import System.IO (hSetEncoding, stdout, utf8)

main :: IO ()
main = do
  hSetEncoding stdout utf8
  TIO.putStrLn "naïve café, λ-calculus"
naïve café, λ-calculus

Test yourself

What does the OverloadedStrings extension do?

  1. Makes strings mutable
  2. Lets string literals have types like Text, not only String
  3. Speeds up String
  4. Enables Unicode

What is T.splitOn "," "a,b,,c"?

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

Why is Data.Text preferred over String in applications?

  1. String cannot hold Unicode
  2. Text is packed and much more memory- and time-efficient
  3. Text is mutable
  4. String is deprecated