View Subcategory
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
php
$list = array("One", "Two", "Three", "Four", "Five");
$three = $list[2];
$three = $list[2];
clojure
(nth '[One Two Three Four Five] 2)
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
php
$list = array("Red", "Green", "Blue");
$last = array_pop($list);
// Be aware of that $list only contains two elements now - not three
$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];
$last = $list[count($list)-1];
clojure
(last '[One Two Three Four Five])
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?
php
$result = array_intersect($beans, $colors);
sort($result); // just to clean it up :)
sort($result); // just to clean it up :)
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)))
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.
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
$ages = array_unique($ages);
// be aware of that $ages[6] will print 14
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)
