Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Cons()?

Tags:

rust

The Rust tutorial example of a linked list is:

enum List {     Cons(u32, Box<List>),     Nil } 

What exactly is the Cons() struct? (It is a struct right?) I can't find any documentation on this anywhere.

like image 409
J V Avatar asked Apr 26 '14 13:04

J V


People also ask

What does cons mean in a list?

A pros and cons list is a quick and easy decision-making tool. Pros are arguments FOR taking a particular path. Cons are arguments AGAINST.

What is cons and nil?

Conses are a data type, and nil is the sole object of type null. The Lisp data type list is taken to mean the union of the cons and null data types, and therefore encompasses both true lists and dotted lists.

Is a cons list a linked list?

The cons list is perhaps the most basic immutable data structure: a singly linked list built out of 'cons cells,' which are cells containing two values, the left hand value being the head of the list and the right hand value being a reference to the rest of the list, or a Nil value denoting the end of the list.


1 Answers

Cons does not have a special meaning in Rust. It is only the name that the author of the tutorial chose to call that variant of the enum. The same List could have been defined as:

enum List {     Pair(u32, Box<List>),     Nil } 

The name cons comes from the Lisp family of programming languages where pairs (nodes of linked lists) are used as the fundamental building blocks of data structures. Here is one way to create the 1,2,3 list in Common Lisp:

(cons 1 (cons 2 (cons 3 nil))) 

cons is a shorthand of construct by which Lisp programmers mean to allocate memory. Programs that allocate lots of memory are said to be consing too much.

Sources

  • cons - wikipedia
  • Marijn Haverbeke's presentation on JS performance
like image 151
nawfel bgh Avatar answered Sep 29 '22 05:09

nawfel bgh