Lists and their ‘Head’ and ‘Tail’

06/05/2009

List are (as name implies) a list of things (mixed type) defined using [] separating items with ,
For example:

[simone, marco, 2+3, {language, erlang}].

returns:

[simone,marco,5,{language,erlang}]

The “head of the list” is the first item in the list (‘simone’ in our example), when you remove the head from a list the remaining part is called “tail of the list” ([marco,5,{language,erlang}] in our example). So a simple schema for a list is [head|tail].

A list:

Devices = [iphone, mac, arduino].

Another list created using an existing one:

ToBuy = [mouse, keyboard | Devices].

Now let’s try to pull out the head of the list using the matching operator ‘=’!

[FirstThingToBuy | OtherThingsToBuy] = ToBuy.

Now I have:

FirstThingToBuy -> mouse (the ex head of the list)

and:

OtherThingsToBuy -> [keyboard,iphone,mac,arduino] (the tail of the list)

Now we need to buy another item (the second), so:

[SecondThingToBuy | OtherThingsToBuy1] = OtherThingsToBuy.

Now I have:

SecondThingToBuy -> keyboard (the new ex hed of the list)

and:

OtherThingsToBuy1 -> [iphone,mac,arduino] (the new tail of the list)

Note: I had to use OtherThingsToBuy1 instead of OtherThingsToBuy because OtherThingsToBuy had already a value and we know that we can’t change it! (I don’t still like it …)

Leave a comment