View Problem

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
DiskEdit
ruby
['Red', 'Green', 'Blue'][-1]
DiskEdit
ruby
['Red', 'Green', 'Blue'].at(-1)
DiskEdit
ruby
['Red', 'Green', 'Blue'].last
DiskEdit
ruby
['Red', 'Green', 'Blue'].fetch(-1)
ExpandDiskEdit
java
String result = list.get(list.size() - 1);
DiskEdit
perl
qw(Red Green Blue)[-1];
DiskEdit
perl
@list = qw(Red Green Blue);
$list[-1];
ExpandDiskEdit
groovy 1.0+
list = ['Red', 'Green', 'Blue']
result = list[-1]
ExpandDiskEdit
scala
val result = list.last
ExpandDiskEdit
scala
val result = (list.drop(list.length - 1)).head
DiskEdit
python
list = ['Red', 'Green', 'Blue']
list[-1]
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ result = list[list->Count - 1];
ExpandDiskEdit
fsharp
let last list =
let rec last' list' =
match list' with
| [x] -> x
| x :: xs -> last' xs
if List.is_empty list then failwith "empty list" else last' list

// ------

let result = last list
ExpandDiskEdit
fsharp
let result = (List.nth list ((List.length list) - 1))
ExpandDiskEdit
fsharp
let result = (List.hd (List.rev list))
ExpandDiskEdit
erlang
Result = lists:last(List),
ExpandDiskEdit
erlang
Result = last(List),
ExpandDiskEdit
erlang
Result = hd(lists:reverse(List)),
ExpandDiskEdit
erlang
Result = lists:nth(length(List), List),
DiskEdit
ocaml
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.nth list ( (List.length list) - 1 );;
DiskEdit
ocaml
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.hd (List.rev list);;
DiskEdit
csharp .NET 2.0
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
DiskEdit
csharp .NET 3.5 & C# 3.0
// Make sure you import the System.Linq namespace.
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"
ExpandDiskEdit
php
$list = array("Red", "Green", "Blue");
$last = array_pop($list);

// Be aware of that $list only contains two elements now - not three
ExpandDiskEdit
php
$list = array("Red", "Green", "Blue");
$last = $list[count($list)-1];

Submit a new solution for ruby, java, perl, groovy ...