A crash course in Haskell

We’re going to do this real fast; for 131:

Haskell = Ocaml + Better syntax

We assume you are familiar with Ocaml

So: we’ll learn Haskell by comparison.

Type Ascription

Ocaml uses : for type ascription

  • e : t means e has type t

vs.

Haskell uses :: for type ascription

  • e :: t means e has type t

Function Definitions and Calls

Ocaml

vs

Haskell

let not needed for top-level binding.

Pattern Matching

Ocaml

vs

Haskell

or better,

Haskell allows different equations for different cases.

Colon vs. Double-Colon

Ocaml

  • uses :: for “cons”
  • uses : for “has type”

vs

Haskell

  • uses : for “cons”
  • uses :: for “has type”

A handy table

Operator Ocaml Haskell
:: “cons” “has type”
: “has type” “cons”

Local Variables

Ocaml

vs

Haskell

QUIZ: Local Variables

What is the value of quiz?

A. Syntax error B. Type Error C. 0 D. 1 E. Other

QUIZ: Local Variables

What is the value of quiz?

A. Syntax error B. Type Error C. 0 D. 1 E. Other

QUIZ: Local Variables

What is the value of quiz?

A. Syntax error B. Type Error C. 0 D. 1 E. Other

QUIZ: Local Variables

What is the value of quiz?

A. Syntax error B. Type Error C. 0 D. 1 E. Other

Local Variables (revisited)

So we can take

and write it better as

where lets you pull local variables aside:

  • meaning exactly same as let, but
  • can specify them in any order.

(Seems strange at first, but truly beautiful.)

Anonymous Functions

Ocaml

vs

Haskell

Very similar: Ocaml’s fun is replaced with Haskell’s \

Tuples and Lists

Ocaml

(12, “cat”)

vs

Haskell

Note

  • Haskell uses (t1, t2) vs Ocaml’s (t1 * t2)
  • Haskell uses [t] vs Ocaml’s t list

Larger Example

Ocaml

vs

Haskell

QUIZ: List Comprehensions

What is the value of

A. Syntax Error B. Type Error C. [0, 5] D. [0, 1, 2, 3, 4] E. [0, 1, 2, 3, 4, 5]

QUIZ: List Comprehensions

What is the value of

A. Syntax Error B. Type Error C. [0, 50] D. [0, 10, 20, 30, 40] E. [0, 10, 20, 30, 40, 50]

QUIZ: List Comprehensions

What is the value of

A. [] B. [0] C. [0, 10] D. [0, 10, 20] E. [0, 10, 20, 30]

QUIZ: List Comprehensions

We can simplify the sort using list comprehensions, as in Python:

Defining Data

Ocaml

vs

Haskell

Constructing Data

Ocaml

vs

Haskell

Note

The tags Plus, Number etc. are (constructor) functions

QUIZ: Constructor Types

Given

What is the type of Number ?

A. Expr B. Double C. Double -> Expr D. Expr -> Double E. Expr -> Expr

Destructing (Accessing) Data

Ocaml

vs

Haskell

Oh look, we wrote a compiler!

  • What’s the source language?
  • What’s the target language?

Recursive Functions

Ocaml

vs.

Haskell

Printf Debugging

Very Very Important

Q: How to print out each input-output pair for calls to fact?

Ocaml

(as in Java, C, Python…), just print it:

vs

Haskell

You can’t just print stuff (for very good reasons…)

However, you can do this:

Which pretty much does what you want.