52
\$\begingroup\$

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':[]   
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – FryAmTheEggman Jun 14 '17 at 19:05
  • \$\begingroup\$ @FryAmTheEggman You can assume they are in the ascii range \$\endgroup\$ – Sriotchilism O'Zaic Jun 14 '17 at 19:06
  • 7
    \$\begingroup\$ @totallyhuman Those are not even valid Haskell. If they were maybe, but nice they are not, definitely no. \$\endgroup\$ – Sriotchilism O'Zaic Jun 14 '17 at 20:43
  • 38
    \$\begingroup\$ This question can be alternatively titled "Diet Haskell". \$\endgroup\$ – March Ho Jun 15 '17 at 14:42
  • 1
    \$\begingroup\$ @cairdcoinheringaahing No, " and ' are syntactically different. \$\endgroup\$ – Sriotchilism O'Zaic Apr 9 '18 at 17:32

72 Answers 72

84
\$\begingroup\$

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 "'\\'':[]".

\$\endgroup\$
  • 25
    \$\begingroup\$ Wait a minute, you mean (++'[':']':[]).((++':':[]).show=<<), no? \$\endgroup\$ – Adám Jun 14 '17 at 19:27
  • 10
    \$\begingroup\$ When any challenge has a Haskell answer, I upvote it out of principle. That goes double for this one. \$\endgroup\$ – Ryan Reich Jun 15 '17 at 5:39
43
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ I suppose that means (++'[':']':[]).(>>= \c->'\'':[]++[c]++'\'':':':[]). \$\endgroup\$ – Adám Jun 14 '17 at 19:31
  • 1
    \$\begingroup\$ I 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. \$\endgroup\$ – CAD97 Jun 16 '17 at 10:04
  • 3
    \$\begingroup\$ This is rather amazing. Two separate approaches that have the same byte count in the same language. \$\endgroup\$ – J Atkin Jun 17 '17 at 19:52
19
\$\begingroup\$

Python 3, 32 bytes

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

Try it online!

\$\endgroup\$
17
\$\begingroup\$

JavaScript ES6, 42 40 31 bytes

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

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

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ I love this about CodeGolf. Never knew about $&. \$\endgroup\$ – Steve Bennett Jun 18 '17 at 7:42
16
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Jun 15 '17 at 8:53
  • 2
    \$\begingroup\$ Lisp! Welcome indeed :) \$\endgroup\$ – Olivier Dulac Jun 15 '17 at 13:47
  • \$\begingroup\$ @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) \$\endgroup\$ – coredump Jun 18 '17 at 13:04
  • \$\begingroup\$ @coredump, thanks!, I've updated the code. \$\endgroup\$ – Renzo Jun 18 '17 at 13:08
11
\$\begingroup\$

V, 11 bytes

Í./'&':
A[]

Try it online!

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

\$\endgroup\$
9
\$\begingroup\$

C, 55 54 53 bytes

s(char*h){while(*h)printf("'%c':",*h++);puts("[]");}
\$\endgroup\$
  • 1
    \$\begingroup\$ you can remove the space in char *h \$\endgroup\$ – Cyoce Jun 14 '17 at 19:24
  • 1
    \$\begingroup\$ You can do puts("[]"); instead to output with a trailing newline to save some bytes. \$\endgroup\$ – Cows quack Jun 14 '17 at 19:29
  • \$\begingroup\$ recursive s(char*h){*h?printf("'%c':",*h++),s(h):puts("[]");} \$\endgroup\$ – l4m2 Apr 9 '18 at 2:59
8
\$\begingroup\$

Python 3, 41 38 36 bytes

-2 bytes thanks to ovs

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Whoops... Forgot that *map exists... \$\endgroup\$ – Mr. Xcoder Jun 14 '17 at 19:25
  • \$\begingroup\$ I was puzzled by the empty input() for the past 20 minutes (literally), when it could just be a lambda @.@ \$\endgroup\$ – Rod Jun 14 '17 at 19:26
  • \$\begingroup\$ Empty input does work? \$\endgroup\$ – Sriotchilism O'Zaic Jun 14 '17 at 19:38
  • \$\begingroup\$ @WheatWizard oh, I was using a empty-empty (no newline) input \$\endgroup\$ – Rod Jun 14 '17 at 19:40
  • \$\begingroup\$ You can replace "[]" with [] \$\endgroup\$ – ovs Jun 14 '17 at 21:08
8
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Apparently I beat you by 4 seconds ;-) \$\endgroup\$ – Digital Trauma Jun 14 '17 at 19:01
  • 1
    \$\begingroup\$ @DigitalTrauma Yours popped up as I was pressing Post Your Answer. \$\endgroup\$ – Riley Jun 14 '17 at 19:02
  • 1
    \$\begingroup\$ You 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"'ÿ':"?}¯? \$\endgroup\$ – Magic Octopus Urn Jun 14 '17 at 19:43
  • \$\begingroup\$ @carusocomputing I use the string interpolator all the time for test suites, but forget to use it in actual code. Thanks! \$\endgroup\$ – Riley Jun 14 '17 at 19:51
  • \$\begingroup\$ @carusocomputing I thought vy"'ÿ':"}¯J would work for 11, but J joins the global array, not the whole stack in that situation. \$\endgroup\$ – Riley Jun 14 '17 at 19:57
