Skip to content
UoL CS Notes

Lecture 4-2

COMP105 Lectures

Let

Sometimes we want to use the same expression more than once:

(x * x - 4) + sqrt (x * x - 4)

The problem of writing out the same equation over again can be solved using the following example:

let s = (x * x - 4) in s + sqrt s

Syntax

let <bindings> in <expression>

Where:

  • <binding> gives names to bindings separated by ;
    • let a = 1; b = a + 1 in a + b
  • <expression> uses those bindings

Let vs Variables

A let expression doesn’t create variables:

  • They are names for particular expressions.
  • You cannot change a binding once it has been made.
  • They are made for convenience only.

Let in GHCI

In GHCI you can write:

> let a = 1

or

> a = 1

To define a let for the rest of the session.

Let across multiple lines

Usually it is clearer to write let across multiple lines:

f x y = let a = x * x
			b = y * y
		in
			a * a + b * b

When splitting across line breaks you don’t need to use ; to separate the bindings.

Scope

When using let the bindings are only defined within the let function.

Examples

cylinder r h =
	let sideArea = 2 * pi * r * h
		topArea = pi * e ** 2
	in sideArea + 2 * topArea

Exercises

  1.  exercise1 x = let a = x * x + 1 in a * a * a
    
  2.  exercise2 x = let a = x + 1; bb = a + 2; ccc = a + bb in ccc *  ccc
    

Haskell’s Layout Rule

Each definition at the same level should start on exactly the same column:

f x y z = let
			a = x * x
			b = y * y 
			cc = z * z
		in
			a * b + b * b

Ignoring the Layout Rule

You can ignore the layout rule by using curly braces to separate the bindings.

let {a = x * x;
	b = y * y;
	c = z * z}
in
	a + b