🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell String Functions

String functions are ready-made helpers that change or split text. Each one takes a string and gives back a new value.

head gives the first character

head takes the first character of the string. print shows that character with single quotes.

main :: IO ()
main = print (head "Haskell")

tail then reverse flips the rest

tail drops the first character from the string. reverse then flips the remaining characters.

main :: IO ()
main = putStrLn (reverse (tail "Haskell"))

take and drop split a string

take keeps the start of the string. drop skips the start of the same string.

main :: IO ()
main = putStrLn (take 4 "Haskell" ++ " / " ++ drop 4 "Haskell")

Example

main :: IO ()
main = putStrLn (unwords (words "the  cat   sat"))

Key points

  • head: head gives the first character of a string.
  • tail: tail gives a string without its first character.
  • take: take keeps a chosen number of characters from the start of a string.
  • drop: drop removes a chosen number of characters from the start of a string.
  • reverse: reverse gives a string with its characters in reverse order.
  • words: words splits a string into separate words at its spaces.
  • unwords: unwords joins separate words into one string with single spaces.

In this example, words splits the text into separate words, unwords joins those words with single spaces, and putStrLn prints the cleaned-up text.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does putStrLn (tail "Haskell") print?