58
\$\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\$ – Ad Hoc Garf Hunter 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\$ – Ad Hoc Garf Hunter Jun 14 '17 at 20:43
  • 39
    \$\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\$ – Ad Hoc Garf Hunter Apr 9 '18 at 17:32

77 Answers 77

2
\$\begingroup\$

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

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

Ruby, 43 bytes

->a{a==''?'[]':"'#{a.chars.join"':'"}':[]"}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can remove the space after join. \$\endgroup\$ – sudee Jun 17 '17 at 22:01
  • \$\begingroup\$ Also, this doesn't return the correct output for an empty string. \$\endgroup\$ – sudee Jun 17 '17 at 22:03
2
\$\begingroup\$

Japt, 14 13 bytes

A port of Downgoat's JS solution.

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

Try it

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ In the header for TIO, put library('methods'). That should allow el to work \$\endgroup\$ – MickyT Jun 14 '17 at 21:41
  • \$\begingroup\$ @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) \$\endgroup\$ – Giuseppe Jun 15 '17 at 13:22
  • \$\begingroup\$ No problem, my default install here has it and it may be because TIO is using RScript to execute the scripts \$\endgroup\$ – MickyT Jun 15 '17 at 19:33
  • \$\begingroup\$ yeah, I did look into it but I screwed up the empty string case...just remembered you can compare strings to the empty string \$\endgroup\$ – Giuseppe Jun 15 '17 at 19:36
  • \$\begingroup\$ I tried paste0 again, still landed at the same number of bytes, unless I missed some obvious golfing somewhere. \$\endgroup\$ – Giuseppe Jun 15 '17 at 19:42
2
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Aceto, 26 bytes

:Lpp&p
'p|L
\'!d["
'M@,]"p
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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':'
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It does not work with the test case "a" -> 'a':[]. I'm sorry. \$\endgroup\$ – mazzy Dec 2 '18 at 9:20
  • \$\begingroup\$ Curiouser and curiouser! 37 bytes @($args|% t*y|%{"'$_'"})+'[]'-join':' \$\endgroup\$ – mazzy Dec 2 '18 at 9:28
1
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

><>, 27 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Charcoal, 11 bytes

FS⁺⁺'ι':¦[]

Try it online! Explanation provided as AST.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Noether, 37 bytes

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

Try it here!

Takes input between quotation marks.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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!

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

Rust, 69 bytes

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

Couldn't find anything shorter than the trivial solution.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Java, 60 bytes

String f(String s){return s.replaceAll(".","['$0']:")+"[]";}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

brainfuck, 48 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Stax, 10 bytes

╩8┼Φv╚▀╛┴►

Run and debug it

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Never thought of doing it this way ... \$\endgroup\$ – Weijun Zhou Apr 11 '18 at 7:17
1
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The space before the last c can be dropped. \$\endgroup\$ – Ørjan Johansen Apr 11 '18 at 6:25
1
\$\begingroup\$

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:?"[]"
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Kotlin, 34 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Ahead, 25 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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)*])
    }
}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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
      3x1v2e                       # Jump to function 2 if it equals variable 1
            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
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Keg, 16 bytes

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

Try it online!

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

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Erlang (escript), 52 bytes

Pretty simple solution.

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

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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 "[]"
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ This doesn't appear to add single quotes around each character. \$\endgroup\$ – FryAmTheEggman Jun 14 '17 at 19:15
  • \$\begingroup\$ @FryAmTheEggman Noticed as soon as I posted it. Fixing now. \$\endgroup\$ – scatter Jun 14 '17 at 19:16

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.