1
\$\begingroup\$

Similar to the Catalogue of hello world. I want to produce a catalogue of short ways to produce CSV.

CSV Definition

In this case CSV meaning the more literal interpretation of; A string representation of a list or array separated by commas.

The input types should not be mixed i.e [1, "hello"] is NOT valid input

The output should not start with a comma or end with a comma. The output should not contain newline (in any way shape or form).

see example; "John,Henry,Carol,Carl"

Input

An array of variable length, containing only simple types. The array representation is how your chosen language defines arrays or lists.

Output

A string representation of the array separated with commas.

Example

Input: ["John", "Henry", "Carol", "Mike"]

Output: "John,Henry,Carol,Mike"

How do I win?

This is , so shortest answer (in bytes) in wins.

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 74557; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$

closed as unclear what you're asking by Mego, Toby Speight, TheNumberOne, Zach Gates, isaacg Apr 4 '16 at 13:28

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 7
    \$\begingroup\$ Many languages can't take an array as input (or in fact, have an array of any kind). How should these languages compete? In addition, several languages can take a CSV string as an array with no additional work. This seems underspecified, I'd recommend moving it to the sandbox. \$\endgroup\$ – FryAmTheEggman Mar 1 '16 at 21:08
  • 5
    \$\begingroup\$ This needs a full specification of what you consider to be CSV, because there are competing variants. \$\endgroup\$ – Peter Taylor Mar 1 '16 at 21:17
  • 4
    \$\begingroup\$ Changing the output format invalidates my answer. It's an easy fix, but this is why you need to post in the sandbox first. \$\endgroup\$ – Morgan Thrapp Mar 1 '16 at 21:25
  • 4
    \$\begingroup\$ I guess I didn't specify this enough in my last comment, but you also need to say whether or not something like [1, 2] would be acceptable. Several answers used the language's native string join, which in some cases won't work on "simple types", which is also pretty unclear for something like python, where all types are basically the same. \$\endgroup\$ – FryAmTheEggman Mar 1 '16 at 21:44
  • 6
    \$\begingroup\$ Congrats on making your first challenge! These things don't always go as planned; often what's clear in your head isn't perfectly clear to others. That's part of what makes creating a good challenge much harder than making a good answer. As has been mentioned, for this purpose we have the Sandbox, where challenge ideas can be posted for community feedback before going to the main site. I hope this experience hasn't discouraged you from challenge writing though. I guarantee it's better than purchasing WinRAR. \$\endgroup\$ – Alex A. Mar 2 '16 at 0:06

19 Answers 19

6
\$\begingroup\$

JavaScript (ES6), 7 bytes

a=>a+""

an array cast to a string has ,s implicitly inserted.

\$\endgroup\$
6
\$\begingroup\$

TeaScript, 0 bytes



An empty TeaScript program does this.

TeaScript implicitly adds the input to the operator stack.

The result of the operator stack is outputted. In this case it's the input, due to JavaScript's nature, when it's casted to a string, commas are added.

Try it online

\$\endgroup\$
  • \$\begingroup\$ What does this compile to? \$\endgroup\$ – CalculatorFeline Mar 6 '16 at 1:36
  • \$\begingroup\$ @CatsAreFluffy this simply compiles to x. Which is the variable containing the input \$\endgroup\$ – Downgoat Mar 6 '16 at 1:37
  • \$\begingroup\$ Well this was interesting while it lasted, I wonder how many other languages have the same behavior, also is the cs output due to the nature of the language or the compiler. \$\endgroup\$ – colsw Mar 2 '17 at 14:35
3
\$\begingroup\$

Python 3, 8 bytes

Saved 12 bytes thanks to DSM.

This isn't even close to a complete implementation of the CSV, but it satisfies the letter of what the challenge is looking for.

','.join
\$\endgroup\$
2
\$\begingroup\$

Haskell, 16 bytes

tail.((',':)=<<)

Usage example: tail.((',':)=<<) $ ["john", "henry", "carol", "Mike"] -> "john,henry,carol,Mike".

\$\endgroup\$
2
\$\begingroup\$

Pyth, 4 bytes

j\,Q

Evaluates input and joins by comma. Nothing much to say.

Try it online.

\$\endgroup\$
2
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 1 char / 2 bytes

ï

Try it here (Firefox only).

This one just outputs the input; however, with arrays, the brackets and quotes are discarded, leaving only the items and commas.

\$\endgroup\$
2
\$\begingroup\$

DUP, 29 bytes

