# Confusion about the : operator for lists

Page 1 of 1

## 3 Replies - 200 Views - Last Post: 12 August 2013 - 03:02 PM

### #1 salazar

Reputation: 86
• Posts: 532
• Joined: 26-June 13

# Confusion about the : operator for lists

Posted 11 August 2013 - 03:19 PM

Okay, i'm confused about the : operator for lists. I see it used as this

```f x : xs = Nothing

```

I later found out that it is used to prepend to a list.

As in,

```1 : [2, 3, 4]

```

Isn't this nearly the opposite.
Can someone explain this to me?

This post has been edited by salazar: 11 August 2013 - 03:20 PM

Is This A Good Question/Topic? 0

## Replies To: Confusion about the : operator for lists

### #2 Raynes

• D.I.C Lover

Reputation: 603
• Posts: 2,812
• Joined: 05-January 09

## Re: Confusion about the : operator for lists

Posted 11 August 2013 - 03:21 PM

It is used to append to a list as demonstrated in your second example. That's all it does. The first example isn't even valid code and doesn't make any sense, so I'm not entirely certain what you're confused about.

EDIT:

I think I see what you're confused about. You should read up on pattern matching.

If you have a function f like so:

```f (x:xs) = x

```

this function takes a list and pattern matches it so that 'x' is bound to the head of the list and 'xs' to the tail (everything but the head) of the list. It's kind of like reverse appending.

This post has been edited by Raynes: 11 August 2013 - 03:25 PM

### #3 sepp2k

• D.I.C Lover

Reputation: 1964
• Posts: 2,927
• Joined: 21-June 11

## Re: Confusion about the : operator for lists

Posted 11 August 2013 - 03:36 PM

foo : bar is a list whose first element is the value foo and whose remaining elements are the list bar. When used as an expression this means that it will create a list containing those values (meaning foo and bar have to be expressions of the appropriate types). When used as a pattern (as in f (foo : bar) -- without the parentheses it'd be a syntax error), this means that the pattern will match non-empty lists, the pattern foo will be applied to the first element of the list and the pattern bar to the list containing the remaining elements (so if foo and bar are merely identifiers, this means that the will be bound to the head and tail of the list respectively).

You might say these are opposites, but I'd rather think of them as complements. In a sense expressions construct and patterns destruct (i.e. take apart) and a pattern that takes apart values of a specific shape will look exactly like an expression that is used to construct values of that shape. So a pattern that takes apart non-empty lists looks exactly like an expressions that constructs non-empty lists.

### #4 salazar

Reputation: 86
• Posts: 532
• Joined: 26-June 13

## Re: Confusion about the : operator for lists

Posted 12 August 2013 - 03:02 PM

Okay thank you seep2k that made perfect sense.