8
\$\begingroup\$

R, 51 bytes

f<-function(x)(paste0(gsub("(.)","'\\1':",x),'[]'))
\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Giuseppe Jun 16 '17 at 14:38
  • \$\begingroup\$ 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! \$\endgroup\$ – t c Jun 16 '17 at 15:37
  • \$\begingroup\$ 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 \$\endgroup\$ – Giuseppe Jun 16 '17 at 15:39
  • \$\begingroup\$ paste0(gsub('(.)',"'\\1':",scan(,"")),'[]') is 43 \$\endgroup\$ – Zahiro Mor Jun 18 '17 at 8:45
8
\$\begingroup\$

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 :
\$\endgroup\$
  • \$\begingroup\$ @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! \$\endgroup\$ – KarlKastor Jun 16 '17 at 8:20
7
\$\begingroup\$

Perl 6, 19 bytes

{S:g|.|'$/':|~'[]'}
\$\endgroup\$
7
\$\begingroup\$

Retina, 12

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

2 stages:

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

Try it online.

\$\endgroup\$
  • \$\begingroup\$ Helped the guy you beat by 4 seconds tie you ;). \$\endgroup\$ – Magic Octopus Urn Jun 14 '17 at 19:45
  • \$\begingroup\$ I was thinking of this! \$\endgroup\$ – CalculatorFeline Jun 18 '17 at 16:43
6
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Slightly shorter \$\endgroup\$ – Sriotchilism O'Zaic Jun 14 '17 at 19:19
  • \$\begingroup\$ Oh, neat. Thanks! \$\endgroup\$ – totallyhuman Jun 14 '17 at 19:36
  • 1
    \$\begingroup\$ One shorter as lambda s:':'.join(map(repr,[*s,[]])) or lambda s:':'.join(map(repr,s))+":[]". \$\endgroup\$ – xnor Jun 14 '17 at 19:52
  • \$\begingroup\$ @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) \$\endgroup\$ – Sriotchilism O'Zaic Jun 15 '17 at 3:28
6
\$\begingroup\$

Befunge, 29 27 bytes

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

Try it online!

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

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>

\$\endgroup\$
5
\$\begingroup\$

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): []
\$\endgroup\$
4
\$\begingroup\$

PHP, 41 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ 4 bytes shorter: for(;~$c=$argn[$i++];)echo"'$c':"?>[]. \$\endgroup\$ – user63956 Jun 15 '17 at 1:31
  • \$\begingroup\$ @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 \$\endgroup\$ – Jörg Hülsermann Jun 15 '17 at 10:41
  • \$\begingroup\$ It works with the -R flag. Tags can be closed even in constructions like eval() and create_function(). \$\endgroup\$ – user63956 Jun 15 '17 at 12:05
4
\$\begingroup\$

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!

\$\endgroup\$
4
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Kevin Cruijssen Apr 11 '18 at 9:56
4
\$\begingroup\$

brainfuck, 68 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Doesn't quite work with the empty string - returned me two non-valid characters in your online test. Very nice, otherwise. \$\endgroup\$ – NoseKnowsAll Jun 15 '17 at 17:57
  • \$\begingroup\$ @NoseKnowsAll I can't seem to replicate that; With no input I get no output. Could you provide an updated link with that input? \$\endgroup\$ – daniero Jun 15 '17 at 18:17
  • \$\begingroup\$ This is what I got when I run it: . With an empty input, it should be returning "[]" without the quotes. \$\endgroup\$ – NoseKnowsAll Jun 15 '17 at 18:21
  • \$\begingroup\$ @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 \$\endgroup\$ – daniero Jun 15 '17 at 18:24
  • 1
    \$\begingroup\$ @NoseKnowsAll There you go, I fixed it ;) \$\endgroup\$ – daniero Jun 15 '17 at 19:10
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ @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 \$\endgroup\$ – DJMcMayhem Jun 15 '17 at 18:14
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ @Laikoni thanks! I always forget that operators have lower precedence than functions. \$\endgroup\$ – musicman523 Jun 23 '17 at 14:17
3
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ 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:'' \$\endgroup\$ – MickyT Jun 15 '17 at 20:56
2
\$\begingroup\$

Python 2, 47 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I had the same approach but I didn't figure out the [1:-1] part so it was longer than totallyhumans. +1 \$\endgroup\$ – Sriotchilism O'Zaic Jun 14 '17 at 19:04
  • \$\begingroup\$ Strange that the trivial solution is just 3 bytes longer (in Python 3). \$\endgroup\$ – Mr. Xcoder Jun 14 '17 at 19:18
2
\$\begingroup\$

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

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

sed, 19 18 bytes

-1 byte thanks to Jordan

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

Try it online!

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

PHP, 39 bytes

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

Run as pipe with -F.

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

Convex, 10 bytes

{`':`}%"[]

Try it online!

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

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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