Logo

Programming-Idioms

History of Idiom 53 > diff from v18 to v19

Edit summary for version 19 by :

Version 18

2015-09-09, 08:50:05

Version 19

2015-10-29, 14:05:14

Idiom #53 Join a list of strings

Concatenate elements of string list x joined by the separator ", " to create a single string y.

Idiom #53 Join a list of strings

Concatenate elements of string list x joined by the separator ", " to create a single string y.

Imports
import qualified Data.Text as T
Imports
import qualified Data.Text as T
Code
{-# LANGUAGE OverloadedStrings #-}
y :: T.Text
y = T.intercalate ", " x
Code
{-# LANGUAGE OverloadedStrings #-}
y :: T.Text
y = T.intercalate ", " x
Comments bubble
The first line allows the string literal ", " to be a type other then type String. In this case it is automatically converted to type Text.
This version uses Text as a common replacement for the built-in String type.

The type annotation on the second line is optional and can be omitted.
Comments bubble
The first line allows the string literal ", " to be a type other then type String. In this case it is automatically converted to type Text.
This version uses Text as a common replacement for the built-in String type.

The type annotation on the second line is optional and can be omitted.
Code
var
  _x: Array of string;
  _y: String;
  i: Integer;
begin
  _y := ''; //initialize result to an empy string
  // assume _x is initialized to contain some values
  for i := Low(_x) to High(_x) do
  begin
    _y := _y + _x[i];
    if i < High(_x) then _y := _y + ';';
  end;
end;
Code
var
  _x: Array of string;
  _y: String;
  i: Integer;
begin
  _y := ''; //initialize result to an empy string
  // assume _x is initialized to contain some values
  for i := Low(_x) to High(_x) do
  begin
    _y := _y + _x[i];
    if i < High(_x) then _y := _y + ';';
  end;
end;
Code
let y = x.connect(", ");
Code
let y = x.connect(", ");
Comments bubble
Note that connect() has been renamed to join() .
Comments bubble
Note that connect() has been renamed to join() .
Demo URL
http://is.gd/8wi2NW
Demo URL
http://is.gd/8wi2NW
Code
$y = implode(", ", $x);
Code
$y = implode(", ", $x);
Doc URL
http://php.net/manual/en/function.implode.php
Doc URL
http://php.net/manual/en/function.implode.php
Code
y = ", ".join(x)
Code
y = ", ".join(x)
Comments bubble
This works only if x contains only strings.
Comments bubble
This works only if x contains only strings.
Doc URL
https://docs.python.org/3/library/stdtypes.html#str.join
Doc URL
https://docs.python.org/3/library/stdtypes.html#str.join
Imports
import "strings"
Imports
import "strings"
Code
y := strings.Join(x, ", ")
Code
y := strings.Join(x, ", ")
Comments bubble
This works only if x has type []string.
Comments bubble
This works only if x has type []string.
Doc URL
http://golang.org/pkg/strings/#Join
Doc URL
http://golang.org/pkg/strings/#Join