Sugar Free Syntax

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


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

• 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 Jun 14 '17 at 19:05
• @totallyhuman Those are not even valid Haskell. If they were maybe, but nice they are not, definitely no. – Wheat Wizard Jun 14 '17 at 20:43
• This question can be alternatively titled "Diet Haskell". – March Ho Jun 15 '17 at 14:42
• May we use " instead of ' (e.g. "a" -> "a":[])? – caird coinheringaahing Apr 9 '18 at 17:31
• @cairdcoinheringaahing No, " and ' are syntactically different. – Wheat Wizard Apr 9 '18 at 17:32

JavaScript23 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

• Welcome 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 Jun 15 '17 at 8:33
• @steenbergh See updated post – guest271314 Jun 17 '17 at 2:57
• Just out of curiosity, why is your StackOverflow account suspended? Sorry if this question is a bit inappropriate. – user72349 Nov 24 '17 at 0:25
• @guest271314. Ok – user72349 Nov 26 '17 at 15:45

Ruby, 43 bytes

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

• You can remove the space after join. – sudee Jun 17 '17 at 22:01
• Also, this doesn't return the correct output for an empty string. – sudee Jun 17 '17 at 22:03

Japt, 14 13 bytes

A port of Downgoat's JS solution.

ç"'$&':" +"[]  Try it 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). • In the header for TIO, put library('methods'). That should allow el to work – MickyT Jun 14 '17 at 21:41 • @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 Jun 15 '17 at 13:22 • No problem, my default install here has it and it may be because TIO is using RScript to execute the scripts – MickyT Jun 15 '17 at 19:33 • 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 Jun 15 '17 at 19:36 • I tried paste0 again, still landed at the same number of bytes, unless I missed some obvious golfing somewhere. – Giuseppe Jun 15 '17 at 19:42 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). 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  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. Aceto, 26 bytes :Lpp&p 'p|L \'!d[" 'M@,]"p  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':'  • It does not work with the test case "a" -> 'a':[]. I'm sorry. – mazzy Dec 2 '18 at 9:20 • Curiouser and curiouser! 37 bytes @($args|% t*y|%{"'$_'"})+'[]'-join':' – mazzy Dec 2 '18 at 9:28 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 ><>, 27 bytes i:0(?vd3*:o$oo':'o
o'[]'/;o


Try it online!

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.

Charcoal, 11 bytes

ＦＳ⁺⁺'ι':¦[]


Try it online! Explanation provided as AST.

Noether, 37 bytes

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


Try it here!

Takes input between quotation marks.

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! • 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 Jun 14 '17 at 21:48 • Edit: This is even shorter:Switch the -p flag with -n and the code with $><<gsub(/(.)/,"'\\1':")+"[]" – daniero Jun 15 '17 at 16:58

Rust, 69 bytes

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


Couldn't find anything shorter than the trivial solution.

Java, 60 bytes

String f(String s){return s.replaceAll(".","['$0']:")+"[]";}  brainfuck, 48 bytes -[-[<++>->++>-<<]>]<<,[<-.>.<.+<.>>,]<<<<+++.++.  Try it online! Stax, 10 bytes ╩8┼Φv╚▀╛┴►  Run and debug it • Never thought of doing it this way ... – Weijun Zhou Apr 11 '18 at 7:17 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 • The space before the last c can be dropped. – Ørjan Johansen Apr 11 '18 at 6:25 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:?"[]"  Kotlin, 34 bytes {it.fold(""){a,v->a+"'$v':"}+"[]"}


Try it online!

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


Try it online!

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.

Rust macro, 185 bytes

macro_rules!f{([])=>{['[',']']};([$c:expr]$($o:tt)*)=>{[$($o,)*'\'',$c,'\'',':','[',']']};([$c:expr$(,$r:tt)*]$($o:tt)*)=>{f!([$($r),*]$($o)*'\''$c'\''':')};($($r:tt)*)=>{f!([$($r)*])}}


Defines a macro that takes a comma-seperated sequence of character tokens and expands to an array of characters.

try it online

Explanation

macro_rules! f {
// the macro is a tt muncher where the inputs are in brackets with the
// accumulator after that.

// the base case for an empty array
([]) => {
// expand to the brackets
['[', ']']
};
// the base case for a single element
([$c:expr]$($o:tt)*) => { [$($o,)* '\'',$c, '\'', ':', '[', ']']
};
// the recursive case
// extract a characters from the input token stream
([$c:expr$(,$r:tt)*]$($o:tt)*) => { f!([$($r),*]$($o)* '\''$c '\'' ':')
};

// entry point
($($r:tt)*) => {
// call the recursive part by wrapping the arguments in brackets
f!([$($r)*])
}
}


naz, 82 bytes

2a2x1v2m9m3a2x2v9a9a1a2x3v1x1f1r3x1v2e2x4v2v1o4v1o2v1o3v1o1f0x1x2f9m5m1a1o2a1o0x1f


Works for any input string terminated with the control character STX (U+0002).

Explanation (with 0x commands removed)

2a2x1v                             # Set variable 1 equal to 2
2m9m3a2x2v                         # Set variable 2 equal to 39 ("'")
9a9a1a2x3v                         # Set variable 3 equal to 58 (":")
1x1f                               # Function 1
1r                             # Read a byte of input
2x4v                   # Otherwise, store the byte in variable 4
2v1o4v1o2v1o3v1o   # Output it, using variables 2 and 3 to format it as required
1f # Jump back to the start of function 1
1x2f                               # Function 2
9m5m1a1o2a1o                   # Output "[]"
1f                                 # Call function 1


Keg, 16 bytes

÷⑷\&⑨ⁿ:"\:⅍⅀⑸[]


Try it online!

This is what you call "the result of me not implementing things properly".

Erlang (escript), 52 bytes

Pretty simple solution.

f(X)->lists:join(":",[["'"|[I|"'"]]||I<-X]++["[]"]).


Try it online!

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
." ':"   \ output ':
loop       \ end loop
." []"     \ output []
;            \ end word definition


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 "[]"

• This doesn't appear to add single quotes around each character. – FryAmTheEggman Jun 14 '17 at 19:15
• @FryAmTheEggman Noticed as soon as I posted it. Fixing now. – scatter Jun 14 '17 at 19:16