55
\$\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\$ – Wheat Wizard 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\$ – Wheat Wizard 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\$ – Wheat Wizard Apr 9 '18 at 17:32

73 Answers 73

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

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

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

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

\$\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.

\$\endgroup\$
1
\$\begingroup\$

Aceto, 26 bytes

:Lpp&p
'p|L
\'!d["
'M@,]"p
\$\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':'
\$\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

\$\endgroup\$
1
\$\begingroup\$

><>, 27 bytes

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

Try it online!

\$\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.

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 11 bytes

FS⁺⁺'ι':¦[]

Try it online! Explanation provided as AST.

\$\endgroup\$
1
\$\begingroup\$

Noether, 37 bytes

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

Try it here!

Takes input between quotation marks.

\$\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!

\$\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.

\$\endgroup\$
1
\$\begingroup\$

Java, 60 bytes

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

brainfuck, 48 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Stax, 10 bytes

╩8┼Φv╚▀╛┴►

Run and debug it

\$\endgroup\$
  • \$\begingroup\$ Never thought of doing it this way ... \$\endgroup\$ – Weijun Zhou Apr 11 '18 at 7:17
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:?"[]"
\$\endgroup\$
1
\$\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
\$\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 "[]"
\$\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
0
\$\begingroup\$

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':[]
\$\endgroup\$
0
\$\begingroup\$

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':[]
\$\endgroup\$
0
\$\begingroup\$

Octave, 37 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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

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

\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

Python 3, 36 bytes

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

A variation of Rod's one.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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 "[]"
;
\$\endgroup\$
0
\$\begingroup\$

Clojure, 42 bytes

#(str(apply str(for[c %](str"'"c"':")))[])
\$\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.