View Category
Define an empty list
Assign the variable
"list" to a list with no elements
ruby
list = []
list = Array.new
erlang
List = [],
clojure
(list)
'()
go
var l []string;
fantom
list := [,]
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)
erlang
List = [one, two, three, four, five],
List = ['One', 'Two', 'Three', 'Four', 'Five'],
clojure
(def a '[One Two Three Four Five])
go
var l = []string{"One", "Two", "Three", "Four", "Five"}
fantom
list := ["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(', ')
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)]]).
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
go
s := strings.Join([]string {"Apple", "Banana", "Carrot"}, ", ")
fantom
["Apple", "Banana", "Carrot"].join(", ")
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(
[]) = ""
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
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
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).
% ------
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)].
%% 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)].
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)))))))))
(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)))))
([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)))))
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([,]))
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]}}
erlang
Combinations =
lists:foldl(fun (Number, Acc) -> Acc ++ lists:map(fun (Letter) -> {Letter, Number} end, Letters) end, [], Numbers),
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]].
clojure
(defn combine [lst1 lst2]
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) ["a", "b", "c"])) [4, 5])
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:
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"]
ruby
foo = ['andrew', 'bob', 'chris', 'bob']
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
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(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).
([X | Xs], F) -> case lists:member(X, Xs) of
true -> [X | F(Xs, F)];
_ -> F(Xs, F)
end;
([], _) -> []
end,
Result = Fun(List, Fun).
clojure
(->> '("andrew" "bob" "chris" "bob")
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
(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(","))
["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]
list[2]
['One', 'Two', 'Three', 'Four', 'Five'].fetch(2)
list = ['One', 'Two', 'Three', 'Four', 'Five']
list.at(2)
list.at(2)
['One', 'Two', 'Three', 'Four', 'Five'][2] # <= note the [2] at end of array
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),
clojure
(nth '[One Two Three Four Five] 2)
go
fmt.Println(list[2])
fantom
["One", "Two", "Three", "Four", "Five"][2]
["One", "Two", "Three", "Four", "Five"].get(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)
erlang
Result = lists:last(List),
Result = last(List),
Result = hd(lists:reverse(List)),
Result = lists:nth(length(List), List),
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
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)),
Common = sets:to_list(sets:intersection(Beans, Colors)),
clojure
(use 'clojure.set)
(let [beans '[broad mung black red white]
colors '[black red blue green]]
(intersection (set beans) (set colors)))
(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))
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
p ages.uniq
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
ages.uniq!
p ages
ages.uniq!
p ages
ages = (Set.new [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).to_a
p ages
p ages
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]).
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)
(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)
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)
erlang
Result = tl(List),
[_|Result] = List,
N = 1, {Left, Right} = lists:split(N - 1, List), Result = Left ++ tl(Right),
Result = drop(1, List),
clojure
(let [fruit ["Apple" "Banana" "Carrot"]
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
go
offset := 0
list = append(list[:offset], list[offset+1:]...)
list = append(list[:offset], list[offset+1:]...)
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(0)
list.removeAt(0)
Remove the last element of a list
ruby
list = ['Apple', 'Banana', 'Carrot']
list.delete_at(-1)
list.delete_at(-1)
list = ['Apple', 'Banana', 'Carrot']
list.pop
list.pop
erlang
Result = init(List),
Result = take(length(List) - 1, List),
Result = lists:reverse(tl(lists:reverse(List))),
clojure
(pop ["Apple" "Banana" "Carrot"])
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(-1)
list.removeAt(-1)
list := ["Apple", "Banana", "Carrot"]ยจ
list.pop
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
items << first = items.shift
# items is rotated
# first contains the first value in the list
erlang
N = 1, {Left, Right} = lists:split(N, List), Result = Right ++ Left,
N = 1, Result = rotate(N, List),
clojure
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
(concat (rest fruit) [(first fruit)])
fantom
list := ["apple", "orange", "grapes", "bananas"]
list.add(list.removeAt(0))
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)
result = first.zip(last, years)
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]
result = [first, last, years].transpose
result = [first, last, years].transpose
erlang
First = ['Bruce', 'Tommy Lee', 'Bruce'], Last = ['Willis', 'Jones', 'Lee'], Years = [1955, 1946, 1940],
Result = lists:zip3(First, Last, Years),
Result = lists: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))
(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))
(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)
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
puts "Deck %s \'Ace of Hearts\'" % if cards.include?(['h', 'A']) then "contains" else "does not contain" end
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]),
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]),
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).
52 = length(Deck2),
true = lists:member({h, 'A'}, Deck2).
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
(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")
["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
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]
ruby
["ox", "cat", "deer", "whale"].map{|i| i.length}
erlang
lists:map(fun (X) ->length(X) end, List).
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.
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
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}
things=["hello", 25, 3.14, now]
numbers, others=things.partition{|i| i.is_a? Numeric}
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.
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)
{Numbers, NonNumbers} = lists:partition(fun(E) -> is_number(E) end, List)
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)}
(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) }
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 }
erlang
Result = lists:all(Pred, List).
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 }
erlang
Result = lists:any(Pred, List).
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])
(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 })
