Wednesday 20 May 2015

Infix and Prefix

You can turn infix operators such as + into prefix functions by putting then in brackets:

Prelude> 2 + 2
4
Prelude> (+) 2 2
4

Conversely you can take prefix functions and turn them into infix operators by
surrounding them with back ticks, thus:

Prelude> mod 12 5
2
Prelude> 12 `mod` 5
2

There is also a list comprehension syntax that works like this.  Imagine someone has just asked for the sum of all numbers in the range 1 to 999 that are either a multiple of 3 or a multiple of 5.  You can translate that pretty directly into Haskell:

Prelude> sum [x | x <- [1..999], mod x 3 == 0 || mod x 5 == 0]
233168

No comments:

Post a Comment