View Category

Define an empty list

Assign the variable "list" to a list with no elements
ruby
list = []
list = Array.new
java
List list = Collections.emptyList();
String[] list = {};
perl
@list = ();
groovy
list = []
// if a special kind of list is required
list = new LinkedList() // java style
LinkedList list = [] // statically typed
// using 'as' operator
list = [] as java.util.concurrent.CopyOnWriteArrayList

scala
val list = Nil
val list = List()
val list : List[String] = List()
val list = List.empty
python
list = []
cpp
Generic::List<String^>^ list = gcnew Generic::List<String^>();
std::list<std::string> list;
fsharp
let list = []
let list = List.empty
let list = new Generic.List<string>()
let list = new Generic.LinkedList<string>()
erlang
List = [],
ocaml
let list = [];;
csharp
var list = new List<object>();
php
$list = array();
haskell
let list = []
clojure
(list)
'()
fantom
list := [,]
go
var l []string;

Define a static list

Define the list [One, Two, Three, Four, Five]
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list = %w(One Two Three Four Five)
java
List<String> numbers = new ArrayList<String>();
Collections.addAll(numbers, "One", "Two", "Three", "Four", "Five");
List numbers = new ArrayList();
numbers.add("One");
numbers.add("Two");
numbers.add("Three");
numbers.add("Four");
numbers.add("Five");
List numbers = Arrays.asList(new String[]{"One", "Two", "Three", "Four", "Five"});
String[] numbers = {"One", "Two", "Three", "Four", "Five"};
List numbers = new ArrayList(){{put("One"); put("Two"); put("Three"); put("Four"); put("Five"); }};
perl
@list = qw(One Two Three Four Five);
@list = ('One', 'Two', 'Three', 'Four', 'Five');
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
// other variations
List<String> numbers1 = ['One', 'Two', 'Three', 'Four', 'Five']
String[] numbers2 = ['One', 'Two', 'Three', 'Four', 'Five']
numbers3 = new LinkedList(['One', 'Two', 'Three', 'Four', 'Five'])
numbers4 = ['One', 'Two', 'Three', 'Four', 'Five'] as Stack // Groovy 1.6+
scala
val list = "One" :: "Two" :: "Three" :: "Four" :: "Five" :: Nil
val list = List("One", "Two", "Three", "Four", "Five")
val list: List[String] = List("One", "Two", "Three", "Four", "Five")
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
print list
cpp
array<String^>^ input = {"One", "Two", "Three", "Four", "Five"};
Generic::List<String^>^ list = gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) input);
Generic::List<String^>^ list = gcnew Generic::List<String^>();

list->Add("One");
list->Add("Two");
list->Add("Three");
list->Add("Four");
list->Add("Five");
std::string input[] = {"One", "Two", "Three", "Four", "Five"};
std::list<std::string> list(input, input + 5);
std::list<std::string> list;

list.push_back("One");
list.push_back("Two");
list.push_back("Three");
list.push_back("Four");
list.push_back("Five");
list<string> lst = { "One", "Two", "Three", "Four", "Five" };
list<string> lst;
lst += "One", "Two", "Three", "Four", "Five";
fsharp
let list = ["One"; "Two"; "Three"; "Four"; "Five"]
let list = (new Generic.LinkedList<string>([|"One"; "Two"; "Three"; "Four"; "Five"|]))
let list = (new Generic.LinkedList<string>())

list.AddFirst("One") ; list.AddLast("Five") ; list.AddBefore(list.Find("Five"), "Four")
list.AddAfter(list.Find("One"), "Two") ; list.AddAfter(list.Find("Two"), "Three")
let list = (new Generic.List<string>())

[|"One"; "Two"; "Three"; "Four"; "Five"|] |> Array.iter (fun x -> list.Add(x))
erlang
List = [one, two, three, four, five],
List = ['One', 'Two', 'Three', 'Four', 'Five'],
ocaml
let list = [ "One"; "Two"; "Three"; "Four"; "Five" ];;
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};
php
$list = array("One", "Two", "Three", "Four", "Five");
$list = array();
$list[] = "One";
$list[] = "Two";
$list[] = "Three";
$list[] = "Four";
$list[] = "Five";
<?php
$list = new SplFixedArray(5);

$list[0] = "One";
$list[1] = "Two";
$list[2] = "Three";
$list[3] = "Four";
$list[4] = "Five";
?>
haskell
let a = ["One", "Two", "Three", "Four", "Five"]
clojure
(def a '[One Two Three Four Five])
(def a (list "One" "Two" "Three" "Four" "Five"))
fantom
list := ["One", "Two", "Three", "Four", "Five"]
go
var l = []string{"One", "Two", "Three", "Four", "Five"}

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
ruby
string = fruit.join(', ')
java
StringBuffer sb = new StringBuffer();
for (Iterator it = fruit.iterator(); it.hasNext();) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(", ");
}
}
String result = sb.toString();
StringBuilder sb = new StringBuilder(fruit.get(0));
for (String item : fruit.subList(1, fruit.size())) sb.append(", ").append(item);
String result = sb.toString();
String result = StringUtils.join(fruit, ", ");
perl
print join ', ', qw(Apple Banana Carrot);
# Longer and less efficient than join(), but illustrates
# Perl's foreach operator, which can be useful for
# less trivial problems with lists

@list = ('Apple', 'Banana', 'Carrot');
foreach $fruit (@list) {
print "$fruit,";
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $, = ", ";
print @a
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $" = ", ";
print "@a\n";
}
groovy
string = fruit.join(', ')
string = fruit.toString()[1..-2]
scala
val result =
((fruit.tail foldLeft (new StringBuilder(fruit.head))) {(acc, e) => acc.append(", ").append(e)}).toString
val result = fruit.mkString(",")
val fruit = List[String]("Apple", "Banana", "Carrot")
println(fruit.mkString(", "))
python
print ", ".join(['Apple', 'Banana', 'Carrot'])
cpp
String^ result = String::Join(L", ", fruit->ToArray());
string fruits[] = {"Apple", "Banana", "Carrot"};
string result = boost::algorithm::join(fruits, ", ");
fsharp
let result = String.Join(", ", [|"Apple"; "Banana"; "Carrot"|])
let result = (List.fold_left (fun acc item -> acc ^ (", " ^ item)) (List.hd fruit) (List.tl fruit))
let result = (List.fold_left (fun (acc : StringBuilder) (item : string) -> acc.Append(", ").Append(item)) (new StringBuilder(List.hd fruit)) (List.tl fruit)).ToString()
erlang
Result = string:join(Fruit, ", "),
Result = lists:foldl(fun (E, Acc) -> Acc ++ ", " ++ E end, hd(Fruit), tl(Fruit)),
Result = lists:flatten([ hd(Fruit) | [ ", " ++ X || X <- tl(Fruit)]]).
ocaml
let () =
let lst = ["Apple"; "Banana"; "Carrot"] in
let str = String.concat ", " lst in
print_endline str
csharp
using System.Collections.Generic;
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}
php
$string = implode(", ", $fruits);
haskell
import Data.List

let join = intercalate ", " ["Apple", "Banana", "Carrot"]
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
fantom
["Apple", "Banana", "Carrot"].join(", ")
go
s := strings.Join([]string {"Apple", "Banana", "Carrot"}, ", ")

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
ruby
def join(arr)
return '' if not arr
case arr.size
when 0 then ''
when 1 then arr[0]
when 2 then arr.join(' and ')
else arr[0..-2].join(', ') + ', and ' + arr[-1]
end
end
java
private String join(List elements) {
if (elements == null || elements.size() == 0) {
return "";
} else if (elements.size() == 1) {
return elements.get(0).toString();
} else if (elements.size() == 2) {
return elements.get(0) + " and " + elements.get(1);
}
StringBuffer sb = new StringBuffer();
for (Iterator it = elements.iterator(); it.hasNext();) {
String next = (String) it.next();
if (sb.length() > 0) {
if (it.hasNext()) {
sb.append(", ");
} else {
sb.append(", and ");
}
}
sb.append(next);
}
return sb.toString();
}
System.out.println(join(fruit));
perl
sub myjoin {
$_ = join ', ', @_;
s/, ([^,]+)$/ and $1/;
return $_;
}


