Gasim
Gasim

Reputation: 7961

OCaml difference between :: and @

I am trying to append one list to an end of another list. The usual :: operator gives me the following error:

This expression has type char list but an expression was expected of type char

in the statement

`(createList 0 5 'a')::['c';'d';'e';'f';'g']`
(* the following createList expression returns the list ['a';'a';'a';'a';'a'] *)

When I use @ operator, it appends the list fine; so, my question is what is the difference between @ and ::? is it just @ is used between two lists while :: used between list and non-list types?

Upvotes: 1

Views: 3012

Answers (2)

Jackson Tale
Jackson Tale

Reputation: 25812

@ is to concatenates two lists.

:: is to add an element to the head of a list

Upvotes: 1

phimuemue
phimuemue

Reputation: 35973

@ concatenates two lists (type 'a list -> 'a list -> 'a list), while :: takes an element of a certain type and "prepends" it before a list containing elements of exactly the same type (i.e. :: has type 'a -> 'a list -> 'a list).

You can basically simulate a::b by [a]@b.

Note that @ requires OCaml to traverse the first list given to find the last argument of the first list. This takes O(n) time where n is the number of elements in the first list. ::, on the other hand, requires O(1) time.

Regarding your example (createList 0 5 'a')::['c';'d';'e';'f';'g']:

(createList 0 5 'a') creates a list holding 'a's, i.e. we have type char list, and ['c';'d';'e';'f';'g'] is also of type char list. Thus, you can only use @ to concatenate them (see above), and :: makes no sense (see type signature of :: above).

Upvotes: 2

Related Questions