String Functions in Haskell

In Haskell, string manipulation is typically done using the Data.Text module, which provides efficient string handling. We’ll use this module along with some functions from the standard Prelude for our examples.

import qualified Data.Text as T
import Data.List (intercalate)

main :: IO ()
main = do
    -- We'll use putStrLn to print each result on a new line
    let p = putStrLn

    -- Here's a sample of string functions available in Haskell
    p $ "Contains:   " ++ show (T.isInfixOf (T.pack "es") (T.pack "test"))
    p $ "Count:      " ++ show (T.count (T.pack "t") (T.pack "test"))
    p $ "HasPrefix:  " ++ show (T.isPrefixOf (T.pack "te") (T.pack "test"))
    p $ "HasSuffix:  " ++ show (T.isSuffixOf (T.pack "st") (T.pack "test"))
    p $ "Index:      " ++ show (T.findIndex (== 'e') (T.pack "test"))
    p $ "Join:       " ++ T.unpack (T.intercalate (T.pack "-") [T.pack "a", T.pack "b"])
    p $ "Repeat:     " ++ T.unpack (T.replicate 5 (T.pack "a"))
    p $ "Replace:    " ++ T.unpack (T.replace (T.pack "o") (T.pack "0") (T.pack "foo"))
    p $ "Split:      " ++ show (T.splitOn (T.pack "-") (T.pack "a-b-c-d-e"))
    p $ "ToLower:    " ++ T.unpack (T.toLower (T.pack "TEST"))
    p $ "ToUpper:    " ++ T.unpack (T.toUpper (T.pack "test"))

This code demonstrates various string operations using the Data.Text module in Haskell. Here’s a breakdown of the functions used:

  • isInfixOf: Checks if one string is a substring of another.
  • count: Counts occurrences of a substring.
  • isPrefixOf and isSuffixOf: Check for prefix and suffix.
  • findIndex: Finds the index of a character.
  • intercalate: Joins strings with a separator.
  • replicate: Repeats a string multiple times.
  • replace: Replaces all occurrences of a substring.
  • splitOn: Splits a string on a delimiter.
  • toLower and toUpper: Convert to lowercase and uppercase.

Note that in Haskell, we need to use pack to convert string literals to Text, and unpack to convert Text back to String for printing.

To run this program, save it as string_functions.hs and use:

$ runhaskell string_functions.hs
Contains:   True
Count:      2
HasPrefix:  True
HasSuffix:  True
Index:      Just 1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Split:      ["a","b","c","d","e"]
ToLower:    test
ToUpper:    TEST

This example demonstrates how to perform common string operations in Haskell using the Data.Text module, which provides efficient string handling capabilities.