🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell String Building

String building is the joining of many small pieces into one string. The pieces are kept in a list and joined once, instead of rebuilding the front again and again.

Two strings join with (++)

This program joins two words with a space between them. The built string and its length are printed.

main :: IO ()
main = do
  let built = "hello" ++ " " ++ "world"
  print built
  print (length built)

concat joins a list of pieces

This program joins three pieces with no separator. The built string and its length are printed.

main :: IO ()
main = do
  let built = concat ["one", "two", "three"]
  print built
  print (length built)

intercalate adds a separator between pieces

This program joins three names with a comma and a space between each pair. The built string and its length are printed.

import Data.List (intercalate)
main :: IO ()
main = do
  let built = intercalate ", " ["ana", "bo", "lee"]
  print built
  print (length built)

Example

import Data.List (intercalate)
main :: IO ()
main = do
  let built = intercalate " " ["Haskell", "builds", "strings", "well"]
  print built
  print (length built)

Key points

  • Concatenation: the joining of two strings with (++).
  • Use concat to join a list of strings into one string.
  • Use intercalate to join a list of strings with a separator between each pair.
  • Use length on the built string to check the result.
  • Repeated (++) on the left rebuilds the whole front each time, so it is the shape to avoid for many pieces.

In this example, the program keeps four words in a list. It joins them once with a space between each pair, then prints the sentence and its length of 27.

Note

A string is a list of characters, so length counts characters, including spaces and separators.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which function joins a list of strings with a separator between each pair?