Sugar Free Syntax

55

6

In Haskell the list notation:

[a,b,c]

Is just syntactic sugar for:

a:b:c:[]

And the string notation:

"abc"

Is just syntactic sugar for:

['a','b','c']

This means that the string:

"abc"

Is the same as:

'a':'b':'c':[]

Task

Given a string you should output what the de-syntaxed version would look like in Haskell.

Rules

  • You will receive a string by any valid input method, you should output a string ending with :[] with every character from the input surrounded by ' and separated by :. The empty string should output [].

  • You can assume that you will not receive any characters that require escaping (e.g. ', newlines, tabs ...) and that input will be in the printable ascii range

  • This is you should aim to minimize the byte count of your answer

Test Cases

"" -> []
"a" -> 'a':[]
"Hello, World" -> 'H':'e':'l':'l':'o':',':' ':'W':'o':'r':'l':'d':[]   

Post Rock Garf Hunter

Posted 2017-06-14T18:54:35.557

Reputation: 55 382

Will the input ever have non-ascii values? Your restriction on characters that require escaping either requires we know which characters Haskell will escape or assumes your list is exhaustive. – FryAmTheEggman – 2017-06-14T19:05:15.457

@FryAmTheEggman You can assume they are in the ascii range – Post Rock Garf Hunter – 2017-06-14T19:06:42.527

Does the string come in surrounded by "? Or is that just to signify that it's a string? – nmjcman101 – 2017-06-14T19:08:44.557

@nmjcman101 Just there to indicate its a string (hard to represent the empty string otherwise). – Post Rock Garf Hunter – 2017-06-14T19:09:33.520

Is 'a':'':[] an acceptable output for a and '':[] an acceptable output for an empty string? – totallyhuman – 2017-06-14T20:40:53.213

7@totallyhuman Those are not even valid Haskell. If they were maybe, but nice they are not, definitely no. – Post Rock Garf Hunter – 2017-06-14T20:43:26.590

printable ascii? – Titus – 2017-06-15T03:51:02.413

@Titus Yes, I'm pretty sure all of the unprintable ascii needs to be escaped. Anything that has to be escaped in Haskell doesn't need to be suported. – Post Rock Garf Hunter – 2017-06-15T03:54:07.823

You should probably specify (printable) ASCII explicitly in the question, as there are a lot of higher Unicode characters that don't need escaping. The rules are somewhat weird and based on Unicode character classes. (The exceptions are just enough spread around to make compression with string literals awkward.) – Ørjan Johansen – 2017-06-15T04:09:22.610

38This question can be alternatively titled "Diet Haskell". – March Ho – 2017-06-15T14:42:34.607

May we use " instead of ' (e.g. "a" -> "a":[])? – caird coinheringaahing – 2018-04-09T17:31:52.383

1@cairdcoinheringaahing No, " and ' are syntactically different. – Post Rock Garf Hunter – 2018-04-09T17:32:43.363

Answers

85

Haskell, 26 bytes

(++"[]").((++":").show=<<)

Try it online!

Explanation:

In non-pointfree notation and using concatMap instead of =<<, this becomes

f s = concatMap(\c-> show c ++ ":")s ++ "[]"

Given a string s, we map each char c to a string "'c':" using the show function which returns a string representation of most Haskell types. Those strings are concatenated and a final [] is appended.

Although not requested by the challenge, this answer even works with proper escaping, because show takes care of it: f "'" yields "'\\'':[]".

Laikoni

Posted 2017-06-14T18:54:35.557

Reputation: 23 676

25Wait a minute, you mean (++'[':']':[]).((++':':[]).show=<<), no? – Adám – 2017-06-14T19:27:07.960

11When any challenge has a Haskell answer, I upvote it out of principle. That goes double for this one. – Ryan Reich – 2017-06-15T05:39:54.003

43

Haskell, 33 28 26 bytes

foldr((.(':':)).shows)"[]"

Try it online!

fold the given pointfree function from the right into the input string starting with []. The function is: show char as a Haskell char, i.e. surrounded with ' and concatenate with the result so far after putting a : in front of it.

Edit: @Ørjan Johansen saved two bytes. Thanks!

nimi

Posted 2017-06-14T18:54:35.557

Reputation: 34 639

I suppose that means (++'[':']':[]).(>>= \c->'\'':[]++[c]++'\'':':':[]). – Adám – 2017-06-14T19:31:23.190

1I think this is superior to the other Haskell answer (at the same byte count) due to using : to build the list rather than ++, though both have their own elegance. – CAD97 – 2017-06-16T10:04:46.827

4This is rather amazing. Two separate approaches that have the same byte count in the same language. – J Atkin – 2017-06-17T19:52:16.420

19

Python 3, 32 bytes

lambda s:"%r:"*len(s)%(*s,)+"[]"

Try it online!

xnor

Posted 2017-06-14T18:54:35.557

Reputation: 115 687

17

JavaScript ES6, 42 40 31 bytes

s=>s.replace(/./g,"'$&':")+"[]"

Replaces each char with '<char>':, then adds [] to the end

Try it online!

Downgoat

Posted 2017-06-14T18:54:35.557

Reputation: 27 116

1I love this about CodeGolf. Never knew about $&. – Steve Bennett – 2017-06-18T07:42:50.240

16

Common Lisp, 50 42 bytes

(format t"~{'~a':~}[]"(coerce(read)'list))

Try it online!

Reduced thanks to the comment of @coredump, by using read instead of defining a function.

Renzo

Posted 2017-06-14T18:54:35.557

Reputation: 2 260

1Welcome to PPCG! – Martin Ender – 2017-06-15T08:53:07.363

2Lisp! Welcome indeed :) – Olivier Dulac – 2017-06-15T13:47:29.040

@Renzo Hi Renzo, you could shrink it a little by using an anonymous lambda form, or simply calling read : (format t"~{'~a':~}[]"(coerce(read)'list)) (some other questions are stricter w.r.t. inputs and outputs, but here this is fine) – coredump – 2017-06-18T13:04:30.097

@coredump, thanks!, I've updated the code. – Renzo – 2017-06-18T13:08:29.573

11

V, 11 bytes

Í./'&':
A[]

Try it online!

Uses a regex to surround every input character with '': and then Appends [] to the end.

nmjcman101

Posted 2017-06-14T18:54:35.557

Reputation: 3 274

10

C, 55 54 53 bytes

s(char*h){while(*h)printf("'%c':",*h++);puts("[]");}

Govind Parmar

Posted 2017-06-14T18:54:35.557

Reputation: 828

1you can remove the space in char *h – Cyoce – 2017-06-14T19:24:59.630

1You can do puts("[]"); instead to output with a trailing newline to save some bytes. – user41805 – 2017-06-14T19:29:41.557

recursive s(char*h){*h?printf("'%c':",*h++),s(h):puts("[]");} – l4m2 – 2018-04-09T02:59:01.377

8

05AB1E, 15 12 11 10 bytes

-3 bytes thanks to carusocomputing
-1 byte thanks to Adnan
-1 byte thanks to Erik the Outgolfer's genius idea

ʒ"'ÿ':"?},

Try it online!

ʒ          # Filter out every character that the following code doesn't return 1 for
 "'ÿ':"?   #   Print the string 'ÿ': with ÿ replaced by this character
        }  # End for
         , # No character returned 1 so an empty array is left on the stack. Print that

Riley

Posted 2017-06-14T18:54:35.557

Reputation: 11 345

Apparently I beat you by 4 seconds ;-) – Digital Trauma – 2017-06-14T19:01:06.257

1@DigitalTrauma Yours popped up as I was pressing Post Your Answer. – Riley – 2017-06-14T19:02:07.900

1You can print the global array instead of pushing the brackets with 3 bytes. You can also interpolate the string for another byte savings for a total of -3, final result 12-bytes: vy"'ÿ':"?}¯? – Magic Octopus Urn – 2017-06-14T19:43:34.237

