Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #360 Create a formatted list

Create the end-user text, s, specifying the contents of collection a.

For example, "A", "A and B", "A, B, and C", etc.

class ListFormatter(dict):
    def set(self, *i, left='', right=''):
        self[i] = left, right
    def format_list(self, array):
        a = list(map(str, array))
        for key, values in self.items():
            for i in key:
                a[i] = a[i].join(values)
        return ''.join(a)
x = ListFormatter()
match n := len(a):
    case 1: ...
    case 2: x.set(0, right=' and ')
    case _:
        x.set(*range(n - 1), right=', ')
        x.set(-1, left='and ')
s = x.format_list(a)
match len(a):
    case 1:
        s = a[0]
    case 2:
        s = ' and '.join(a)
    case _:
        s = ', '.join(a[:-1])
        s += ', and ' + a[-1]
#include <string>
int n {size(a)};
string s;
if (n == 1) s = a[0];
else if (n == 2)
    s = a[0] + " and "s + a[1];
else {
    int i {};
    s = a[i++];
    --n;
    while (i not_eq n)
        s += ", "s + a[i++];
    s += ", and "s + a[n];
}
import static java.lang.String.join;
import static java.util.Arrays.copyOfRange;
int n = a.length - 1;
String s = switch (n) {
    case 0 -> a[0];
    case 1 -> a[0] + " and " + a[1];
    default -> {
        s = join(", ", copyOfRange(a, 0, n));
        yield s + ", and " + a[n];
    }
};
import static java.text.MessageFormat.format;
String s = format("{0,list}", a);
sysutils
  if Length(a) > 1 then
  begin
    s := String.Join(', ', a, 0, Length(a)-1);
    s := s + ' and ' + a[High(a)]
  end
  else
  begin
    if Length(a) > 0 then
      s := a[0]
    else
      s :='';
  end;
remainder, last = a[..-2], a[-1]
s = remainder.join(", ") + "#{' and ' unless remainder.empty?}" + last.to_s

New implementation...
< >
reilas