Singly-linked list/Element definition: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: mention pitfalls of Pair, and show custom type example)
Line 941: Line 941:
$node{next} = \%bar_node; # mutable</lang>
$node{next} = \%bar_node; # mutable</lang>
=={{header|Perl 6}}==
=={{header|Perl 6}}==

The <tt>Pair</tt> constructor is exactly equivalent to a cons cell.
====With <tt>Pair</tt>====

A <tt>Pair</tt> (constructed with the <code>=></code> operator) can be treated as a cons cell, and thus used to build a linked lists:

<lang perl6>my $elem = 42 => $nextelem;</lang>
<lang perl6>my $elem = 42 => $nextelem;</lang>

However, because this is not the primary purpose of the <tt>Pair</tt> type, it suffers from the following limitations:

* The naming of <tt>Pair</tt>'s accessor methods is not idiomatic for this use case (<code>.key</code> for the cell's value, and <code>.value</code> for the link to the next cell).
* A <tt>Pair</tt> (unlike an <tt>Array</tt>) does not automatically wrap its keys/values in item containers &ndash; so each cell of the list will be immutable once created, making element insertion/deletion impossible (except inserting at the front).
* It provides no built-in convenience methods for iterating/modifying/transforming such a list.

====With custom type====

For more flexibility, one would create a custom type:

<lang perl6>class Cell {
has $.value is rw;
has Cell $.next is rw;
# ...convenience methods here...
}

sub cons ($value, $next) { Cell.new(:$value, :$next) }

my $list = cons 10, (cons 20, (cons 30, Nil));</lang>


=={{header|Phix}}==
=={{header|Phix}}==