@carusocomputing I use the string interpolator all the time for test suites, but forget to use it in actual code. Thanks! – Riley – 2017-06-14T19:51:33.277

@carusocomputing I thought vy"'ÿ':"}¯J would work for 11, but J joins the global array, not the whole stack in that situation. – Riley – 2017-06-14T19:57:44.120

8

Pyth, 14 10 8 bytes

j\:a`MQY

Try this!

-2 bytes thanks to @isaacg

Finally, pyth is good at something.

explanation

j\:a`MQY
    `MQ        # map the representation over the input string: ["'a'","'b'",...]
   a   Y       # append the empty list
j\:            # join on :

KarlKastor

Posted 2017-06-14T18:54:35.557

Reputation: 2 352

@isaacg Thank you! I forgot about M and I don't know why I didn't use a. Now we're at least 2 bytes shorter than all the other solutions here! – KarlKastor – 2017-06-16T08:20:52.250

8

Python 3, 41 38 36 bytes

-2 bytes thanks to ovs

print(*map(repr,input()),[],sep=':')

Try it online!

Rod

Posted 2017-06-14T18:54:35.557

Reputation: 17 588

Whoops... Forgot that *map exists... – Mr. Xcoder – 2017-06-14T19:25:15.290

I was puzzled by the empty input() for the past 20 minutes (literally), when it could just be a lambda @.@ – Rod – 2017-06-14T19:26:05.430

Empty input does work? – Post Rock Garf Hunter – 2017-06-14T19:38:25.123

@WheatWizard oh, I was using a empty-empty (no newline) input – Rod – 2017-06-14T19:40:35.953

You can replace "[]" with [] – ovs – 2017-06-14T21:08:22.613

8

R, 51 bytes

f<-function(x)(paste0(gsub("(.)","'\\1':",x),'[]'))

t c

Posted 2017-06-14T18:54:35.557

Reputation: 81

1

Nice solution! A few ways you can save some bytes and really get this down. default I/O lets you just return an anonymous function, or even take input from stdin, the latter of which would be much shorter using scan(,'') instead of a function.

– Giuseppe – 2017-06-16T14:38:11.063

Thanks, am a bit of a newb with R (and code golf!) so haven't quite grasped anonymous functions in it yet, although I was trying to do it without 'function' in there. scan could be useful! – t c – 2017-06-16T15:37:57.077

ah, well an anonymous function is just one where you don't assign it to a variable so you'd just drop the f<- from the beginning of your code – Giuseppe – 2017-06-16T15:39:24.327

paste0(gsub('(.)',"'\1':",scan(,"")),'[]') is 43 – Zahiro Mor – 2017-06-18T08:45:14.640

7

Retina, 12

  • 3 bytes saved thanks to @FryAmTheEggman
.
'$&':
$
[]

2 stages:

  • for each remaining character put ' ': around it
  • add [] to the end

Try it online.

Digital Trauma

Posted 2017-06-14T18:54:35.557

Reputation: 64 644

Helped the guy you beat by 4 seconds tie you ;). – Magic Octopus Urn – 2017-06-14T19:45:10.000

I was thinking of this! – CalculatorFeline – 2017-06-18T16:43:08.700

7

Perl 6, 19 bytes

{S:g|.|'$/':|~'[]'}

Sean

Posted 2017-06-14T18:54:35.557

Reputation: 4 136

6

Python 2, 48 46 44 37 bytes

-2 bytes thanks to Rod. -7 bytes thanks to Wheat Wizard.

lambda s:':'.join(map(repr,s)+['[]'])

Try it online!

totallyhuman

Posted 2017-06-14T18:54:35.557

Reputation: 15 378

1Slightly shorter – Post Rock Garf Hunter – 2017-06-14T19:19:57.977

Oh, neat. Thanks! – totallyhuman – 2017-06-14T19:36:39.770

1One shorter as lambda s:':'.join(map(repr,[*s,[]])) or lambda s:':'.join(map(repr,s))+":[]". – xnor – 2017-06-14T19:52:37.353

@xnor The second example you give doesn't seem to work for the empty case. (the original answer looked very similar to that but paid a lot to cover the empty string case) – Post Rock Garf Hunter – 2017-06-15T03:28:30.703

6

JavaScript (ES6), 36 bytes

s=>s?`'${[...s].join`':'`}':[]`:"[]"

Try it

f=
s=>s?`'${[...s].join`':'`}':[]`:"[]"
oninput=_=>o.innerText=f(i.value);o.innerText=f(i.value="abc")
<input id=i><pre id=o>

Shaggy

Posted 2017-06-14T18:54:35.557

Reputation: 24 623

6

Befunge, 29 27 bytes

<,,,,\_v#`0:~"'':"
@,,"[]"<

