Skip to content

Latest commit

 

History

History
173 lines (164 loc) · 2.34 KB

ch04.adoc

File metadata and controls

173 lines (164 loc) · 2.34 KB

4 Basic datatypes

4.2 Anatomy of a data declaration

given data type, answer

data Mood = Blah | Woot deriving Show
  1. type constructor is Mood

  2. values are Blah and Woot

  3. :: Mood → Woot to :: Mood → Mood, as Woot is value, not type

  4. change mood

    link:ch04_4.2_0.hs[role=include]
  5. done :)

4.4 Comparing values

Intermission: Exercises

  1. bug

    not True && true
    -- fix
    not True && True
  2. bug

    not (x = 6)
    -- fix
    not (x == 6)
  3. correct

    (1 * 2) > 5
  4. bug

    [Merry] > [Happy]
    -- fix
    ["Merry"] > ["Happy"]
  5. bug

    [1, 2, 3] ++ "look at me!"
    -- fix
    ['1', '2', '3'] ++ "look at me!"

4.7 Chapter Exercises

awesome = ["Papuchon", "curry", "Haskell"]
alsoAwesome = ["Quake", "The Simons"]
allAwesome = [awesome, alsoAwesome]
  1. length

    1. type signature

      :: [a] -> Int
    2. takes one argument

    3. result is Int

  2. results

    1. length [1, 2, 3, 4, 5] == 5

    2. length [(1, 2), (2, 3), (3, 4)] == 3

    3. length allAwesome == 2

    4. length (concat allAwesome) == 5

  3. second breaks

    -- works
    6 / 3
    -- both values need to be Fractional, length returns Int
    6 / length [1, 2, 3]
  4. fixed previous example

    6 `div` length [1, 2, 3]
  5. 2 + 3 == 5 type is Bool and result is True as 5 == 5

  6. type is Bool, result is False as 8 /= 5

    Prelude> let x = 5
    Prelude> x + 3 == 5
  7. as follows

    Prelude> length allAwesome == 2
    -- works - True
    Prelude> length [1, 'a', 3, 'b']
    -- breaks on types, list cannot be heterogenic
    Prelude> length allAwesome + length awesome
    -- works - 5
    Prelude> (8 == 8) && ('b' < 'a')
    -- works - False
    Prelude> (8 == 8) && 9
    -- breaks - 9 is not a Bool
  8. palidrome function

    link:ch04_4.7_0.hs[role=include]
  9. return absolute value

    link:ch04_4.7_1.hs[role=include]
  10. tuple function

    link:ch04_4.7_2.hs[role=include]

Reading Syntax

  1. length + 1

    link:ch04_4.7_3.hs[role=include]
  2. identity

    \x -> x
  3. head

    \ (x:xs) -> x
  4. fst

    f (a, b) = a

Match the function names to their types

  1. c) Show a ⇒ a → String

  2. b) Eq a ⇒ a → a → Bool

  3. a) (a, b) → a

  4. d) Num a ⇒ a → a → a