简体   繁体   中英

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?

@ 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 (ie :: 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, ie 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).

@ is to concatenates two lists .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM