Chapter 2: Hello, Haskell!

This note captures my solutions to exercises in Chapter 2: Hello, Haskell! of the book Haskell programming from first principles

Exercises: Comprehension check

comprehensionCheck.hs

Exercises: Parentheses and association

  1. 8 + 7 * 9 is not the same as (8 + 7) * 9. arentheses changes the results.
  2. perimeter x y = (x * 2) + (y * 2) is the same as perimeter x y = x * 2 + y * 2. Parentheses does not change the results.
  3. f x = x / 2 + 9 is not the same as f x = x / (2 + 9). Parentheses change the results.

Exercises: A head code

  1. let x = 5 in x returns 5.
  2. let x = 5 in x * x returns 25.
  3. let x = 5; y = 6 in x * y returns 30.
  4. let x = 3; y = 1000 in x + 3 returns 6.

Chapter Exercises

Parenthesization

  1. 2 + 2 * 3 - 1 == 2 + (2 * 3) - 1.
  2. (^) 10 $ 1 + 1 == (^) 10 (1 + 1).
  3. 2 ^ 2 * 4 ^ 5 + 1 == ((2 ^ 2) * (4 ^ 5)) + 1.

Equivalent expressions

  1. 1 + 1 == 2
  2. 10 ^ 2 == 10 + 9 * 10
  3. 400 - 37 /= (-) 37 400
  4. 100 `div` 3 is not the same as 100 / 3. div is integral division. / is fractional division.
  5. 2 * 5 + 18 /= 2 * (5 + 18)

More fun with functions

1

let z = 7
let y = z + 8
let x = y ^ 2
let waxOn = x * 5

10 + waxOn
-- gives 1135
(+10) waxOn
-- gives 1135
(-) 15 waxOn
-- gives -1110
(-) waxOn 15
--gives 1110

2

let z = 7
let y = z + 8
let x = y ^ 2
let waxOn = x * 5
let triple x = x * 3

3

triple waxOn
-- gives 3375

4, 5, 6 & 7

module WaxOn where

  waxOn :: Integer
  waxOn = x * 5 
    where x = y ^ 2
          y = z + 8
          z = 7

  triple :: Num a => a -> a
  triple x = x * 3

  waxOff :: Num a => a -> a
  waxOff x = triple x

waxOn.hs

  1. waxOff waxOn gives 3375.
  2. waxOff 10 gives 30.
  3. waxOff (-50) gives -150.