[`$~][$'"=^'[=2ø']=||[][,]?]#

Try it here.

Takes input from STDIN as something like ["asdf","adsf","fdsa"] because DUP doesn't really have arrays that can hold strings.

Explanation

[   ][                     ]# {while loop}
 `$~                          {read an input char until end of input (-1)}
      $'"=^'[=2ø']=||         {check if input char is [,], or "}
                     [][ ]?   {conditional}
                        ,     {if not, output char}
\$\endgroup\$
  • \$\begingroup\$ Hooray for DUP! \$\endgroup\$ – cat Mar 6 '16 at 3:43
2
\$\begingroup\$

Python 2, 10 bytes (or may be 8, without assignment)

x=','.join

Test

>>> x(["John", "Henry", "Carol", "Mike"])
'John,Henry,Carol,Mike'
\$\endgroup\$
  • 1
    \$\begingroup\$ Generally it's acceptable to provide functions that are not assigned to variables. \$\endgroup\$ – CalculatorFeline Mar 6 '16 at 1:32
  • \$\begingroup\$ @CatsAreFluffy, I see, but somebody already posted same in python3, so, I will leave it like this. \$\endgroup\$ – YOU Mar 6 '16 at 4:57
1
\$\begingroup\$

PowerShell, 16 bytes

$args[0]-join','

Takes input, -joins 'em together. PowerShell supports mixed array types without anything special.

Example

PS C:\Tools\Scripts\golfing> .\csv-for-fun.ps1 ('Doorknob',33,'Martin','Peter')
Doorknob,33,Martin,Peter

Additionally

If you want an actual CSV output, PowerShell also has the excellent Export-CSV command. For example, ('Doorknob',33,'Martin','Peter')|epcsv -Path .\c.csv (with epcsv as an alias).

\$\endgroup\$
1
\$\begingroup\$

Jelly, 3 bytes

j”,

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Explanation: j join list ”, with separator "," \$\endgroup\$ – CalculatorFeline Mar 1 '16 at 21:44
  • \$\begingroup\$ That sums it up nicely. \$\endgroup\$ – Dennis Mar 1 '16 at 21:45
  • \$\begingroup\$ Even works for [1,2] \$\endgroup\$ – CalculatorFeline Mar 1 '16 at 21:45
1
\$\begingroup\$

POSIX sh, 15 bytes

IFS=,
echo "$*"

Example

# bash, dash, zsh, ksh, mksh... any basically POSIX-compatible shell.
dash -c 'IFS=,;echo "$*"' -- 'Foo B' ar baz
# -> Foo B,ar,baz

Explanation

$* is basically argv[1:].join(IFS[0]). Double-quoted to avoid further splitting and globbing, which in our case will give us back a b c. If you passed something like a b '*' in instead, you will find all your files listed due to the globbing.

The positional parameters, i.e. argv[1:], is the basic way to represent arrays in pure POSIX shell scripts. Functions are sometimes used to create new space for holding such parameter lists. You can only have one array working at a time using this technique.

\$\endgroup\$
1
\$\begingroup\$

Milky Way 1.6.5, 10 bytes

'C"'[]"-G!

Explanation

'C          ` push input to the stack as a list of characters
  "'[]"     ` push a string containing a single quote & square brackets
       -    ` remove the characters in the TOS from the STOS
        G!  ` output the remaining characters

Usage

$ ./mw <path-to-code> -i "['John','Phil','Dave','Matt H.','Matt D.']"
John,Phil,Dave,Matt H.,Matt D.

Input should be provided as the string of an array, containing no double quotes.

\$\endgroup\$
  • \$\begingroup\$ Ah, never mind. I missed the requirement for mandatory file extension. Works fine now. (Of course, excepting the weird “The output should not contain newline (in any way shape or form).” rule, which personally I find plain stupid.) \$\endgroup\$ – manatwork Mar 2 '16 at 14:28
1
\$\begingroup\$

Perl 6, 12 bytes

{.join: ','}

 

\$\endgroup\$
1
\$\begingroup\$

Dyalog APL, 11 bytes

1↓∊',',¨⍕¨⎕

Works even on numbers and mixed datatypes (remove ⍕¨ if unnecessary`). Takes list of strings as prompted input

prompt for and evaluate input
',',¨ prepend comma to each
flatten
1↓ remove initial comma

\$\endgroup\$
0
\$\begingroup\$

Retina, 3 bytes

¶
,

Try it online!

Takes newline-separated list. If this isn't valid, here's another 6-byte solution that takes a more... conventional... format.

["{}]
<empty>

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Lua, 42 Bytes

Simple use of the table.concat() function, limiting the type-mixing possibility to only numbers and strings.

function f(t)print(table.concat(t,","))end
\$\endgroup\$
0
\$\begingroup\$

Mathematica, 19 30 28 bytes

""<>Riffle[ToString/@#,","]&

#~StringRiffle~","& works if only strings will be input (which nobody actually knows)

\$\endgroup\$
0
\$\begingroup\$

PHP, 37 34 bytes

function i($a){echo join(",",$a);}

The vast majority of the size comes from setting the function. As a simple call it's just join(",",$a).

If we allow the array to come from the URL:

PHP, 24 21 bytes

echo join(",",$_GET);
\$\endgroup\$
0
\$\begingroup\$

Gogh, 1 byte

s

Usage:

$ ./gogh noa "s" 'John Mike Henry'

See the wiki to understand Gogh's array input.


Explanation

     “ Implicit input    ”
s    “ String conversion ”
     “ Implicit output   ”
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.