View Problem

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
DiskEdit
ruby
items = ["apple", "orange", "grapes", "bananas"]
items << first = items.shift

# items is rotated
# first contains the first value in the list
ExpandDiskEdit
java 1.5 or later
list.add(list.remove(0));
DiskEdit
perl
@list = qw(apple, orange, grapes, bananas);
push @list, shift @list;
DiskEdit
perl
@list = qw(apple orange grapes bananas);
@list = @list[1..$#list,0];
ExpandDiskEdit
groovy 1.5.6
first = items.head()
items = items.tail() + first
ExpandDiskEdit
groovy
items = items[1..-1] + items[0]
ExpandDiskEdit
groovy
items = items + items.remove(0)
ExpandDiskEdit
scala
items = items.tail ::: List(items.head)
ExpandDiskEdit
scala
items = (items.head :: ((items.tail).reverse)).reverse
DiskEdit
python
l = ["apple", "orange", "grapes", "bananas"]
first, l = l[0], l[1:] + l[:1]
DiskEdit
python
fruit = ['apple', 'orange', 'grapes', 'bananas']
fruit.append(fruit.pop(0))
ExpandDiskEdit
cpp C++/CLI .NET 2.0
fruit->Add(fruit[0]); fruit->RemoveAt(0);
ExpandDiskEdit
fsharp
let rotate list n =
if n <= 0 then
list
else
let (left, right) = split_at list (n - 1)
right @ left

// ------

let result = (rotate fruit 1)
ExpandDiskEdit
erlang
N = 1, {Left, Right} = lists:split(N, List), Result = Right ++ Left,
ExpandDiskEdit
erlang
N = 1, Result = rotate(N, List),
DiskEdit
ocaml
let rotate list =
match list with
| head::tail -> tail@[head]
| [] -> []
ExpandDiskEdit
php
$list = array("Apple", "Orange", "Grapes", "Banana");
$first = array_shift($list); //get and remove the first
array_push($list, $first); //prepend the $first to the array

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