View Category
Define an empty list
Assign the variable
"list" to a list with no elements
python
list = []
fsharp
let list = []
let list = List.empty
let list = new Generic.List<string>()
let list = new Generic.LinkedList<string>()
fantom
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
list = new LinkedList() // java style
LinkedList list = [] // statically typed
// using 'as' operator
list = [] as java.util.concurrent.CopyOnWriteArrayList
Define a static list
Define the list
[One, Two, Three, Four, Five]
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
print list
print list
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")
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))
[|"One"; "Two"; "Three"; "Four"; "Five"|] |> Array.iter (fun x -> list.Add(x))
fantom
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+
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+
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
python
print ", ".join(['Apple', 'Banana', 'Carrot'])
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()
fantom
["Apple", "Banana", "Carrot"].join(", ")
groovy
string = fruit.join(', ')
string = fruit.toString()[1..-2]
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(
join(
join(
join(
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
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(*[]) == ""
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(*[]) == ""
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)
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)
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([,]))
{
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([,]))
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]
}
}
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 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() == ""
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]]
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])]
[x for x in itertools.product(["a", "b", "c"], [4, 5])]
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
aa
|> List.map (fun a -> bb |> List.map (fun b -> (a, b)))
|> List.concat
fantom
[4,5].each |Int i| { ["a","b","c"].each |Str s| { r.add([i,s]) } }
groovy
letters = ['a', 'b', 'c']
numbers = [4, 5]
combos = [letters, numbers].combinations()
numbers = [4, 5]
combos = [letters, numbers].combinations()
From a List Produce a List of Duplicate Entries
Taking a list:
Write the code to produce a list of duplicates in the list:
["andrew", "bob", "chris", "bob"]
Write the code to produce a list of duplicates in the list:
["bob"]
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]
input = ["andrew", "bob", "chris", "bob"]
input.sort()
output = [k for k, g in itertools.groupby(input, lambda x: x) if len(list(g)) > 1]
fsharp
["andrew"; "bob"; "chris"; "bob"]
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
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(","))
["andrew", "bob", "chris", "bob"].each |Str v| { nameCounts[v]++ }
results := nameCounts.findAll |Int v, Str k->Bool| { v > 1 }.keys
echo(results.join(","))
groovy
def input = ["andrew", "bob", "chris", "bob"]
def output = input.findAll{input.count(it)>1}.unique()
assert output == ["bob"]
def output = input.findAll{input.count(it)>1}.unique()
assert output == ["bob"]
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
list[2]
fsharp
let result = List.nth ["One"; "Two"; "Three"; "Four"; "Five"] 2
fantom
["One", "Two", "Three", "Four", "Five"][2]
["One", "Two", "Three", "Four", "Five"].get(2)
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
result = list[2] // index starts at 0
result = list[2] // index starts at 0
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
python
list = ['Red', 'Green', 'Blue']
list[-1]
list[-1]
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 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))
fantom
["Red", "Green", "Blue"][-1]
["One", "Two", "Three", "Four", "Five"].last
groovy
list = ['Red', 'Green', 'Blue']
result = list[-1]
result = list[-1]
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?
python
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = [b for b in beans if b in colors]
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)
colors = ['black', 'red', 'blue', 'green']
common = set(beans) & set(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 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
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)) ;;
// 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)) ;;
fantom
beans := ["broad", "mung", "black", "red", "white"]
colors := ["black", "red", "blue", "green"]
echo(beans.intersection(colors))
colors := ["black", "red", "blue", "green"]
echo(beans.intersection(colors))
groovy
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = beans.intersect(colors)
assert common == ['black', 'red']
colors = ['black', 'red', 'blue', 'green']
common = beans.intersect(colors)
assert common == ['black', 'red']
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.
python
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique_ages = list(set(ages))
unique_ages = list(set(ages))
fsharp
(Set.ofList [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]) |> Set.iter (fun age -> printf "%d, " age)
fantom
uniqueAges := [18, 16, 17, 18, 16, 19, 14, 17, 19, 18].unique
echo(uniqueAges)
echo(uniqueAges)
groovy
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
println ages.unique()
println ages.unique()
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique = ages as Set
println unique
unique = ages as Set
println unique
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
python
myList = ['Apple', 'Banana', 'Carrot']
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
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 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)
if n <= 0 then
list
else
let (_, right) = split_at list (n - 1)
right
// ------
let result = (drop fruit 1)
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(0)
list.removeAt(0)
groovy
// to produce a new list
newlist = list.tail() // for 'Apple' at start
newlist = list - 'Apple' // for 'Apple' anywhere
newlist = list.tail() // for 'Apple' at start
newlist = list - 'Apple' // for 'Apple' anywhere
// mutate original list
list.remove(0)
list.remove(0)
Remove the last element of a list
python
myList = ['Apple', 'Banana', 'Carrot']
myList.pop()
myList.pop()
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))
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)
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)
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(-1)
list.removeAt(-1)
list := ["Apple", "Banana", "Carrot"]ยจ
list.pop
list.pop
groovy
list = ['Apple', 'Banana', 'Carrot']
// to produce a new list
newlist = list[0,1]
// to modify original list
list.remove(2)
// to produce a new list
newlist = list[0,1]
// to modify original list
list.remove(2)
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"]
python
l = ["apple", "orange", "grapes", "bananas"]
first, l = l[0], l[1:] + l[:1]
first, l = l[0], l[1:] + l[:1]
fruit = ['apple', 'orange', 'grapes', 'bananas']
fruit.append(fruit.pop(0))
fruit.append(fruit.pop(0))
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)
if n <= 0 then
list
else
let (left, right) = split_at list (n - 1)
right @ left
// ------
let result = (rotate fruit 1)
fantom
list := ["apple", "orange", "grapes", "bananas"]
list.add(list.removeAt(0))
list.add(list.removeAt(0))
groovy
first = items.head()
items = items.tail() + first
items = items.tail() + first
items = items[1..-1] + items[0]
items = items + items.remove(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.
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)
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = zip(first, last, years)
assert len(actors) == 3
assert actors[1] == ('Tommy Lee', 'Jones', 1946)
fsharp
let result = (List.zip3 first last years)
fantom
r := [,]
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }
echo(r)
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }
echo(r)
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]
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = [first, last, years].transpose()
assert actors.size() == 3
assert actors[1] == ['Tommy Lee', 'Jones', 1946]
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'.
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
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
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")
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 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"
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"
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")
["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")
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
suites = ['H', 'D', 'C', 'S']
deck = [faces, suites].combinations()
assert deck.size() == 52
assert ['A', 'H'] in deck
Perform an operation on every item of a list
Perform an operation on every item of a list, e.g.
for the list
the list of sizes of the strings, e.g.
for the list
["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g.
[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']]
fsharp
let lengths = List.map String.length ["ox"; "cat"; "deer"; "whale"]
fantom
["ox", "cat", "deer", "whale"].map { it.size }
groovy
animals = ["ox", "cat", "deer", "whale"]
assert animals*.size() == [2, 3, 4, 5]
assert animals*.size() == [2, 3, 4, 5]
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.
split the list into numbers and non-numbers.
python
import re
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)
nonDigits = re.findall(re.compile('\D'), data)
digits = re.findall(re.compile('\d'), data)
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)
nonDigits = re.findall(re.compile('\D'), data)
digits = re.findall(re.compile('\d'), data)
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
let isNumber (x:obj) =
match x with
| :? int | :? float | :? byte | :? decimal | :? int16 | :? int64 -> true
| _ -> false
let numbers, nonNumbers = things |> List.partition isNumber
fantom
things := ["hello", 25, 3.14, Time.now]
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }
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]
things = ["hello", 25, 3.14, now]
(numbers, others) = things.split{ it instanceof Number }
assert numbers == [25, 3.14]
assert others == ["hello", now]
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.
python
all(x > 1 for x in [2,3,4])
fsharp
let rec IsAll predicate source =
let mutable acc = true
for e in source do
acc <- acc && (predicate e)
acc
let mutable acc = true
for e in source do
acc <- acc && (predicate e)
acc
fantom
echo([2,3,4].all{ it>1 })
groovy
[2,3,4].every{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.
python
any(x > 3 for x in [2, 3, 4])
fsharp
let rec IsAny predicate source =
match source with
| [] -> false
| h::t ->
if (predicate h) then true
else (IsAny predicate t )
match source with
| [] -> false
| h::t ->
if (predicate h) then true
else (IsAny predicate t )
fantom
echo([2,3,4].any{ it==4 })
groovy
[2,3,4].any{it > 3}
