17.01.2015 Views

Erlang and OTP in Action.pdf - Synrc

Erlang and OTP in Action.pdf - Synrc

Erlang and OTP in Action.pdf - Synrc

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

30<br />

That was the last <strong>in</strong> our list of built-<strong>in</strong> data types. We will now discuss someth<strong>in</strong>g that<br />

unites them all: the comparison operators.<br />

2.2.9 – Compar<strong>in</strong>g terms<br />

The different data types <strong>in</strong> <strong>Erlang</strong> have one th<strong>in</strong>g <strong>in</strong> common: they can all be compared <strong>and</strong><br />

ordered, us<strong>in</strong>g built-<strong>in</strong> operators like , <strong>and</strong> ==. The normal order<strong>in</strong>gs on numbers of<br />

course hold, so that 1 < 2 <strong>and</strong> 3.14 > 3 <strong>and</strong> so on, <strong>and</strong> atoms <strong>and</strong> str<strong>in</strong>gs (as well as any<br />

other lists) <strong>and</strong> tuples are ordered lexicographically, so that 'abacus' < 'abba', "zzz"<br />

> "zzy", [1,2,3] > [1,2,2,1], <strong>and</strong> {fred,baker,42} < {fred,cook,18}.<br />

So far, it all seems pretty normal, but on top of that you also have an order<strong>in</strong>g between<br />

values of different types, so that for example 42 < 'aardvark', [1,2,3] > {1,2,3},<br />

<strong>and</strong> 'abc' < "abc". That is, all numbers come before all atoms, all tuples come before all<br />

lists, <strong>and</strong> all atoms come before all tuples <strong>and</strong> lists (str<strong>in</strong>gs are really lists, remember).<br />

You don’t have to memorize which data types come before which <strong>in</strong> this order. The<br />

important th<strong>in</strong>g to know is that you can compare any two terms for order, <strong>and</strong> you will get<br />

the same result always. In particular, if you sort a list of various terms of different types (a<br />

list of mixed numbers, str<strong>in</strong>gs, atoms, tuples, …) by us<strong>in</strong>g the st<strong>and</strong>ard library function<br />

lists:sort(…), you will always get a properly sorted list as result, where all the numbers<br />

come first, then all atoms, <strong>and</strong> so on. You can try it out <strong>in</strong> the shell: for example,<br />

lists:sort([b,3,a,"z",1,c,"x",2.5,"y"]).<br />

LESS-THAN/GREATER-THAN OR EQUALS<br />

One of those little differences <strong>in</strong> syntax between <strong>Erlang</strong> <strong>and</strong> most other programm<strong>in</strong>g<br />

languages except Prolog is that the less-than-or-equals operator is not written “

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!