Learn/Haskell/8. Strings and a small project
Lesson 8 of 8
Sign in

Haskell, lesson 8

Strings and a small project

In Haskell, String is simply another name for [Char], a list of characters. That means everything you learned about lists in the last lesson works on text too.

Strings are lists

Pattern matching works as well. (c : rest) matches a string whose first character is c:

Characters: Data.Char

The Data.Char module (part of base) has the character tools. Import what you need:

Since toUpper works on one Char, you map it over the whole string. This "lift a character function to the whole string" pattern comes up all the time.

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Class report

Press Ctrl Enter or Check to test your code.

Words and lines

words splits on whitespace and unwords joins with single spaces. lines and unlines do the same with line breaks:

To capitalise each word, combine them:

The . operator is function composition: f . g means "do g, then f". So titleCase splits into words, capitalises each, and joins them back, read from right to left. Notice it has no parameter: it's defined as a pipeline of functions.

Formatting

printf from Text.Printf can also return a String instead of printing it, which is handy for building lines:

Putting it together

The last exercise is a small project using everything from this course. A good plan for a Haskell program:

  1. Parse the input into a list of values (here: (String, Int) pairs).
  2. Write pure functions for each rule, such as turning a score into a grade.
  3. Compute summaries with list functions (sum, length, a fold).
  4. Keep main short: read, call the functions, print.

To find the best entry, a fold that only replaces the current best when it finds something strictly bigger keeps the first one on a tie:

Computing an average needs a conversion, since sum and length give whole numbers: fromIntegral total / fromIntegral count.

Further reading

  • Data.Char
  • Prelude: words, unwords, lines
  • Text.Printf
  • A Gentle Introduction to Haskell: Strings and lists

Read one line of text and print four lines:

For the palindrome test, ignore case and ignore every character that is not a letter. So Never odd or even counts as a palindrome.

Sample input:

Sample output:

Time for a small project. The first input line is the number of students (at least 1). Each following line has a student's name and a whole-number score from 0 to 100, separated by a space.

Grades: 90 or more is A, 80 or more is B, 70 or more is C, 60 or more is D, anything lower is F.

Print one line per student in input order, <name>: <score> (<grade>). Then print the average score with one decimal place, and the name of the top student. If several students share the top score, print the one who appears first.

Sample input:

Sample output:

The starter parses the students for you.

length "Haskell"           -- 7
reverse "Haskell"          -- "lleksaH"
take 4 "Haskell"           -- "Hask"
drop 4 "Haskell"           -- "ell"
"Has" ++ "kell"            -- "Haskell"
'k' `elem` "Haskell"       -- True
filter (/= 'l') "Haskell"  -- "Haske"
initial :: String -> String
initial "" = "?"
initial (c : _) = [c] ++ "."
import Data.Char (toUpper, toLower, isAlpha, isDigit, isSpace)

map toUpper "shout"        -- "SHOUT"
filter isDigit "R2-D2"     -- "22"
isAlpha 'x'                -- True
words "  red green  blue "     -- ["red","green","blue"]
unwords ["a", "b", "c"]        -- "a b c"
capitalize :: String -> String
capitalize "" = ""
capitalize (c : rest) = toUpper c : map toLower rest

titleCase :: String -> String
titleCase = unwords . map capitalize . words
import Text.Printf (printf)

label :: String -> Int -> String
label name score = printf "%-8s|%5d|" name score   -- "Ada     |   95|"
best :: [(String, Int)] -> (String, Int)
best (first : rest) = foldl pick first rest
  where
    pick current x = if snd x > snd current then x else current
best [] = ("nobody", 0)
Upper: <the line in uppercase>
Reversed: <the line reversed>
Length: <number of characters in the line>
Palindrome: <yes or no>
Never odd or even
Upper: NEVER ODD OR EVEN
Reversed: neve ro ddo reveN
Length: 17
Palindrome: yes
3
Ada 95
Ben 72
Cleo 88
Ada: 95 (A)
Ben: 72 (C)
Cleo: 88 (B)
Average: 85.0
Top: Ada