CSV for fun and profit (mostly neither)

1

1

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>

Alex Carlsen

Posted 2016-03-01T21:03:23.900

Reputation: 387

Question was closed 2016-04-04T13:28:43.133

coming right up – Alex Carlsen – 2016-03-01T21:05:39.333

7Many 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. – FryAmTheEggman – 2016-03-01T21:08:09.313

5This needs a full specification of what you consider to be CSV, because there are competing variants. – Peter Taylor – 2016-03-01T21:17:18.393

Full spec coming up – Alex Carlsen – 2016-03-01T21:18:14.987

@nimi an uncaught mistake, and additional spacing has been defined – Alex Carlsen – 2016-03-01T21:23:35.573

4Changing the output format invalidates my answer. It's an easy fix, but this is why you need to post in the sandbox first. – Morgan Thrapp – 2016-03-01T21:25:06.350

I will fix the definition. – Alex Carlsen – 2016-03-01T21:26:28.903

So many downvotes - First Golf challenge for my part. And i'm already almost at the point where I would rather buy winrar, than try another golf lol – Alex Carlsen – 2016-03-01T21:31:30.487

1@VisualBean That's what the sandbox is for. There's a decent idea underneath the incomplete spec. The sandbox would've let you iron those problems out before posting it. – Morgan Thrapp – 2016-03-01T21:33:53.217

1This also needs a clarification for "containing only simple types". Would this mean a python answer would have to support: [1, "hello"]? – FryAmTheEggman – 2016-03-01T21:36:01.523

@MorganThrapp what is "The Sandbox" – Alex Carlsen – 2016-03-01T21:36:59.090

@VisualBean It's linked in the sidebar under "Featured on Meta" The Sandbox

– Morgan Thrapp – 2016-03-01T21:37:40.580

4I 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. – FryAmTheEggman – 2016-03-01T21:44:36.597

3Probably also need to address one-element input arrays, arrays where the strings contian newlines, arrays where the strings contain the comma character, arrays where the strings contian only whitespace, arrays where the strings contain unprintable, arrays where the string contains unicode, arrays where the strings contian rtl chars/combining chars/direction chars... And probably more... You can probably save a bunch of these by restricting input to printable ASCII? Still got some problems though... – FryAmTheEggman – 2016-03-01T21:53:26.373

Even if the spec was clarified. I'm down voting as too trivial. An empty program in TeaScript does this

– Downgoat – 2016-03-01T23:07:41.300

@Downgoat: all catalogue challenges so far are trivial. Many of them have 0 bytes solutions. – nimi – 2016-03-01T23:34:56.770

6

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.

– Alex A. – 2016-03-02T00:06:45.017

2Is there any reason for “The output should not contain newline (in any way shape or form).” other than unfairly prioritizing functions over full programs? – manatwork – 2016-03-02T08:49:35.720

I'm voting to close as unclear because "simple types" is not descriptive. – Mego – 2016-04-04T05:44:41.810

Answers

6

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

Downgoat

Posted 2016-03-01T21:03:23.900

Reputation: 27 116

What does this compile to? – CalculatorFeline – 2016-03-06T01:36:23.780

@CatsAreFluffy this simply compiles to x. Which is the variable containing the input – Downgoat – 2016-03-06T01:37:24.053

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. – colsw – 2017-03-02T14:35:21.543

6

JavaScript (ES6), 7 bytes

a=>a+""

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

Downgoat

Posted 2016-03-01T21:03:23.900

Reputation: 27 116

3

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

Morgan Thrapp

Posted 2016-03-01T21:03:23.900

Reputation: 3 574

2

Haskell, 16 bytes

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

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

nimi

Posted 2016-03-01T21:03:23.900

Reputation: 34 639

2

Pyth, 4 bytes

j\,Q

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

Try it online.

a spaghetto

Posted 2016-03-01T21:03:23.900

Reputation: 10 647

2

, 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.

Mama Fun Roll

Posted 2016-03-01T21:03:23.900

Reputation: 7 234

2

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}

Mama Fun Roll

Posted 2016-03-01T21:03:23.900

Reputation: 7 234

Hooray for DUP! – cat – 2016-03-06T03:43:53.050

2

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

x=','.join

Test

>>> x(["John", "Henry", "Carol", "Mike"])
'John,Henry,Carol,Mike'

YOU

Posted 2016-03-01T21:03:23.900

Reputation: 4 321

1Generally it's acceptable to provide functions that are not assigned to variables. – CalculatorFeline – 2016-03-06T01:32:09.713

@CatsAreFluffy, I see, but somebody already posted same in python3, so, I will leave it like this. – YOU – 2016-03-06T04:57:23.337

1

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).

AdmBorkBork

Posted 2016-03-01T21:03:23.900

Reputation: 41 581

1

Jelly, 3 bytes

j”,

Try it online!

Dennis

Posted 2016-03-01T21:03:23.900

Reputation: 196 637

Explanation: j join list ”, with separator "," – CalculatorFeline – 2016-03-01T21:44:26.637

That sums it up nicely. – Dennis – 2016-03-01T21:45:01.223

Even works for [1,2] – CalculatorFeline – 2016-03-01T21:45:54.480

1

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.

Arthur2e5

Posted 2016-03-01T21:03:23.900

Reputation: 143

1

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.

Zach Gates

Posted 2016-03-01T21:03:23.900

Reputation: 6 152

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.) – manatwork – 2016-03-02T14:28:34.213

1

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

Adám

Posted 2016-03-01T21:03:23.900

Reputation: 37 779

1

Perl 6, 12 bytes

{.join: ','}

 

Hotkeys

Posted 2016-03-01T21:03:23.900

Reputation: 1 015

0

Mathematica, 19 30 28 bytes

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

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

CalculatorFeline

Posted 2016-03-01T21:03:23.900

Reputation: 2 608

0

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!

Mama Fun Roll

Posted 2016-03-01T21:03:23.900

Reputation: 7 234

0

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

Katenkyo

Posted 2016-03-01T21:03:23.900

Reputation: 2 857

0

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);

ricdesi

Posted 2016-03-01T21:03:23.900

Reputation: 499

0

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   ”

Zach Gates

Posted 2016-03-01T21:03:23.900

Reputation: 6 152