# Note: I don't think this meets the spec --Geoff
sub myjoin {
if ($#_ < 2) {
return join ' and ', @_;
} else {
return join(', ', @_[0..$#_-1]) . ' and ' . $_[-1];
}
}

# Note: I don't think this meets the spec --Geoff
# Previous "myjoin()" responses don't meet the spec of including
# the final comma before the "and" if the list has more than
# two elements...this is one way to meet that spec...it may
# not be the most efficient...

sub AnotherMyJoin {
my @list = @_;

if ($#list == -1) {return}
elsif ($#list == 0) {return $list[0]}
elsif ($#list == 1) {return $list[0].' and '.$list[1]}
else {
return join(", ", @list[0..$#list - 1]) . ', and '. $list[$#list];
}
}
# This is the long way, but it's kind of fun
# It illustrates the use of Perl's reverse()
# operator to work our way through the list
# elements backwards...I wrote this one before
# getting smart and looking at some of the other
# algorithms from the other languages. Still,
# it is only 12 lines of code vs 9 for my other
# solution if you disregard the comments.

sub myjoin {
my @list = reverse(@_); # Reverse original order of elements
my $retval;

# Make our exit here if we were passed an empty list
if ($#list == -1) {return}

# Loop through reversed elements in end-to-start order
for (0..$#list) {
# Add the reversed form of each element plus a space char
$retval .= reverse($list[$_]).' ';

# Add 'and' to lists with two or more elements
# placing it in between final and 'next to final'
$retval .= "dna " if ($#list > 0 and $_== 0);

# Add ',' to each element as long as there are more
# than two elements and the current element isn't the
# final element
$retval .= "," if ($#list > 1 and $_ != $#list);
}

# Remove what will end up as an extraneous leading space
chop($retval);

# Done looping, now reverse things back into correct order and return
$retval = reverse($retval);
return($retval);
}
# Yes, this doesn't meet the spec, the spec is flawed
# the serial comma (Oxford comma) is not required in a list
sub english_join {
return join(', ', @_[0..$#_-1])
. ($#_ ? ' and ' : '' )
. $_[-1];
}
groovy
def join(list) {
if (!list) return ''
switch(list.size()) {
case 1:
return list[0]
case 2:
return list.join(' and ')
default:
return list[0..-2].join(', ') + ', and ' + list[-1]
}
}
ArrayList.metaClass.joinEng = { ->
def closureMap = [0: { -> delegate.join(' and ')}, 1 : {-> delegate.join(' and ')}].withDefault { k -> { -> delegate[0..-2].join(', ') + ', and ' + delegate[-1] } }
if (delegate.size()) closureMap[delegate.size()-1].call()
else ""
}

assert ["a"].joinEng() == "a"
assert ["a", "b"].joinEng() == "a and b"
assert ["a", "b", "c"].joinEng() == "a, b, and c"
assert [].joinEng() == ""
def join(list) {
list.join(', ').reverse().replaceFirst(/,/, "dna ").reverse()
}
scala
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case _ => list(0) + ", " + join(list.tail)
}
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case x::xs => x + ", " + join(xs)
}
def join[T](list : List[T]) = list match {
case xs if xs.size < 3 => xs.mkString(" and ")
case xs => xs.init.mkString(", ") + ", and " + xs.last
}
python
def join(*x):
if len(x) <= 2:
return ' and '.join(x)
else:
return ', '.join(x[:-1] + ('and ' + x[-1],))

if __name__ == "__main__":
assert join("Apple", "Banana", "Carrot") == "Apple, Banana, and Carrot"
assert join("One", "Two") == "One and Two"
assert join("Lonely") == "Lonely"
assert join(*[]) == ""
cpp
Console::WriteLine(join(fruit));
string join(const vector<string> &s, int b=0)
{
switch (s.size() - b)
{
case 0: return "";
case 1: return s[b];
case 2: return s[b] + (s.size() > 2 ? "," : "") + " and " + s[b+1];
default: return s[b] + ", " + join(s, b+1);
}
}
fsharp
let join list =
let rec join' list' s =
match list' with
| [] -> s
| [w] -> join' [] (s ^ " and " ^ w)
| w :: ws -> join' ws (s ^ ", " ^ w)
match list with
| [] -> ""
| w :: ws -> join' ws w

// ------

printfn "%s" (join fruit)
erlang
io:format("~s~n", [join(Fruit)]).

% ------

join([]) -> "";
join([W|Ws]) -> join(Ws, W).

join([], S) -> S;
join([W], S) -> join([], S ++ " and " ++ W);
join([W|Ws], S) -> join(Ws, S ++ ", " ++ W).
%% According to the reference manual, "string is not a data type in Erlang."
%% Instead it has lists of integers. But I/O functions in general accept
%% IO lists, where an IO list is either a list of IO lists or an integer.
%% This gives you O(1) string concatenation.

-module(commalist).
-export([join/1]).

join([]) -> "";
join([W]) -> W;
join([W1, W2]) -> [W1, " and ", W2];
join([W1, W2, W3]) -> [W1, ", ", W2, ", and ", W3];
join([W1|Ws]) -> [W1, ", ", join(Ws)].

ocaml
let join list =
let rec join' list acc =
match list with
| [] -> ""
| [single] -> single
| one::[two] ->
if acc = "" then one ^ " and " ^ two
else acc ^ one ^ ", and " ^ two
| first::others -> join' others (acc ^ first ^ ", ")
in
join' list ""
csharp
using System.Collections.Generic;
using System.Linq;

public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}
php
function ImplodeToEnglish($array) {
// sanity check
if (!$array || !count ($array))
return "";

// get last element
$last = array_pop($array);

// if it was the only element - return it
if (!count ($array))
return $last;

return implode(", ", $array)." and ".$last;
}
//example
ImplodeToEnglish(array("Apple", "Banana")); // returns: Apple and Banana
haskell
join [] = ""
join [x] = x
join [x,y] = x ++ " and " ++ y
join [x,y,z] = x ++ ", " ++ y ++ ", and " ++ z
join (x:xs) = x ++ ", " ++ join xs
clojure
(defn join [lst]
(cond
(= (count lst) 0) ""
(= (count lst) 1) (first lst)
(= (count lst) 2) (str (first lst) " and " (second lst))
(> (count lst) 2) (loop [lst lst sb (StringBuilder.)]
(if (empty? lst)
(.toString sb)
(recur (rest lst) (.append sb (cond
(> (count lst) 2) (str (first lst) ", ")
(> (count lst) 1) (str (first lst) ", and ")
(= (count lst) 1) (str (first lst)))))))))
(defn join
([lst]
(join lst false))
([lst is-long]
(condp = (count lst)
0 ""
1 (first lst)
2 (str (first lst) (if is-long ",") " and " (second lst))
(str (first lst) ", " (join (rest lst) true)))))
(defn join [& a]
(case (count a)
0 ""
1 (-> a first str)
2 (->> a (interpose " and ") (apply str))
(apply str (concat (interpose ", " (butlast a)) [", and " (last a)]))))
fantom
join := |List list -> Str|
{
switch(list.size)
{
case 0: return ""
case 1: return list[0]
case 2: return list.join(" and ")
default: return list[0..-2].join(", ") + ", and " + list[-1]
}
}

echo(join(["Apple", "Banana", "Carrot"]))
echo(join(["One", "Two"]))
echo(join(["Lonely"]))
echo(join([,]))

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
ruby
common = [] ; [4, 5].each {|n| ['a', 'b', 'c'].each {|l| common << [l, n]}}
[4, 5].product(['a', 'b', 'c']).map(&:reverse)
java
List<String> combinations = new ArrayList<String>();

for (int number : numbers)
for (String letter : letters)
combinations.add(letter + ":" + Integer.toString(number));
SortedSet<AbstractMap.SimpleImmutableEntry<String, Integer> > combinations =
new TreeSet<AbstractMap.SimpleImmutableEntry<String, Integer> >(new CombinationComparator());

for (int number : numbers)
for (String letter : letters)
combinations.add(new AbstractMap.SimpleImmutableEntry<String, Integer>(letter, Integer.valueOf(number)));
perl
@letters = qw(a b c);
@numbers = (4, 5);
@list = map { $number=$_; map [$_, $number], @letters; } @numbers;
@letters = qw(a b c);
@numbers = (4, 5);

for $number (@numbers) {
for $letter (@letters) {
push @list, [$letter, $number];
}
}
groovy
letters = ['a', 'b', 'c']
numbers = [4, 5]
combos = [letters, numbers].combinations()
scala
val combinations =
(numbers foldLeft List[Pair[String, Int]]()) { (acc : List[Pair[String, Int]], number : Int) =>
acc ::: (letters map { (letter : String) => Pair(letter : String, number : Int) }) }
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}

// ------

val combinations =
product(numbers, letters) map { (c) => c match { case Pair(number, letter) => Pair(letter, number) } }
val letters = List('a', 'b', 'c')
val numbers = List(4, 5)
for { l <- letters; n <- numbers } yield (l,n)
python
[(x, y) for y in [1,2] for x in ['a','b','c']]
import itertools
[x for x in itertools.product(["a", "b", "c"], [4, 5])]
cpp
Specialized::StringCollection^ combinations = gcnew Specialized::StringCollection;

for each(int number in numbers)
for each(String^ letter in letters)
combinations->Add(makeCombo(letter, number));
string letters[] = { "a", "b", "c" };
int numbers[] = { 4, 5 };
list<pair<string,int> > combo;

for (int n = 0; n < sizeof numbers / sizeof *numbers; n++)
for (int l = 0; l < sizeof letters / sizeof *letters; l++)
combo.push_back(make_pair(letters[l], numbers[n]));

cout << combo << endl;
fsharp
let combinations = (List.fold_left (fun acc number -> acc @ (List.map (fun letter -> (letter, number)) letters)) [] numbers)
let combinations aa bb =
aa
|> List.map (fun a -> bb |> List.map (fun b -> (a, b)))
|> List.concat
erlang
Combinations =
lists:foldl(fun (Number, Acc) -> Acc ++ lists:map(fun (Letter) -> {Letter, Number} end, Letters) end, [], Numbers),
Combinations = lists:keysort(2, sofs:to_external(sofs:product(sofs:set(Letters), sofs:set(Numbers))))
[[A, B] || A <- ["a", "b", "c"], B <- [4, 5]].

ocaml
let combinations =
let l1 = ["a"; "b"; "c"]
and l2 = [4; 5] in
List.rev (
List.fold_left (fun acc y ->
List.fold_left (fun acc2 x ->
(x, y)::acc2
) acc l1
) [] l2
)
csharp
using System.Collections.Generic;
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };

// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}
php
foreach ($short as $s) {
foreach ($long as $l) {
$list[] = array($l, $s);
}
}
haskell
comb :: [(String, Int)]
comb = do
b <- [4,5]
a <- ["a","b","c"]
return (a,b)

main = mapM_ print comb
comb :: [(String, Int)]
comb = [(a, b) | b <- [4,5], a <- ["a","b","c"]]

main = print comb
clojure
(defn combine [lst1 lst2]
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) ["a", "b", "c"])) [4, 5])
(for [x [4 5] y ["a" "b" "c"]] [y x])
fantom
[4,5].each |Int i| { ["a","b","c"].each |Str s| { r.add([i,s]) } }

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
ruby
foo = ['andrew', 'bob', 'chris', 'bob']
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
xs = ['andrew', 'bob', 'chris', 'bob']
xs.uniq.select { |x| xs.count(x) > 1 }
java
List listOfDuplicates = new ArrayList(Arrays.asList(new String[]{"andrew", "bob", "chris", "bob"}));

Set set = new HashSet(listOfDuplicates);
for (Object element : set)
listOfDuplicates.remove(element);
perl
my @input = ("andrew", "bob", "chris", "bob", "bob");

my %input_count;
my @output = grep { $input_count{$_}++; $input_count{$_} == 2 } @input;
groovy
def input = ["andrew", "bob", "chris", "bob"]

def output = input.findAll{input.count(it)>1}.unique()

assert output == ["bob"]
scala
List("andrew", "bob", "chris", "bob")
.groupBy(identity)
.filter( person => person._2.size > 1)
.map(_._1)
val l = List("andrew", "bob", "chris", "bob")
l.diff(l.distinct)
python
import itertools
input = ["andrew", "bob", "chris", "bob"]
input.sort()
output = [k for k, g in itertools.groupby(input, lambda x: x) if len(list(g)) > 1]
cpp
vector<string> lst = { "andrew", "bob", "chris", "bob" };
vector<string> lst_no_dups;
vector<string> tmp;
vector<string> dups;

sort(lst.begin(), lst.end());
unique_copy(lst.begin(), lst.end(), back_inserter(lst_no_dups));
set_difference(lst.begin(), lst.end(),
lst_no_dups.begin(), lst_no_dups.end(),
back_inserter(tmp));
unique_copy(tmp.begin(), tmp.end(), back_inserter(dups));

cout << dups << endl;
list<string> lst = { "andrew", "bob", "chris", "bob" };
map<string,int> num_identical;
list<string> dups;

for (auto &s: lst)
num_identical[s]++;
for (auto &n: num_identical)
if (n.second > 1)
dups.push_back(n.first);
cout << dups << endl;
fsharp
["andrew"; "bob"; "chris"; "bob"]
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
erlang
{_, Result} = lists:foldl(
fun(X, {Uniq, Dupl}) -> case lists:member(X, Uniq) of
true -> {Uniq,[X | Dupl]};
_ -> {[X | Uniq], Dupl}
end
end,
{[], []},
List),
Fun = fun
([X | Xs], F) -> case lists:member(X, Xs) of
true -> [X | F(Xs, F)];
_ -> F(Xs, F)
end;
([], _) -> []
end,
Result = Fun(List, Fun).
ocaml
let rem v lst =
let rec aux acc = function
| [] -> List.rev acc
| x::xs ->
if compare v x = 0
then aux acc xs
else aux (x::acc) xs
in
aux [] lst

(** in case of a match, returns a list with the duplicate(s) removed *)
let rec mem_rem v lst =
let rec aux acc = function
| [] -> None
| x::xs ->
if compare v x = 0
then Some(List.rev_append acc (rem v xs))
else aux (x::acc) xs
in
aux [] lst

let duplicates lst =
let rec aux acc = function
| [] -> List.rev acc
| x::xs ->
match mem_rem x xs with
| Some ret -> aux (x::acc) ret
| None -> aux acc xs
in
aux [] lst

let () =
let lst = ["andrew"; "bob"; "chris"; "bob"; "mike"; "peter"; "bob"] in
let dup = duplicates lst in
List.iter print_endline dup
(* Using standard (functorized) sets *)

module SetTools(ASet: Set.S) =
struct
let find_duplicates l =
let rec aux l seen acc =
match l with
| [] -> acc
| h :: q ->
if ASet.mem h seen then
aux q seen (h :: acc)
else
aux q (ASet.add h seen) acc in
aux l (ASet.empty) []
end

module StringSet = Set.Make(String)

module StringSetTools = SetTools(StringSet)

StringSetTools.find_duplicates ["andrew"; "bob"; "chris"; "bob"];;
csharp
List<String> values = new List<string> {"andrew", "bob", "chris", "bob"};

var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}
php
$arr = array('andrew', 'bob', 'chris', 'bob', 'chris', 'john', 'mary', 'lucy');

function match($a, $b)
{
// This is a separate function so you could include checking
// with loose comparisons or lowercase both strings, etc.
return $a === $b;
}

$results = array();

sort($arr);

for($i = 0; $i < count($arr) - 1; $i++)
{
if (match($arr[$i], $arr[$i+1]))
{
$results[] = $arr[$i];
$i++;
}
}
print_r($results);
$arr = array('lucy', 'andrew', 'lucy', 'bob', 'chris', 'bob', 'chris', 'john', 'mary');

function match($a, $b)
{
// This is a separate function so you could include checking
// with loose comparisons or lowercase both strings, etc.
return $a === $b;
}

$results = array();

for($i = 0; $i < count($arr); $i++)
{
if (isset($results[$arr[$i]]))
{
$results[$arr[$i]]++;
}
else
{
$results[$arr[$i]] = 0;
}
}

$out = array();

foreach($results as $name => $count)
{
echo $name . ':' . $count . '<br />';
if ($count > 0)
{
$out[] = $name;
}
}

print_r($out);
<?php
$array = array("andrew", "bob", "chris", "bob");
$counts = array_count_values($array);

$duplicates = array_filter(
array_unique($array),
function($key) use ($counts) {
return $counts[$key] > 1;
}
);
?>
haskell
import Data.List

input = ["andrew", "bob", "chris", "bob"]
output = [ head l | l <- group (sort input), length l > 1]
clojure
(->> '("andrew" "bob" "chris" "bob")
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
fantom
nameCounts := Str:Int[:] { def = 0 }
["andrew", "bob", "chris", "bob"].each |Str v| { nameCounts[v]++ }
results := nameCounts.findAll |Int v, Str k->Bool| { v > 1 }.keys
echo(results.join(","))

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
['One', 'Two', 'Three', 'Four', 'Five'].fetch(2)
list = ['One', 'Two', 'Three', 'Four', 'Five']
list.at(2)
['One', 'Two', 'Three', 'Four', 'Five'][2] # <= note the [2] at end of array
java
String result = list.get(2);
perl
qw(One Two Three Four Five)[2];
@list = qw(One Two Three Four Five);
$list[2];
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
result = list[2] // index starts at 0
scala
val result = list(2)
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
cpp
String^ result = list[2];
fsharp
let result = List.nth ["One"; "Two"; "Three"; "Four"; "Five"] 2
erlang
Result = lists:nth(3, List),
Result = element(3, list_to_tuple(List)),
{Left, _} = lists:split(3, List), Result = lists:last(Left),
Result = nth0(2, List),
ocaml
let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;;
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
php
$list = array("One", "Two", "Three", "Four", "Five");
$three = $list[2];
haskell
let a = [1..5]
let b = a !! 2
print b
clojure
(nth '[One Two Three Four Five] 2)
fantom
["One", "Two", "Three", "Four", "Five"][2]
["One", "Two", "Three", "Four", "Five"].get(2)
go
fmt.Println(list[2])

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
ruby
['Red', 'Green', 'Blue'][-1]
['Red', 'Green', 'Blue'].at(-1)
['Red', 'Green', 'Blue'].last
['Red', 'Green', 'Blue'].fetch(-1)
java
String result = list.get(list.size() - 1);
perl
qw(Red Green Blue)[-1];
@list = qw(Red Green Blue);
$list[-1];
groovy
list = ['Red', 'Green', 'Blue']
result = list[-1]
list = ['Red', 'Green', 'Blue']
result = list.last()
scala
val result = list.last
val result = (list.drop(list.length - 1)).head
python
list = ['Red', 'Green', 'Blue']
list[-1]
Seaton India
cpp
String^ result = list[list->Count - 1];
string last_elem = lst.back();
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
let result = (List.nth list ((List.length list) - 1))
let result = (List.hd (List.rev list))
erlang
Result = lists:last(List),
Result = last(List),
Result = hd(lists:reverse(List)),
Result = lists:nth(length(List), List),
ocaml
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.nth list ( (List.length list) - 1 );;
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.hd (List.rev list);;
let list_last l =
let rec aux h q =
match q with
| [] -> h
| h :: q -> aux h q in
match l with
| [] -> invalid_arg "list_last"
| h :: q -> aux h q
;;
list_last ["Red"; "Green"; "Blue"]
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
// 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"
php
$list = array("Red", "Green", "Blue");
$last = array_pop($list);

// Be aware of that $list only contains two elements now - not three
$list = array("Red", "Green", "Blue");
$last = $list[count($list)-1];
haskell
last ["Red", "Green", "Blue"]
clojure
(last '[One Two Three Four Five])
fantom
["Red", "Green", "Blue"][-1]
["One", "Two", "Three", "Four", "Five"].last

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
ruby
common = (beans.intersection(colors)).to_a
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = beans & colors
java
List beans = Arrays.asList(new String[]{"broad", "mung", "black", "red", "white"});
List colors = Arrays.asList(new String[]{"black", "red", "blue", "green"});

List common = ListUtils.intersection(beans, colors);
perl
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);
@seen{@beans} = ();
for (@colors) {
push(@intersection, $_) if exists($seen{$_});
}
print join(', ', @intersection);
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);

my %colors_hash = map { $_ => 1 } @colors;
my @intersection = grep { $colors_hash{$_} } @beans;
print join(', ', @intersection),"\n";
@beans = qw/broad mung black red white/;
@colors = qw/black red blue green/;

print join ', ', grep { $_ ~~ @colors } @beans;
groovy
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = beans.intersect(colors)
assert common == ['black', 'red']
scala
val beans = "broad" :: "mung" :: "black" :: "red" :: "white" :: Nil
val colors = "black" :: "red" :: "blue" :: "green" :: Nil
val common = beans intersect colors
python
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']

common = [b for b in beans if b in colors]
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']

common = set(beans) & set(colors)
cpp
array<String^>^ inbeans = {"broad", "mung", "black", "red", "white"};
Generic::ICollection<String^>^ beans = makeSET<String^>(gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) inbeans));

array<String^>^ incolors = {"black", "red", "blue", "green"};
Generic::ICollection<String^>^ colors = makeSET<String^>(gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) incolors));

Generic::ICollection<String^>^ result = intersectSET<String^>(beans, colors);
fsharp
let beans = (Set.of_list ["broad"; "mung"; "black"; "red"; "white"])
let colors = (Set.of_list ["black"; "red"; "blue"; "green"])
let common = (Set.intersect beans colors)
let beans = Set ["broad"; "mung"; "black"; "red"; "white"]
let colors = Set ["black"; "red"; "blue"; "green"]
let common = Set.intersect beans colors
// Iterates elements of
// list1 across Elements of list2 returning a list of string options
// as generated by List.tryFind
let findCommon(list1 : 'a list, list2 : 'a list) : 'a list =
list1 |> List.map(fun y -> list2 |> List.tryFind(fun x -> y = x))
// Iterates elements of string option list generated above
// returning a string list containing common elements of List1 and List2
|> List.fold(fun acc x -> if x <> None then x.Value::acc else acc) []
// reverse order of list (can't seem to make List.foldBack work for this
|> List.rev

let beans = ["broad"; "mung"; "black"; "red"; "white"]
let colors = ["black"; "red"; "blue"; "green"]
printfn "%A" (findCommon(beans, colors)) ;;
erlang
Beans = sets:from_list([broad, mung, black, red, white]), Colors = sets:from_list([black, red, blue, green]),

Common = sets:to_list(sets:intersection(Beans, Colors)),
ocaml
let beans = ["broad"; "mung"; "black"; "red"; "white"]

let colors = ["black"; "red"; "blue"; "green"]

let f common c = if List.mem c beans then c::common else common

let common = List.fold_left f [] colors;;

(* common will contain a list with the common elements *)
(* using standard (functorized) sets *)

module SetTools(ASet: Set.S) =
struct
let of_list l =
List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l

let find_common l1 l2 =
ASet.elements (ASet.inter (of_list l1) (of_list l2))
end

module StringSet = Set.Make(String)

module StringSetTools = SetTools(StringSet)
;;
let beans = ["broad"; "mung"; "black"; "red"; "white"] in
let colors = ["black"; "red"; "blue"; "green"] in
StringSetTools.find_common beans colors;;
csharp
// Make sure you import the System.Linq namespace.
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']
php
$result = array_intersect($beans, $colors);
sort($result); // just to clean it up :)
haskell
import Data.List

beans = ["broad", "mung", "black", "red", "white"]
colors = ["black", "red", "blue", "green"]

main = print (intersect beans colors)
clojure
(use 'clojure.set)

(let [beans '[broad mung black red white]
colors '[black red blue green]]
(intersection (set beans) (set colors)))
fantom
beans := ["broad", "mung", "black", "red", "white"]
colors := ["black", "red", "blue", "green"]
echo(beans.intersection(colors))

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
ruby
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
p ages.uniq
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
ages.uniq!
p ages
ages = (Set.new [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).to_a
p ages
java
Set<Integer> ages = new TreeSet<Integer>(Arrays.asList(new Integer[]{18, 16, 17, 18, 16, 19, 14, 17, 19, 18}));

System.out.println(ages);
perl
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@seen{@ages} = ();
@unique = keys %seen;
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@unique = grep(!$seen{$_}++, @ages);
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', grep(!$seen{$_}++, @ages));
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
for (@ages) {
push(@unique, $_) unless $seen{$_}++;
}
print join(', ', @unique);
use List::MoreUtils qw(uniq);

@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', uniq(@ages));
groovy
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
println ages.unique()
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique = ages as Set
println unique
scala
val ages = (18 :: 16 :: 17 :: 18 :: 16 :: 19 :: 14 :: 17 :: 19 :: 18 :: Nil) removeDuplicates
python
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]

unique_ages = list(set(ages))
cpp
array<int>^ input = {18, 16, 17, 18, 16, 19, 14, 17, 19, 18};
Generic::List<int>^ ages = gcnew Generic::List<int>((Generic::IEnumerable<int>^) input);

Generic::ICollection<int>^ result = makeSET<int>(ages);
list<int> input;
input += 18, 16, 17, 18, 16, 19, 14, 17, 19, 18;
input.sort();
unique_copy(input.begin(), input.end(), ostream_iterator<int>(cout, "\n"));
fsharp
(Set.ofList [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]) |> Set.iter (fun age -> printf "%d, " age)
erlang
Ages = sets:to_list(sets:from_list([18, 16, 17, 18, 16, 19, 14, 17, 19, 18])), io:format("~w~n", [Ages]).
lists:usort([18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).
ocaml
let ages = [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]

let f res e = if List.mem e res then res else e::res

let unique = List.fold_left f [] ages;;
(* using standard (functorized) sets *)

module SetTools(ASet: Set.S) =
struct
let of_list l =
List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l

let unique l =
ASet.elements (of_list l)
end

module Integer =
struct
type t = int
let compare (x:t) y = Pervasives.compare x y
end

module IntegerSet = Set.Make(Integer)
module IntegerSetTools = SetTools(IntegerSet)
;;
IntegerSetTools.unique [18; 16; 17; 18; 16; 19; 14; 17; 19; 18];;
let removeDuplicate list =
let rec aux acc = function
| [] -> acc
| h :: t -> if (List.mem h t) then aux acc t else aux (h::acc) t
in
List.rev (aux [] list);;
csharp
using System.Collections.Generic;
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}
php
$ages = array(18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
$ages = array_unique($ages);
// be aware of that $ages[6] will print 14
haskell
import Data.List

ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]

uniqueAges = nub ages
clojure
;; returns a set
(set [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;#{14 16 17 18 19}

;; returns a lazy sequence of the unique elements
(distinct [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;(18 16 17 19 14)


fantom
uniqueAges := [18, 16, 17, 18, 16, 19, 14, 17, 19, 18].unique
echo(uniqueAges)

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
ruby
['Apple', 'Banana', 'Carrot'].shift
fruit.delete_at(0)
java
list.remove(0);
perl
@list = qw(Apple Banana Carrot);
shift @list;
@list = qw(Apple Banana Carrot);
$offset = 0;
splice(@list, $offset, 1);
groovy
// to produce a new list
newlist = list.tail() // for 'Apple' at start
newlist = list - 'Apple' // for 'Apple' anywhere
// mutate original list
list.remove(0)
scala
val (fl, fr) = fruit.splitAt(0) ; fruit = fl ::: fr.tail
fruit = fruit.tail
fruit = fruit.drop(1)
fruits = fruits.remove(fruits.indexOf(_) == 0)
fruits.filterNot(fruits.indexOf(_) == 0)
python
myList = ['Apple', 'Banana', 'Carrot']
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
Easy trick

a=[Apple, Banana, Carrot]
a=a[1:]

remove first n entry:

a=[n:]

remove last n entry=>

a=[0:-n]
cpp
fruit->RemoveAt(0);
fsharp
let split_at list n =
let rec split_at' list' n' left right =
match list' with
| [] -> (List.rev left, List.rev right)
| x :: xs -> if n' <= n then split_at' xs (n' + 1) (x :: left) right else split_at' xs (n' + 1) left (x :: right)
split_at' list 0 [] []

// ------

let (_, right) = split_at fruit 0
let drop list n =
if n <= 0 then
list
else
let (_, right) = split_at list (n - 1)
right

// ------

let result = (drop fruit 1)
erlang
Result = tl(List),
[_|Result] = List,
N = 1, {Left, Right} = lists:split(N - 1, List), Result = Left ++ tl(Right),
Result = drop(1, List),
ocaml
let delete_at i al =
if i < 0 || i >= List.length al then
invalid_arg "delete_at"
else
let rec del i l =
match l with
| [] -> []
| h::t when i = 0 -> t
| h::t -> h :: del (i-1) t
in
del i al
;;
let rem_first l =
match l with
| [] -> []
| h::t -> t
;;
List.tl ["Apple"; "Banana"; "Carrot"]
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
php
$list = array("Apple", "Banana", "Carrot");
unset($list[0]);

// Be aware of that $list[0] isn't set. "Banana" is still $list[1]
$list = array("Apple", "Banana", "Carrot");
array_shift($list);

// Be aware of that $list[0] is set to "Banana"
haskell
deleteNth n xs | n > 0 = take (n-1) xs ++ drop n xs

main = print $ deleteNth 1 [1..3]
fruit :: [String]
fruit = ["Apple", "Banana", "Carrot"]

main :: IO ()
main = putStrLn $ show $ tail fruit
clojure
(let [fruit ["Apple" "Banana" "Carrot"]
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
(let [v ["Apple" "Banana" "Carrot"]
index 0]
(into (subvec v 0 n) (subvec v (inc n))))
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(0)
go
offset := 0
list = append(list[:offset], list[offset+1:]...)

Remove the last element of a list

ruby
list = ['Apple', 'Banana', 'Carrot']
list.delete_at(-1)
list = ['Apple', 'Banana', 'Carrot']
list.pop
java
list.remove(list.size() - 1);
perl
pop @list;
groovy
list = ['Apple', 'Banana', 'Carrot']
// to produce a new list
newlist = list[0,1]
// to modify original list
list.remove(2)
list = ['Apple', 'Banana', 'Carrot']

result = list[0,-2]

//or using ranges
result = list[0..-2]
scala
fruit = fruit.init
fruit = fruit.take(fruit.length - 1)
python
myList = ['Apple', 'Banana', 'Carrot']
myList.pop()

cpp
fruit->RemoveAt(fruit->Count - 1);
fsharp
let take list n =
if n <= 0 then
list
else
let (left, _) = split_at list (n - 1)
left

// ------

let result = (take fruit ((List.length fruit) - 1))
let but_last list =
let rec but_last' list' acc =
match list' with
| [x] -> List.rev acc
| x :: xs -> but_last' xs (x :: acc)
if List.is_empty list then [] else but_last' list []

// ------

let result = (but_last fruit)
Seq.rev xs |> Seq.tail |> Seq.rev
erlang
Result = init(List),
Result = take(length(List) - 1, List),
Result = lists:reverse(tl(lists:reverse(List))),
lists:sublist(List,length(List)-1)
ocaml
let remove_last list =
match (List.rev list) with
| h::t -> List.rev t
| [] -> []
let remove_last lst =
List.rev (List.tl (List.rev lst))
let list_remove_last l =
let rec aux h q acc =
match q with
| [] -> List.rev acc
| h2 :: q -> aux h2 q (h :: acc) in
match l with
| [] -> invalid_arg "list_remove_last"
| h :: q -> aux h q []
csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);
php
$list = array("Apple", "Banana", "Carrot");
unset($list[count($list)-1]);

// Be aware of that
// $list[] = "Orange";
// will be $list[3] and not $list[2]
$list = array("Apple", "Banana", "Carrot");
array_pop($list);
haskell
ages = [1,2,3,4]

init ages
clojure
(pop ["Apple" "Banana" "Carrot"])
(drop-last ["Apple" "Banana" "Carrot"])
(butlast ["Apple" "Banana" "Carrot"])
(-> ["Apple" "Banana" "Carrot"] reverse rest reverse)
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(-1)
list := ["Apple", "Banana", "Carrot"]ยจ
list.pop

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"]
ruby
items = ["apple", "orange", "grapes", "bananas"]
items << first = items.shift

# items is rotated
# first contains the first value in the list
fruits = ["apple", "orange", "grapes", "bananas"]
fruits.rotate!
java
list.add(list.remove(0));
Collections.rotate(list, -1);
perl
@list = qw(apple, orange, grapes, bananas);
push @list, shift @list;
@list = qw(apple orange grapes bananas);
@list = @list[1..$#list,0];
groovy
first = items.head()
items = items.tail() + first
items = items[1..-1] + items[0]
items = items + items.remove(0)
scala
items = items.tail ::: List(items.head)
items = (items.head :: ((items.tail).reverse)).reverse
python
l = ["apple", "orange", "grapes", "bananas"]
first, l = l[0], l[1:] + l[:1]
fruit = ['apple', 'orange', 'grapes', 'bananas']
fruit.append(fruit.pop(0))
cpp
fruit->Add(fruit[0]); fruit->RemoveAt(0);
rotate(fruit.begin(), fruit.begin()+1, fruit.end());
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)
erlang
N = 1, {Left, Right} = lists:split(N, List), Result = Right ++ Left,
N = 1, Result = rotate(N, List),
ocaml
let rotate list =
match list with
| head::tail -> tail@[head]
| [] -> []
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();
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
haskell
main = print $ rotate ["apple", "orange", "grapes", "bananas"]

rotate xs | length xs < 2 = xs
| otherwise = tail xs ++ [head xs]
clojure
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
fantom
list := ["apple", "orange", "grapes", "bananas"]
list.add(list.removeAt(0))

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
ruby
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]

result = first.zip(last, years)
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]

result = [first, last, years].transpose
java
String[] first = new String[]{"Bruce", "Tommy Lee", "Bruce"};
String[] last = new String[]{"Willis", "Jones", "Lee"};
String[] years = new String[]{"1955", "1946", "1940"};

List<String[]> list = new ArrayList<String[]>(); list.add(first); list.add(last); list.add(years);

String[] result = zip(",", list);
perl
my @first = ('Bruce', 'Tommy Lee', 'Bruce');
my @last = ('Willis', 'Jones', 'Lee');
my @years = (1955, 1946, 1940);

my @actors;

my $max = scalar @first;
for my $index (0 .. $max) {
push @actors, [ $first[$index], $last[$index], $years[$index] ];
};
groovy
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = [first, last, years].transpose()
assert actors.size() == 3
assert actors[1] == ['Tommy Lee', 'Jones', 1946]
scala
def zip3(l1 : List[_], l2 : List[_],l3 : List[_]) : List[Tuple3[_, _, _]] =
{
def zip3$ (l1$ : List[_], l2$ : List[_], l3$ : List[_], acc : List[Tuple3[_, _, _]]) : List[Tuple3[_, _, _]] = l1$ match
{
case Nil => acc reverse
case l1$head :: l1$tail => zip3$(l1$tail, l2$.tail, l3$.tail, Tuple3(l1$head, l2$.head, l3$.head) :: acc)
}

zip3$(l1, l2, l3, List[Tuple3[_,_,_]]())
}

// ------

val result = zip3(first, last, years)
val first = List("Bruce", "Tommy Lee", "Bruce")
val last = List("Willis", "Jones", "Lee")
val years = List(1955, 1946, 1940)
val results = (first, last, years).zipped.toList
println(results)
def zip3[A, B, C](l1 : List[A], l2 : List[B],l3 : List[C]) : List[(A, B, C)] =
l1.zip(l2).zip(l3).map { case ((a, b), c) => (a, b, c) }
python
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]

actors = zip(first, last, years)

assert len(actors) == 3
assert actors[1] == ('Tommy Lee', 'Jones', 1946)
cpp
array<String^>^ first = {"Bruce", "Tommy Lee", "Bruce"}; array<String^>^ last = {"Willis", "Jones", "Lee"}; array<String^>^ years = {"1955", "1946", "1940"};

array<String^>^ result = zip<String^>(",", first, last, years);
list<string> first = { "Bruce", "Tommy Lee", "Bruce" };
list<string> last = {"Willis", "Jones", "Lee"};
list<int> years = {1955, 1946, 1940};
list<tuple<string,string,int> > actors;

for (firstIt = first.begin(), lastIt = last.begin(), yearIt = years.begin();
firstIt != first.end() && lastIt != last.end() && yearIt != years.end();
++firstIt, ++lastIt, ++yearIt)
actors.push_back(make_tuple(*firstIt, *lastIt, *yearIt));
fsharp
let result = (List.zip3 first last years)
erlang
First = ['Bruce', 'Tommy Lee', 'Bruce'], Last = ['Willis', 'Jones', 'Lee'], Years = [1955, 1946, 1940],

Result = lists:zip3(First, Last, Years),
ocaml
let rec combine3 f l y =
match f, l, y with
| [], [], [] -> []
| fh :: fq, lh :: lq, yh :: yq ->
(fh, lh, yh) :: combine3 fq lq yq
| _ -> invalid_arg "combine3"
;;
let first = ["Bruce"; "Tommy Lee"; "Bruce"] in
let last = ["Willis"; "Jones"; "Lee"] in
let years = [1955; 1946; 1940] in
combine3 first last years
csharp
String[] first = { "Bruce", "Tommy Lee", "Bruce" };
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));
php
for ($i = 0; $i < $count; $i++) {
$list[] = array($first[$i], $last[$i], $years[$i]);
}
$list = array_map(NULL, $first, $last, $years);
haskell
import Prelude hiding (last)

first = ["Bruce", "Tommy Lee", "Bruce"]
last = ["Willis", "Jones", "Lee"]
years = [1955, 1946, 1940]

actors = zip3 first last years
clojure
(defn gatherer [listOfLists]
(if (empty? (first listOfLists))
() ; the base case for recursion
(cons
(map first listOfLists) ; get the first element of each of the lists
(gatherer (map rest listOfLists)) ; gather all the subsequent ones
)
)
)

(def firstnames '("Bruce" "Tommy Lee" "Bruce"))
(def lastnames '("Willis" "Jones" "Lee"))
(def years '(1955 1946 1940))

(println (gatherer [firstnames lastnames years]))

; -> ((Bruce Willis 1955) (Tommy Lee Jones 1946) (Bruce Lee 1940))
(def firstnames ["Bruce" "Tommy Lee" "Bruce"])
(def lastnames ["Willis" "Jones" "Lee"])
(def years [1955 1946 1940])
(println (map (fn [f l y] [f l y]) firstnames lastnames years))
fantom
r := [,]
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }

echo(r)

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
ruby
suites.each {|s| faces.each {|f| cards << [s, f]}}
puts "Deck %s \'Ace of Hearts\'" % if cards.include?(['h', 'A']) then "contains" else "does not contain" end
suites = ['H', 'D', 'C', 'S']
faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']

deck = suites.product(faces)

puts deck.length #=> 52
puts deck.include?(['H', 'A']) #=> true
java
SortedSet<AbstractMap.SimpleImmutableEntry<String, String> > cards =
new TreeSet<AbstractMap.SimpleImmutableEntry<String, String> >(new CardComparator());

for (String suite : suites)
for (String face : faces)
cards.add(new AbstractMap.SimpleImmutableEntry<String, String>(suite, face));

Boolean containsEntry = cards.contains(new AbstractMap.SimpleImmutableEntry<String, String>("h", "A"));

if (containsEntry) System.out.println("Deck contains 'Ace of Hearts'");
else System.out.println("'Ace of Hearts' not in deck");
perl
@suites = qw(H D C S);
@faces = qw(2 3 4 5 6 7 8 9 10 J Q K A);
@deck = map { $suite=$_; map $suite.$_, @faces; } @suites;
print 'checking deck size: ' . (@deck == 52 ? 'pass' : 'fail') . "\n";
print 'deck contains "Ace of Hearts": ' . (grep(/^HA$/, @deck) ? 'true' : 'false') . "\n";
groovy
faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suites = ['H', 'D', 'C', 'S']
deck = [faces, suites].combinations()
assert deck.size() == 52
assert ['A', 'H'] in deck
scala
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}

// ------

val cards = product(suites, faces)

printf("Deck has %d cards\n", cards.length)
if (cards.contains(Pair("h", "A"))) println("Deck contains 'Ace of Hearts'")
else println("'Ace of Hearts' not in this deck")
python
suites = ('H', 'D', 'C', 'S')
faces = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
deck = [(face,suite) for suite in suites for face in faces]
assert len(deck) == 52
assert ('A', 'H') in deck
cpp
Specialized::StringCollection^ cards = gcnew Specialized::StringCollection;

for each(String^ suite in suites)
for each(String^ face in faces)
cards->Add(makeCard(suite, face));

Console::WriteLine("Deck has {0} cards", cards.Count);
if (cards->Contains(makeCard("h", "A"))) Console::WriteLine("Deck contains 'Ace of hearts'"); else Console::WriteLine("'Ace of hearts' not in deck");
auto suites = {"h", "d", "c", "s"};
auto faces = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
list<card> cards;

for (auto s: suites)
for (auto f: faces)
cards.push_back(make_pair(s,f));

cout << "Deck has " << cards.size() << " cards." << endl;

card ace_of_harts = make_pair("h", "A");
if (end(cards) != find_if(begin(cards), end(cards),
[&](const card& c) { return c == ace_of_harts; }))
cout << "Deck contain 'Ace of Harts'" << endl;
else
cout << "Deck lacks 'Ace of Harts'" << endl;
fsharp
let cards = (List.fold_left (fun acc suite -> acc @ (List.map (fun face -> (suite, face)) faces)) [] suites)

printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
let product (set1 : List<'a>) (set2 : List<'a>) : List<'a * 'a> =
let p = new ResizeArray<'a * 'a>()
for e1 in set1 do for e2 in set2 do p.Add(e1, e2) done done
Array.to_list (p.ToArray())

// ------

let cards = product suites faces

printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
let deck =
suites
|> List.map (fun s -> faces |> List.map (fun f -> (s, f)))
|> List.concat

printfn "Deck has %d cards" (List.length deck)
match deck |> List.exists (fun e -> e = ("h", "A")) with
| true -> printfn "Deck contains 'Ace of Hearts'"
| _ -> printfn "'Ace of Hearts' not in deck"
erlang
Cards = lists:foldl(fun (Suite, Acc) -> Acc ++ lists:flatmap(fun (Face) -> [{Suite, Face}] end, Faces) end, [], Suites),

io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
Cards = sofs:to_external(sofs:product(sofs:set(Suites), sofs:set(Faces))),

io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
Deck2 = [{S, V} || S <- [d, c, h, s], V <- [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']],
52 = length(Deck2),
true = lists:member({h, 'A'}, Deck2).

ocaml
let suites = ["H"; "D"; "C"; "S"]
let faces = ["2";"3";"4";"5";"6";"7";"8";"9";"10";"J";"Q";"K";"A"]

let desk =
List.fold_left (fun acc y ->
List.fold_left (fun acc2 x ->
(x, y)::acc2
) acc faces
) [] suites

let () =
assert (List.length desk = 52);
if List.mem ("A", "H") desk
then print_endline "Ace of Hearts found!"
else print_endline "Ace of Hearts not found :("
csharp
using System;
using System.Collections.Generic;
using System.Linq;

namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};

// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}

// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}

// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}

// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52

Console.ReadLine();
}
}
}
php
foreach ($suites as $suite) {
foreach ($faces as $face) {
$cards[] = $suite.$face;
}
}
if (count($cards) == 52) {
echo "The deck have all 52 cards.\n";
}
if (in_array("HA", $cards)) {
echo "The deck contains 'Ace of Heart'\n";
} else {
echo "The deck doesn't contain 'Ace of Heart'\n";
}
haskell
import Data.List

suites = ["H", "D", "C", "S"]
faces = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

main = do
let cards = [(s,f) | s <- suites, f <- faces ]
print (length cards)
print $ hasCard ("H", "A") "Ace of Hearts" cards
where hasCard t name cards = (if elem t cards then "Contains "
else "Does not contain") ++ name
clojure
(def suites ["H" "D" "C" "S"])
(def faces [2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A"])
(defn listCards [] (for [s suites f faces] [f s]))
(some (partial = ["A" "H"]) (listCards))
; -> true
(count (listCards))
; -> 52
fantom
r := [,]
["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c|
{ ["H","D","C","S"].each |Str s| { r.add([c,s]) } }

q := ["A","H"]
result := r.contains(q)
echo("Deck size=${r.size}, contains $q? -> $result")

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
ruby
["ox", "cat", "deer", "whale"].map{|i| i.length}
java
public class SolutionXX {
public static void main(String[] args) {
String[] list = {"ox", "cat", "deer", "whale"};
for (String str : list) {
System.out.println(str.length() + " ");
}
}
}
perl
my @list = qw{ox cat deer whale};

my @lengths = map {length($_)} @list;

print "@list\n";
print "@lengths\n";
groovy
animals = ["ox", "cat", "deer", "whale"]
assert animals*.size() == [2, 3, 4, 5]
// or somewhat more verbosely, using collect
animals = ["ox", "cat", "deer", "whale"]
assert animals.collect { it.size() } == [2, 3, 4, 5]
scala

val sizes = List("ox", "cat", "deer", "whale") map {_ size}
assert(sizes == List(2, 3, 4, 5))
python
print map(lambda x: len(x), ["ox", "cat", "deer", "whale"])
print [len(x) for x in ['ox', 'cat', 'deer', 'whale']]
cpp
list<string> words;

words.push_back("ox");
words.push_back("cat");
words.push_back("deer");
words.push_back("whale");

for (list<string>::iterator it = words.begin(); it != words.end(); ++it)
cout << it->size() << ' ';
cout << endl;
auto words = { "ox", "cat", "deer", "whale" };
list<size_t> word_sizes;

transform(begin(words),
end(words),
back_inserter(word_sizes),
[](const string& s) { return s.size(); });
fsharp
let lengths = List.map String.length ["ox"; "cat"; "deer"; "whale"]
erlang
lists:map(fun (X) ->length(X) end, List).
ocaml
List.map String.length ["ox"; "cat"; "deer"; "whale"];;
csharp
using System.Collections.Generic;
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}
php
$sizes = array_map('strlen', array('ox', 'cat', 'deer', 'whale'));
haskell
map length ["ox", "cat", "deer", "whale"]
clojure
(map count ["ox" "cat" "deer" "whale"])
fantom
["ox", "cat", "deer", "whale"].map { it.size }

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
ruby
now=Time.now
things=["hello", 25, 3.14, now]

numbers=things.select{|i| i.is_a? Numeric}
others=things-numbers
now=Time.now
things=["hello", 25, 3.14, now]

numbers, others=things.partition{|i| i.is_a? Numeric}
java
public class NumbersSolution {
public static void main(String[] args) {
List<Object> items = Arrays.asList(new Object[] { new Date(), 12L, 15.4, 99, "x" } ) ;
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : items )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
public class NumbersSolution {
public static void main() {
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : new Object[] { new Date(), 12L, 15.4, 99, "x" } )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
perl
use Scalar::Util qw(looks_like_number);
my @things = ('hello',25,3.14,scalar(localtime(time)));
my @numbers;
my @others;
for ( @things ) {
if ( looks_like_number $_ ) {
push @numbers, $_;
} else {
push @other, $_;
}
}
groovy
now = new Date()
things = ["hello", 25, 3.14, now]
(numbers, others) = things.split{ it instanceof Number }
assert numbers == [25, 3.14]
assert others == ["hello", now]
scala
val now = new java.util.Date()
val result = List("hello", 25, 3.14, now) partition { _.isInstanceOf[Number] }
assert(result == (List(25, 3.14), List("hello", now)))
python
import re
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)

nonDigits = re.findall(re.compile('\D'), data)
digits = re.findall(re.compile('\d'), data)


cpp
typedef variant<int,float,string,date> dynamic;

class is_number : public static_visitor<bool>
{
public:
bool operator()(int &) const {
return true;
}
bool operator()(float &) const {
return true;
}
bool operator()(string &) const {
return false;
}
bool operator()(date &) const {
return false;
}
};

int main()
{
list<dynamic> lst;
list<dynamic> numbers;
list<dynamic> non_numbers;

lst += "hello", 3.14f, 42, date(2011,Aug,23);

BOOST_FOREACH(dynamic v, lst)
if (apply_visitor(is_number(), v))
numbers += v;
else
non_numbers += v;
#include <iostream>
#include <list>

#include <boost/any.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/foreach.hpp>

using namespace boost;
using namespace boost::gregorian;
using namespace std;

int main()
{
list<any> lst;
list<any> numbers;
list<any> non_numbers;

lst.push_back(string("hello"));
lst.push_back(42);
lst.push_back(3.14f);
lst.push_back(date(day_clock::local_day()));

BOOST_FOREACH(const any &a, lst)
try
{
numbers.push_back(any_cast<int>(a));
}
catch (bad_any_cast &e)
{
try
{
numbers.push_back(any_cast<float>(a));
}
catch (bad_any_cast &e)
{
non_numbers.push_back(a);
}
}

// float and int are now in 'numbers' and the rest in 'non_numbers'
}
fsharp
let (things:obj list) = [ "hello"; 25; 3.14; System.DateTime.Now ]

let isNumber (x:obj) =
match x with
| :? int | :? float | :? byte | :? decimal | :? int16 | :? int64 -> true
| _ -> false

let numbers, nonNumbers = things |> List.partition isNumber
erlang
% Wrapped call to the auxiliary function
number_split(Xs) ->
number_split(Xs, [], []).

% The auxiliary function
number_split([], Num, NonNum) ->
{Num, NonNum};
number_split([X|Xs], Num, NonNum) ->
case is_number(X) of
true ->
number_split(Xs, [X|Num], NonNum);
false ->
number_split(Xs, Num, [X|NonNum])
end.
List = ["hello", 25, 3.14, calendar:local_time()],
{Numbers, NonNumbers} = lists:partition(fun(E) -> is_number(E) end, List)
ocaml
(* OCaml is a strongly statically typed language so it is not possible to mix
items of different types in a single list.
So here we use a list of strings, some of these strings represent a number *)

let is_a_number v =
try ignore(float_of_string v); true
with _ -> false

let numbers, others =
List.partition is_a_number ["Joe"; "3.14"; "8"; "hello"; "23/04/2009"]

(* ========================================================================== *)
(* If we really want to mix items of several types, we can declare a variant: *)

type item = Int of int | Float of float | String of string | Char of char

let is_a_number = function
| Float _ | Int _ -> true
| String _ | Char _ -> false

let numbers, others =
List.partition is_a_number [String "Joe"; Float 3.14; Int 8; Char 'Z']
csharp
using System;
using System.Collections.Generic;
using System.Linq;

// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };

// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}

}
php
$now = new DateTime();
$things = array('hello', 25, 3.14, $now);
$numbers = array_filter($things, 'is_numeric');
$others = array();
foreach ($things as $thing) {
if (!in_array($thing, $numbers)) {
$others[] = $thing;
}
}
haskell
import Data.List (partition)

type Date = String
data Things = TS String | TI Int | TD Date
deriving Show

main = do
let myList = [TI 1, TI 23, TS "Joe", TD "23/04/2009"]
print $ partition isNumber myList

where isNumber (TS _) = False
isNumber (TI _) = True
isNumber (TD _) = False
clojure
(def jumble [3 "Bill" 5.7 '("A" "B" "C")]) ; int, string, float, list

(defn numberNonNumberSorter [jumbledList]
(if (empty? jumbledList)
(hash-map :numbers [], :nonnumbers []) ; recursion base case - return two empty lists
(let [head (first jumbledList)] ; let <head> be the first element in the list
(let [tailresult (numberNonNumberSorter (rest jumbledList))] ; tailresult applies recursively to the remainder
(if (number? head) ; is head a number?
(hash-map
:numbers (cons head (tailresult :numbers)) ; add <head> to the numbers
:nonnumbers (tailresult :nonnumbers)) ; leave nonnumbers the same
(hash-map
:numbers (tailresult :numbers) ; leave numbers the same
:nonnumbers (cons head (tailresult :nonnumbers))) ; add <head> to nonnumbers
)
)
)
)
)

(println (numberNonNumberSorter jumble))

; -> {:nonnumbers (Bill (A B C)), :numbers (3 5.7)}
(group-by number? ["hello" 42 3.14 (Date.)])
fantom
things := ["hello", 25, 3.14, Time.now]
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
ruby
[2, 3, 4].all? { |x| x > 1 }
java
List<String> la = Arrays.asList("a", "b", "", "c");// listWithEmptyValues
List<String> lb = Arrays.asList("a", null, "", "c");// listWithNullValues
List<String> lc = Arrays.asList("a", "b", "d", "c");// listWithNonEmptyValues

Predicate<String> correctValue = (String s) -> s != null && !s.isEmpty();

System.out.println(la.stream().allMatch(correctValue)); // false
System.out.println(lb.stream().allMatch(correctValue)); // false
System.out.println(lc.stream().allMatch(correctValue)); // true
int[] array = {1, 2, 3}; Arrays.stream(array).anyMatch((x) -> x > 1);
groovy
[2,3,4].every{it > 1}
scala
List(2, 3, 4).forall { _ > 1 }
List(2, 3, 4).forall { x => x > 1 }
python
all(x > 1 for x in [2,3,4])
cpp
template <typename InputIterator, typename Predicate>
bool match_all(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, !pred(_1)) == last;
}
fsharp
let rec IsAll predicate source =
let mutable acc = true
for e in source do
acc <- acc && (predicate e)
acc
erlang
Result = lists:all(Pred, List).
ocaml
(* from the interactive loop *)
# List.for_all (fun x -> x > 1) [2; 3; 4] ;;
- : bool = true
haskell

all (> 1) [2, 3, 4]
clojure
(every? #(> % 1) [2 3 4])
fantom
echo([2,3,4].all{ it>1 })

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
ruby
[2, 3, 4].any? { |x| x > 3 }
groovy
[2,3,4].any{it > 3}
scala
List(2, 3, 4).exists { _ > 3 }
List(2, 3, 4).exists { x => x > 3 }
python
any(x > 3 for x in [2, 3, 4])
cpp
template <typename InputIterator, typename Predicate>
bool match_any(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, pred) != last;
}
fsharp
let rec IsAny predicate source =
match source with
| [] -> false
| h::t ->
if (predicate h) then true
else (IsAny predicate t )
erlang
Result = lists:any(Pred, List).
ocaml
(* from the interactive loop: *)
# List.exists (fun x -> x > 3) [2; 3; 4] ;;
- : bool = true
haskell
any (> 1) [1, 2, 3]
clojure
; The standard library in Clojure has "not-any?" but (oddly enough) no "any?"
(defn any? [pred coll]
((complement not-any?) pred coll))

(any? #(> % 3) [2 3 4])
(some #(> % 3) [2 3 4])
fantom
echo([2,3,4].any{ it==4 })