Anonymous user
Singly-linked list/Element definition: Difference between revisions
Singly-linked list/Element definition (view source)
Revision as of 21:00, 14 November 2018
, 5 years ago→{{header|Perl 6}}: mention pitfalls of Pair, and show custom type example
(→{{header|Perl 6}}: mention pitfalls of Pair, and show custom type example) |
|||
Line 941:
$node{next} = \%bar_node; # mutable</lang>
=={{header|Perl 6}}==
====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>
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 – 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}}==
|