Try it online!

user55852

Posted 2017-06-14T18:54:35.557

Reputation:

5

Jelly,  11 10  8 bytes

-1 byte thanks to Christian (remove concatenation ; and utilise implicit printing instead)

+0 bytes (fixed for edge case of an empty string - previously the full program: ŒṘ€j”:“:[])

-2 thanks to Erik the Outgolfer (use p in place of ;€ since ”: is effectively length 1; use Ø[ since it has become shorthand for ⁾[])

ŒṘ€p”:Ø[

Try it online!

A full program printing the result (as a link it returns a list of lists of characters).

...but is there a way to save using STDIN?

How?

ŒṘ€p”:Ø[ - Main link: list of characters, s  e.g. "Hey"
ŒṘ€      - Python representation for €ach    [["'",'H',"'"],["'",'e',"'"],["'",'y',"'"]]
    ”:   - literal character = ':'
   p     - Cartesian product                 [["'",'H',"'",':'],["'",'e',"'",':'],["'",'y',"'",':']]
         - implicit print (no newline): 'H':'e':'y':
      Ø[ - literal list of characters        ['[',']']
         - implicit print (no newline): []

Jonathan Allan

Posted 2017-06-14T18:54:35.557

Reputation: 67 804

4

PHP, 41 bytes

<?=preg_filter("#.#","'$0':",$argn)."[]";

Try it online!

Jörg Hülsermann

Posted 2017-06-14T18:54:35.557

Reputation: 13 026

4 bytes shorter: for(;~$c=$argn[$i++];)echo"'$c':"?>[]. – user63956 – 2017-06-15T01:31:37.137

@user63956 need it not a additional <? with which option must it be run? Make an own approach I would say to get upvotes and titus have done something similar in the meantime – Jörg Hülsermann – 2017-06-15T10:41:58.260

It works with the -R flag. Tags can be closed even in constructions like eval() and create_function(). – user63956 – 2017-06-15T12:05:10.080

4

Perl 5, 22 bytes

19 bytes of code + -p flag.

s/./'$&':/g;$\="[]"

Or, for the same bytecount, s/./'$&':/g;s/$/[]/.

Quite straight forward: s/./'$&':/g surrounds each characters with quotes and add a : after. $\ is implicitly printed after each print, so setting it to [] outputs the final [].

Try it online!

Dada

Posted 2017-06-14T18:54:35.557

Reputation: 8 279

4

brainfuck, 68 bytes

+[-->+[<]>-]>>,[<.>.<.>>-[>+<+++++++++]>+.[-]<<,]-[+[+<]>>+]<+++.++.

Try it online!

daniero

Posted 2017-06-14T18:54:35.557

Reputation: 17 193

Doesn't quite work with the empty string - returned me two non-valid characters in your online test. Very nice, otherwise. – NoseKnowsAll – 2017-06-15T17:57:01.800

@NoseKnowsAll I can't seem to replicate that; With no input I get no output. Could you provide an updated link with that input? – daniero – 2017-06-15T18:17:10.457

This is what I got when I run it: . With an empty input, it should be returning "[]" without the quotes. – NoseKnowsAll – 2017-06-15T18:21:50.133

@NoseKnowsAll Your link goes to the "hello world" input (get an updated link by pressing that link/chain button), but yes, I get what you mean. I'll look into that – daniero – 2017-06-15T18:24:35.300

1@NoseKnowsAll There you go, I fixed it ;) – daniero – 2017-06-15T19:10:14.363

4

Java (OpenJDK 8), 86 83 76 bytes

-3 bytes thanks to @KevinCruijssen
-7 bytes thanks to @FlorianSchaetz

s->{String b="";for(char c:s.toCharArray()){b+="'"+c+"':";};return b+"[]";};

Try it online!

Bashful Beluga

Posted 2017-06-14T18:54:35.557

Reputation: 413

You can drop 4 bytes. The trailing ; doesn't have to be counted for lambda answers, the ; after the } isn't necessary at all, and the { and } can be removed around the for-loop. And you could save 4 more bytes in Java 10 changing both the String and char to var. – Kevin Cruijssen – 2018-04-11T09:56:38.587

3

Brain-Flak, 135, 131 bytes

{({}<>)<>}(((((((()()()()()){})){}{}())){}{})[()()])<>{<>(((((((()()()){}()){}){}()){})[(((()()()){})){}{}()])<>)({}<({}<>)>)<>}<>

Try it online!

+1 byte for the -c flag.

Thanks to WheatWizard for removing very obvious NOOPs that I had for no reason XD.

James

Posted 2017-06-14T18:54:35.557

Reputation: 54 537

@WheatWizard >_> Yeah, I was just testing you... Hahaha, thanks for pointing that out. I'll try to golf it more later, but I'll add that now lol – James – 2017-06-15T18:14:26.620

3

Cubix, 31 29 bytes

uo@[)o'U);!A?ro;o;o;os:'/u:''

A can also be substituted for i; trying to figure out if there's a good way to squeeze another byte or two out of this. -2 bytes thanks to MickyT! Also outgolfed by MickyT!

Fits on a 3x3x3 cube:

      u o @
      [ ) o
      ' U )
; ! A ? r o ; o ; o ; o
s : ' / u : ' ' . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

Watch it online!

Try it online!

Giuseppe

Posted 2017-06-14T18:54:35.557

Reputation: 21 077

You can save a couple of bytes, by using a couple of increments for the last bracket. This allows the bottom line to be compressed a bit uo@[)o'U);!A?ro;o;o;os:'/u:'' – MickyT – 2017-06-15T20:56:02.440

3

Standard ML, 52 50 bytes

Saved 2 bytes thanks to @Laikoni!

fn s=>String.translate(fn c=>"'"^str c^"':")s^"[]"

Try it online!

String.translate is an unfortunately long name, but was 5 bytes shorter than using concat, map, and explode.

musicman523

Posted 2017-06-14T18:54:35.557

Reputation: 4 472

@Laikoni thanks! I always forget that operators have lower precedence than functions. – musicman523 – 2017-06-23T14:17:48.193

2

Python 2, 47 bytes

lambda a:`list(a)+[[]]`.replace(', ',':')[1:-1]

Try it online!

Rod

Posted 2017-06-14T18:54:35.557

Reputation: 17 588

I had the same approach but I didn't figure out the [1:-1] part so it was longer than totallyhumans. +1 – Post Rock Garf Hunter – 2017-06-14T19:04:50.153

Strange that the trivial solution is just 3 bytes longer (in Python 3).

– Mr. Xcoder – 2017-06-14T19:18:04.857

2

APL (Dyalog), 21 19 bytes

'[]',⍨'.'⎕R'''&'':'

Try it online!

'[]',⍨ the brackets appended to

'.' every character

⎕R PCRE Replaced with

'''&'':' a quote, the match, a quote and a colon

Adám

Posted 2017-06-14T18:54:35.557

Reputation: 37 779

2

Japt, 14 13 bytes

A port of Downgoat's JS solution.

ç"'$&':" +"[]

Try it

Shaggy

Posted 2017-06-14T18:54:35.557

Reputation: 24 623

2

sed, 19 18 bytes

-1 byte thanks to Jordan

s/./'&':/g;s/$/[]/

Try it online!

Una

Posted 2017-06-14T18:54:35.557

Reputation: 638

2

R, 75 50 bytes

function(x)cat(gsub("(.)","'\\1':",x),"[]",sep="")

Try it online!

Or for a non-regex approach:

R, 63 bytes

function(x)cat(sprintf("'%s':",el(strsplit(x,''))),'[]',sep='')

Try it online!

It turns out that sprintf will recycle the format string to match the length of its input, which is a nice golf from the previous answer (which you can see in the edit history).

Giuseppe

Posted 2017-06-14T18:54:35.557

Reputation: 21 077

In the header for TIO, put library('methods'). That should allow el to work – MickyT – 2017-06-14T21:41:30.020

@MickyT I could but I think at that point I'd need to include it as additional bytes, same as importing it from Python. I'm just complaining because It Works On My Machine (I don't know if any packages I have loaded in are causing that it to work though) – Giuseppe – 2017-06-15T13:22:50.933

No problem, my default install here has it and it may be because TIO is using RScript to execute the scripts

– MickyT – 2017-06-15T19:33:42.800

yeah, I did look into it but I screwed up the empty string case...just remembered you can compare strings to the empty string – Giuseppe – 2017-06-15T19:36:19.660

I tried paste0 again, still landed at the same number of bytes, unless I missed some obvious golfing somewhere. – Giuseppe – 2017-06-15T19:42:51.870

No I missed the empty string trick when I looked at it. – MickyT – 2017-06-15T19:50:17.273

2

JavaScript 23 40 bytes

f=s=>!s?"[]":"'"+[...s].join("':'")+"':[]"

f=s=>!s?"[]":"'"+[...s].join("':'")+"':[]"
console.log(f() + "\n") // `"[]"`
console.log(f("") + "\n") // `"[]"`
console.log(f("abc") + "\n") // "'a':'b':'c':[]"

Using spread element to convert string to array, Array.prototype.join() to concatenate ":" characters

guest271314

Posted 2017-06-14T18:54:35.557

Reputation: 1

2Welcome to PPCG. There seem to be some issues with your answer. 1.) This seems to be a snippet, not a function or full program. 2) This doesn't add quotes around the characters. 3.) You should use some additional formatting in the header of your answer (by putting a # in front of it). – steenbergh – 2017-06-15T08:33:34.310

@steenbergh See updated post – guest271314 – 2017-06-17T02:57:01.883

1Just out of curiosity, why is your StackOverflow account suspended? Sorry if this question is a bit inappropriate. – None – 2017-11-24T00:25:15.230

@guest271314. Ok – None – 2017-11-26T15:45:35.733

2

PHP, 39 bytes

<?while(~$c=$argn[$i++])echo"'$c':"?>[]

Run as pipe with -F.

Titus

Posted 2017-06-14T18:54:35.557

Reputation: 13 814

2

Convex, 10 bytes

{`':`}%"[]

Try it online!

GamrCorps

Posted 2017-06-14T18:54:35.557

Reputation: 7 058

2

Cubix, 27 bytes

uosW?U.iv":'"^soso;os@o[]'/

Try it online!

      u o s
      W ? U
      . i v
" : ' " ^ s o s o ; o s
@ o [ ] ' / . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

Watch it run

A slightly different variation from Guiseppe's answer. This puts the colon and quote on the stack. Then it loops through the input, swapping and outputting the stack. Only the input is scrapped and the colon and quote are retained.

Once the end of the input is reached the IP wonders around the cube a bit, adding and outputting the brackets. There are a couple of redundant commands in the mix.

MickyT

Posted 2017-06-14T18:54:35.557

Reputation: 11 735

2

Ruby, 43 bytes

->a{a==''?'[]':"'#{a.chars.join"':'"}':[]"}

dkudriavtsev

Posted 2017-06-14T18:54:35.557

Reputation: 5 781

You can remove the space after join. – sudee – 2017-06-17T22:01:49.190

Also, this doesn't return the correct output for an empty string. – sudee – 2017-06-17T22:03:48.750

2

Excel, 68 bytes

=IFERROR(CONCAT("'"&MID(A1,ROW(OFFSET(A1,,,LEN(A1))),1)&"':"),)&"[]"

Takes input from A1, outputs to whatever cell this formula is placed in. It's an array formula, so Ctrl-Shift-Enter instead of Enter to enter it.

11 of the bytes here are just for handling the empty string correctly, since Excel doesn't have a concept of arrays with zero elements.

The answer's pretty straightforward, but I did learn a couple things: IFERROR's second argument is taken to be "" when left blank, and & will operate in an array-aware manner if and only if the construction is inside a function that will take an array (replacing CONCAT(...) with just (...) feels like it should work but it doesn't).

Sophia Lechner

Posted 2017-06-14T18:54:35.557

Reputation: 1 200

1

SOGL, 12 bytes

,{ļ'pō':}ō[]

Explanation:

,{      }     iterate over the chars of string input
  ļ'          output "'"
    p         output the current char
     ō':      output "':"
         ō[]  output "[]"

In theory 10 byte ļ'pō':}ō[] could work, but, alas, it doesn't.

dzaima

Posted 2017-06-14T18:54:35.557

Reputation: 19 048

1

Ruby, 43 28 + 1 = 44 29 bytes

A whopping -15 bytes thanks to Value Ink.

+1 byte for the -p flag.

$_=gsub(/(.)/,"'\\1':")+"[]"

Try it online!

totallyhuman

Posted 2017-06-14T18:54:35.557

Reputation: 15 378

Since you're using the -p flag you can replace $_.gsub! with simply gsub, and you don't need the parantheses. That should save 8 bytes in total: gsub /(.)/,"'\\1':";gsub /$/,'[]' – daniero – 2017-06-14T21:48:10.490

1Edit: This is even shorter:Switch the -p flag with -n and the code with $><<gsub(/(.)/,"'\\1':")+"[]" – daniero – 2017-06-15T16:58:15.230

1

Aceto, 26 bytes

:Lpp&p
'p|L
\'!d["
'M@,]"p

L3viathan

Posted 2017-06-14T18:54:35.557

Reputation: 3 151

1

PowerShell, 43 bytes

It's a join(map(repr, input)) shape problem? That's simply 177 bytes of:

[linq.enumerable]::Aggregate([Linq.Enumerable]::Select(
[Object[]][Char[]]"$args", [Func[Object,String]]{"'$args'"})+(,'[]'),
[func[object,object,object]]{param($a,$b) $a+':'+$b})

Edit: can golf that down to a mere 171:

$e='[Linq.Enumerable]::';$o='Object';
"${e}Aggregate(${e}Select([$o[]][Char[]]""$args"",[Func[$o,$O]]{""'`$args'""})+(,'[]'),[func[$o,$o,$o]]{`$args[0]+':'+`$args[1]})"|iex

Oh all right, 43 bytes of:

(([char[]]"$args"|%{"'$_'"})+,'[]')-join':'

TessellatingHeckler

Posted 2017-06-14T18:54:35.557

Reputation: 2 412

It does not work with the test case "a" -> 'a':[]. I'm sorry. – mazzy – 2018-12-02T09:20:50.900

Curiouser and curiouser! 37 bytes @($args|% t*y|%{"'$_'"})+'[]'-join':' – mazzy – 2018-12-02T09:28:31.043

1

Swift, 49 bytes

{$0.characters.reduce("",{$0+"'\($1)':"})+"[]"}

This is a lambda (closure in Swift). Because converting a Character Array to a string is a.joined(seperator:"") I've used .reduce("",+) as a golf. Kind of unreadable so broken down:

{
  $0.characters.reduce("", {
    $0 + "'\($1)':"
  }) + "[]"
}

because a map + converting to a string is too long, reduce will convert to a string for us as we go

Downgoat

Posted 2017-06-14T18:54:35.557

Reputation: 27 116

1

><>, 27 bytes

i:0(?vd3*:o$oo':'o
o'[]'/;o

Try it online!

Emigna

Posted 2017-06-14T18:54:35.557

Reputation: 50 798

1

Noether, 37 bytes

{I~sL0>}{sL("'"Psi/P"':"Pi1+~i)}"[]"P

Try it here!

Takes input between quotation marks.

Beta Decay

Posted 2017-06-14T18:54:35.557

Reputation: 21 478

1

Excel VBA, 51 bytes

Anonymous VBE immedate function that takes input as string from cell [A1], iterates across the input string, splitting it by character and then outputs to the VBE immediate window

For i=1To[Len(A1)]:?"'"Mid([A1],i,1)"':";:Next:?"[]

Previous, Longer Versions

1:  a=Split(StrConv([A1],64),Chr(0)):For i=0To[Len(A1)-1]:?"'"a(i)"':";:Next:?"[]"

2:  ?"'"Mid(Join(Split(StrConv([A1],64),Chr(0)),"':'"),1,4*Len([A1])-1)"[]"

3:  ?"'"Left(Join(Split(StrConv([A1],64),Chr(0)),"':'"),4*Len([A1])-1)"[]"

4:  ?"'"Replace(Left(Strconv([A1],64),2*Len([A1])-1),Chr(0),"':'")":[]"    

5:  ?Replace(Left("'"&StrConv([A1],64),2*Len([A1])),Chr(0),"':'")"':[]"

6:  ?"'"Left(Replace(StrConv([A1],64),Chr(0),"':'"),4*Len([A1])-1)"[]"

7:  ?"'"Replace(Replace(StrConv([A1],64),Chr(0),"':'")&" ","' ","[]")

8:  For i=1To Len([A1]):?"'"&Mid([A1],i,1);"':";:Next:?"[]"

9:  For i=1To[Len(A1)]:?"'"&Mid([A1],i,1);"':";:Next:?"[]"

10: For i=1To[Len(A1)]:?"'"Mid([A1],i,1)"':";:Next:?"[]"

Taylor Scott

Posted 2017-06-14T18:54:35.557

Reputation: 6 709

1

Mathematica, 34 bytes

"'"<>#<>"':"&/@Characters@#<>"[]"&

Anonymous function. Takes a string as input and returns a string as output. Just separates the input's characters, inserts '...': around each, and adds [] to the end.

LegionMammal978

Posted 2017-06-14T18:54:35.557

Reputation: 15 731

1

Charcoal, 11 bytes

FS⁺⁺'ι':¦[]

Try it online! Explanation provided as AST.

ASCII-only

Posted 2017-06-14T18:54:35.557

Reputation: 4 687

1

Rust, 69 bytes

|s:&str|s.chars().map(|s|format!("'{}':",s)).collect::<String>()+"[]"

Couldn't find anything shorter than the trivial solution.

CensoredUsername

Posted 2017-06-14T18:54:35.557

Reputation: 951

1

Java, 60 bytes

String f(String s){return s.replaceAll(".","['$0']:")+"[]";}

Khaled.K

Posted 2017-06-14T18:54:35.557

Reputation: 1 435

1

brainfuck, 48 bytes

-[-[<++>->++>-<<]>]<<,[<-.>.<.+<.>>,]<<<<+++.++.

Try it online!

Jo King

Posted 2017-06-14T18:54:35.557

Reputation: 38 234

1

Stax, 10 bytes

╩8┼Φv╚▀╛┴►

Run and debug it

recursive

Posted 2017-06-14T18:54:35.557

Reputation: 8 616

Never thought of doing it this way ... – Weijun Zhou – 2018-04-11T07:17:11.517

1

MATL, 16 bytes

g39*Gyt19+v'[]'h

Try it online!

A bit surprised not to see a MATL submission already.

Explanation:

	% implicit input, 'abc'
g	% convert to logical
	% STACK: {[1 1 1]}
39*	% multiply by 39, ASCII for ', elementwise.
	% STACK: {[39 39 39]}
G	% push input
	% STACK: {[39 39 39]; 'abc'}
yt	% copy from below and dup
	% STACK: {[39 39 39]; 'abc'; [39 39 39]; [39 39 39]}
19+	% add 19, elementwise, to get 58, ASCII for :
	% STACK: {[39 39 39]; 'abc'; [39 39 39]; [58 58 58]}
v	% vertically concatenate stack contents, implicitly converting to strings.
	% STACK: {'''
	%	  abc
	%	  '''
	%	  :::}
'[]'h	% push '[]' and horizontally concatenate, linearizing as needed
	% STACK: 'a':'b':'c':[]
	% implicit output

Giuseppe

Posted 2017-06-14T18:54:35.557

Reputation: 21 077

0

Jelly, 13 bytes

”';Ѐ;€⁾':⁾[]

Try it online!

Explanation:

”';Ѐ;€⁾':⁾[]

”';Ѐ            Concatenate ' to the beginning of each element
     ;€⁾':       Concatenate ': to the end of each element
          ⁾[]    Implicit concatenation of literal "[]"

scatter

Posted 2017-06-14T18:54:35.557

Reputation: 874

This doesn't appear to add single quotes around each character. – FryAmTheEggman – 2017-06-14T19:15:37.320

@FryAmTheEggman Noticed as soon as I posted it. Fixing now. – scatter – 2017-06-14T19:16:18.367

0

CJam, 13 12 bytes

q{`':`}%"[]"

Explanation:

q    e# Input: "test"
{    e# For each character: ['t 'e 's 't]
  `  e#   Get the string representation: ["'t" "'e" "'s" "'t"]
  ': e#   Push the character ':': ["'t" ': "'e" ': "'s" ': "'t" ':]
  `  e#   Get the string representation: ["'t" "':" "'e" "':" "'s" "':" "'t" ':]
}%   e# End
"[]" e# Push the string "[]"
e# Implicit print: 't':'e':'s':'t':[]

Esolanging Fruit

Posted 2017-06-14T18:54:35.557

Reputation: 13 542

0

braingasm, 18 bytes

,[39.."':".,]"[]".

Just a simple loop, reading one byte at a time and printing the necessary stuff before and after the input, then the final square brackets.

Test run:

$ echo -n Hello | braingasm haskell_strings.bg 
'H':'e':'l':'l':'o':[]

daniero

Posted 2017-06-14T18:54:35.557

Reputation: 17 193

0

QBIC, 35 bytes

[_l;||X=X+@'`+_sA,a,1|+B+@:`]?X+@[]

Explanation

[    |         FOR a = 1 TO
 _l |           the length of
   ;              input string
X=X+@'`        Add to Z$ a literal '
   +_sA,a,1|   and a 1-char substring at index a of the input A$
   +B          and another quote (defining it as literal created B$)
   +@:`        and a literal :
]              NEXT
?X+@[]         PRINT Z$ and a literal [] (no closing backtick because EOF)

steenbergh

Posted 2017-06-14T18:54:35.557

Reputation: 7 772

0

Octave, 37 bytes

@(s)(s&&printf("'%c':",s))+puts("[]")

Try it online!

rahnema1

Posted 2017-06-14T18:54:35.557

Reputation: 5 435

0

Braingolf, 29 bytes

VRl1-M[R>#'<"':">>>>v]R"[]"&@

Try it online!

Currently a bug in Braingolf foreach loops that breaks them when handling 2 adjacent duplicates (such as the ls in Hello), so I have to use this method that costs me an extra 13 bytes

If foreach loops worked properly, it would've been this, which is only 16 bytes:

{>#'<"':"}"[]"&@

Explanation

VRl1-M[R>#'<"':">>>>v]R"[]"&@  Implicit input from commandline args
VRl1-M                         Create stack2, push length of stack1 - 1 to stack2
      [..............]         Do-While loop, will run for each item on stack1
       R>                      Return to stack2, move ToS to bottom
         #'<                   Push single quote and move BoS back to top
            "':"               Push single quote and colon
                >>>>           Rotate stack to next item from input
                    v          Switch to stack2 for loop counting
                      R"[]"&@  Switch to stack1, push [] and print entire stack

Skidsdev

Posted 2017-06-14T18:54:35.557

Reputation: 9 656

0

Groovy, 37 bytes

{it.replaceAll(~/./,{"'$it':"})+"[]"}

(It's an anonymous closure, which can be called thus {...}("hello") or via a name thus f = {...};f("hello").)

randomsimon

Posted 2017-06-14T18:54:35.557

Reputation: 151

0

Python 3, 36 bytes

lambda s:':'.join(map(repr,[*s,[]]))

A variation of Rod's one.

Try it online!

Evpok

Posted 2017-06-14T18:54:35.557

Reputation: 558

0

setlx, 36 bytes

s|->join(["'"+x+"':":x in s],"")+"[]";

Explanation:

s |->                               // a function taking an argument s
    join(                           // join:
        [ "'" + x + "':" : x in s], // a list from each char wrapped in quotes
        ""                          // with the empty string
    ) 
    + []                            // add an empty list to the string, this will convert it to the string "[]"
;

corvus_192

Posted 2017-06-14T18:54:35.557

Reputation: 1 889

0

Clojure, 42 bytes

#(str(apply str(for[c %](str"'"c"':")))[])

madstap

Posted 2017-06-14T18:54:35.557

Reputation: 141

0

Javascript 33 bytes

f=s=>s.replace(/(.)/g,"'$1':")+'[]'

Steve Bennett

Posted 2017-06-14T18:54:35.557

Reputation: 1 558

0

><>, 25 bytes

i:0(?v":''"o{ooo
o"[]"<;o

Try it online!

hakr14

Posted 2017-06-14T18:54:35.557

Reputation: 1 295

You can save a couple of bytes by taking input through the -s flag – Jo King – 2018-04-11T06:41:50.397

0

Actually, 9 bytes

♂è[]@q':j

Try it online!

Explanation:

♂è[]@q':j
           implicit input ("abc")
♂è         push a list containing the string representation of each character (['a', 'b', 'c'])
  []@q     add an empty list to the end of that list (['a', 'b', 'c', [])
      ':j  join with colons ("'a':'b':'c':[]")
           implicit print ('a':'b':'c':[])

Mego

Posted 2017-06-14T18:54:35.557

Reputation: 32 998

0

Pari/GP, 52 bytes

s->c=concat;c(c([Str("'",x,"':")|x<-Vec(s)],["[]"]))

Try it online!

alephalpha

Posted 2017-06-14T18:54:35.557

Reputation: 23 988

0

SNOBOL4 (CSNOBOL4), 81 bytes

	N =INPUT
S	N LEN(1) . X REM . N	:F(O)
	O =O "'" X "':"	:(S)
O	OUTPUT =O "[]"
END

Try it online!

Giuseppe

Posted 2017-06-14T18:54:35.557

Reputation: 21 077

0

Add++, 30 bytes

D,f,@*,39@39 58
L^~,€{f}"[]"BF

Try it online!

How it works

D,f,@*,		; Create a function, 'f', that
		; that takes one argument, and returns the full stack
		; Example argument:	['a']
	39@	; Prepend 39;	STACK = [39 'a']
	39 58	; Push 39, 58;	STACK = [39 'a' 39 58]
		; Return the full stack
		; 39 is the ordinal of ' and 58 of :

L^~,		; Create a lambda function
		; The ^ converts all integers to characters, then concatenates, when returning
		; The ~ unpacks the argument beforehand
		; Example argument:		['a' 'b' 'c']
	€{f}	; Run 'f' over each;	STACK = [[39 'a' 39 58] [39 'b' 39 58] [39 'c' 39 58]]
	"[]"	; Push '[]';		STACK = [[39 'a' 39 58] [39 'b' 39 58] [39 'c' 39 58] '[]']
	BF	; Flatten;		STACK = [39 'a' 39 58 39 'b' 39 58 39 'c' 39 58 '[]']
		; The ^ flag converts integers to characters:
		;			STACK = ["'" 'a' "'" ':' "'" 'b' "'" ':' "'" 'c' "'" ':' '[]']
		; Then concatenates them into a single string:
		;			STACK = ["'a':'b':'c':[]"]
		; And returns the top value:
		;			Return "'a':'b':'c':[]"

caird coinheringaahing

Posted 2017-06-14T18:54:35.557

Reputation: 13 702

0

SmileBASIC 3, 53 48 bytes

-5 with the WHILE trick, thanks 12Me21!

LINPUT S$WHILE""<S$?"'"+SHIFT(S$)+"':";
WEND?"[]

Explainer:

LINPUT S$              'Read line from console
WHILE ""<S$            'WHILE S$ is not empty
 ?"'"+SHIFT(S$)+"':";  'Print 'x': where x is popped off the front of S$
WEND                   'End WHILE
?"[]"                  'Print []

snail_

Posted 2017-06-14T18:54:35.557

Reputation: 1 982

snail remember – 12Me21 – 2018-04-10T00:22:04.827

0

Husk, 9 bytes

J':`:søms

Try it online!

Explanation

J':`:søms  Implicit input                                 "abc"
       ms  String representation of each character        ["'a'","'b'","'c'"]
   `:sø    Append the string of an empty list to the end  ["'a'","'b'","'c'","[]"]
J':        Join with a colon character                    "'a':'b':'c':[]"

Fyr

Posted 2017-06-14T18:54:35.557

Reputation: 561

0

F#, 55 bytes

My first F#, which means it probably isn't very good. My SmileBASIC answer is beating it, even...

fun s->List.reduce(+)[for c in s->sprintf"'%c':"c]+"[]"

Try it online. Golfing tips are appreciated

snail_

Posted 2017-06-14T18:54:35.557

Reputation: 1 982

The space before the last c can be dropped. – Ørjan Johansen – 2018-04-11T06:25:17.647

0

Kotlin, 34 bytes

{it.fold(""){a,v->a+"'$v':"}+"[]"}

Try it online!

snail_

Posted 2017-06-14T18:54:35.557

Reputation: 1 982

0

Ahead, 25 bytes

v>"]["W@
>jri''r
^W"':"W<

Try it online!

snail_

Posted 2017-06-14T18:54:35.557

Reputation: 1 982

0

Burlesque - 21 bytes

m{bx"'~':"jf~}"[]"_+Q

Longer versions:

XX{bx"'~':"jf~}\m"[]"_+Q

Burlesque shows characters with a single ' i.e. 'x instead of 'x' which is why we have to surround characters manually with two 's.

mroman

Posted 2017-06-14T18:54:35.557

Reputation: 1 382

0

Forth (gforth), 47 bytes

: f bounds ?do ." '"i 1 type ." ':"loop ." []";

Try it online!

Code Explanation

: f          \ start a new word definition
  bounds     \ get the starting and ending addresses of the string
  ?do        \ loop from start to end (skip if start=end)       
    ." '"    \ output '
    i 1 type \ print the character at the current address
    emit     \ output character of string
    ." ':"   \ output ':
  loop       \ end loop
  ." []"     \ output []
;            \ end word definition

reffu

Posted 2017-06-14T18:54:35.557

Reputation: 1 361