Haskell 2

Cover page image

Cay S. Horstmann

Type Inference

Parse Tree

Build Parse Tree

Get Equation Set

Simplify Equations

Function Types

Equations

You try it!

Hint: r = p tells you that you can use p instead of r.

Remember the goal (u). Keep plugging in until you can't simplify any more.

What do you get? Pay attention to parentheses.

Lists

Equations

Lab

  1. Add this function to lab.hs and load it.
    f1 x = x + 2

    What type do you get? (Simplify Num a to int throughout in your answers.)

  2. Add
    apply f x = f x

    What type do you get?

  3. What do you expect to get as the result of
    apply f1 3

    Try it out to verify your expectation

  4. Draw the parse tree for apply f x = f(x)
  5. Read off the equations. What equations do you get?
  6. Solve the equations. What is the type of apply?
  7. Compare with Haskell. How do the answers differ?
  8. Here we have used curried functions, just to be cool. Haskell has a pair type (a, b) (where a and b are any types). Try defining
    apply2(f,x) = f(x)

    What type does Haskell report?

  9. Draw the parse tree. Here, the (f,x) needs to be described as an application of a curried function makepair f x. (makepair is similar to cons). makepair has type a -> b -> (a, b) (where a, b are type variables). That is, the left hand of the parse tree side is Apply(apply2, Apply(Apply(makepair, f), x)).
  10. Read off the equations of the parse tree. (There will be 5 equations.) What are they?
  11. Solve the equations. What is the type of apply2?
  12. On to something more practical. Try this definition in Haskell:
    rev [] = []
    rev (x:xs) = rev xs

    What type do you get?

    There is an error in the function. It doesn't actually reverse a list. How can you tell that the function is wrong just by looking at the inferred type?