View Problem
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(
Submit a new solution for php, clojure, or cpp
There are 21 other solutions in additional languages (csharp, erlang, fantom, fsharp ...)
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
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
// 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
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)))))))))
Submit a new solution for php, clojure, or cpp
There are 21 other solutions in additional languages (csharp, erlang, fantom, fsharp ...)




