Chapter 3: Strings

This note captures my solutions to exercises in Chapter 3: Strings of the book Haskell programming from first principles

Exercises: Scope

Question 1

Prelude> let x = 5
Prelude> let y = 7
Prelude> let z = x * y

y is in scope for z.

Question 2

Prelude> let f = 3
Prelude> let g  = 6 * f + h

h is not in scope for function g.

Question 3

area d = pi * (r * r)
r = d / 2

Everything we need to execute area is not in scope. r is not in scope in the area function. d is not in scope in the r function.

Question 4

area d = pi * (r * r)
  where r = d / 2

r and d are now in scope for area.

Exercises: Syntax errors

  1. ++ [1, 2, 3] [4, 5, 6] should be (++) [1, 2, 3] [4, 5, 6]
  2. '<3' ++ ' Haskell' should be "<3" ++ " Haskell"
  3. concat ["<3", " Haskell"] compiles.

Concatenation and scoping

Print3Broken.hs

Chapter Exercises

Reading Syntax

  1. concat [[1, 2, 3], [4, 5, 6]] is written correctly. The result is [1,2,3,4,5,6]
  2. ++ [1,2,3] [4,5,6]is not written correctly. The ++ should be (++). The result of (++) [1,2,3] [4,5,6] is [1,2,3,4,5,6].
  3. (++) "hello" " world" is written correctly. The result is "hello world".
  4. ["hello" ++ " world] is not written correctly. " world should be " world". The result of ["hello" ++ " world"] is ["hello world"].
  5. 4 !! "hello" is not written correctly. 4 !! "hello" should be "hello" !! 4. The result of "hello" !! 4 is o.
  6. (!!) "hello" 4 is written correctly. The result of (!!) "hello" 4 is o.
  7. take "4 lovely" is not written correctly. take "4 lovely" should be take 4 "lovely". The result of take 4 "lovely" is "love".
  8. take 3 "awesome" is written correctly. The result of take 3 "awesome" is "awe".

Result Matching

  1. concat [[1 * 6],[2 * 6], [3 * 6]] gives [6, 12, 18] (option d).
  2. "rain" ++ drop 2 "elbow" gives "rainbow" (option c).
  3. 10 * head [1,2,3] gives 10 (option e).
  4. (take 3 "Julie") ++ (tail "yes") gives "Jules" (option a).
  5. concat [tail [1, 2, 3], tail [4, 5, 6], tail [7, 8, 9]] gives [2,3,5,6,8,9] (option b).

Building functions

1

-- #1
-- a)
"Curry is awesome" ++ "!"

-- b)
take 1 $ drop 4 $ "Curry is awesome" ++ "!"

-- c)
drop 9 $ "Curry is awesome" ++ "!"

2

extract.hs

3

thirdLetter.hs

4

letterIndex.hs

5 & 6

reverse.hs