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([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
DiskEdit
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)))))))))
DiskEdit
clojure
(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)))))
ExpandDiskEdit
cpp C++/CLI .NET 2.0
Console::WriteLine(join(fruit));
ExpandDiskEdit
cpp
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);
}
}
DiskEdit
csharp .NET 3.5
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>()) );
}
}
ExpandDiskEdit
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).
DiskEdit
erlang
%% 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)].

ExpandDiskEdit
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([,]))
ExpandDiskEdit
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)
ExpandDiskEdit
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]
}
}
DiskEdit
groovy 1.7.x
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() == ""
DiskEdit
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
ExpandDiskEdit
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();
}
ExpandDiskEdit
java 1.5 or later
System.out.println(join(fruit));
DiskEdit
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 ""
DiskEdit
perl
sub myjoin {
$_ = join ', ', @_;
s/, ([^,]+)$/ and $1/;
return $_;
}


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

# Note: I don't think this meets the spec --Geoff
DiskEdit
perl
# 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];
}
}
DiskEdit
perl
# 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);
}
DiskEdit
perl
# 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];
}
ExpandDiskEdit
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
DiskEdit
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(*[]) == ""
ExpandDiskEdit
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
ExpandDiskEdit
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)
}
ExpandDiskEdit
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 x::xs => x + ", " + join(xs)
}
ExpandDiskEdit
scala
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
}

Submit a new solution for clojure, cpp, csharp, erlang ...