HPM Education - Haskell

Searchβ¦

Introduction

Types in Haskell

Defining Functions / Working with Functions

List Comprehensions

Higher-order Functions

Cutom Types

Interactive Programming

Functors, Applicatives and Monads

Local Definitions

We already saw how we can use where to define local helper expressions, but there is another way. The let-in construct also allows us to define local expressions with the syntax

`let <declarations> in <expression>`

:1

sumSquares2 x y =

2

let

3

a = x ^ 2

4

b = y ^ 2

5

in

6

a + b

7

8

ghci> sumSquares 2 5

9

29

10

ghci> sumSquares2 2 5

11

29

Copied!

We can also use

`let-in`

and `where`

in combination β for example, let's write a function that checks whether the sum of squares of two numbers is a multiple of five:1

sumSquaresM5 x y =

2

let

3

sum = a + b

4

in

5

mod sum 5 == 0 -- (mod) is the modulo operator

6

where

7

a = x ^ 2

8

b = y ^ 2

Copied!

We know a number is a multiple of five if the remainder of its division by five is zero. A thing to note here is the difference between

`let-in`

and`where`

. What we define in the `where`

declarations is accessible to any code above it, however, the declarations from the `let`

block are only accessible in the `in`

block of the `let-in`

clause. For example, we could try to calculate the remainder from the division by five in the where clause using the `sum`

from the `let`

clause, but it will not work:1

sumSquaresM5 x y =

2

let

3

sum = a + b

4

in

5

res == 0

6

where

7

a = x ^ 2

8

b = y ^ 2

9

res = mod sum 2 -- the sum expression is not accessible here

Copied!

The compilation of the above would result in an error as **super-localised expressions** that aren't accessible anywhere outside the

`sum`

is only accessible in the `in`

clause of the code. This means that with `let-in`

we can create `in`

code block.Copy link