How to insert separators between columns?

Clash Royale CLAN TAG#URR8PPPHow to insert separators between columns?
I have columns in @columns:
@columns
my @columns =('column1', 'column2', 'column3');
and I have separators in @separators:
@separators
my @separators = (',', '|');
I want to insert the separators between columns, one by one:
column1,column2|column
my solution is:
(@columns »~» (|@separators,"")).join("")
Here I have three columns and two separators, and how about insert N-1 separators between N columns?
N-1
N
say ((@columns Z @separators), @columns[*-1]).flat.join("")
@HåkonHægland Thanks, have fixed the typo ^_^
– chenyf
15 hours ago
Do mean the case that
N is different from @columns.elems?– Håkon Hægland
15 hours ago
N
@columns.elems
@HåkonHægland
N is equal to @columns.elems, also equal to @separators.elems +1 – chenyf
15 hours ago
N
@columns.elems
@separators.elems +1
But doesn't your proposed solution already work fine for that case?
– Håkon Hægland
15 hours ago
2 Answers
2
Assuming that @separators has the right number of values, you could use roundrobin.
@separators
roundrobin
roundrobin( @columns, @separators ).flat.join()
So this should work for a any length of @columns or @separators :
@columns
@separators
First we use the >>,>> hyper operator to make a list of lists.
>>,>>
(@columns >>,>> @separators)
(@columns >>,>> @separators)
Which gives :
[("column1", ","), ("column2", "|"), ("column3", ",")]
[("column1", ","), ("column2", "|"), ("column3", ",")]
Then we flatten this into a single list using a slip.
(@columns >>,>> @separators).map( |* )
(@columns >>,>> @separators).map( |* )
Which gives:
("column1", ",", "column2", "|", "column3", ",").Seq
("column1", ",", "column2", "|", "column3", ",").Seq
Then we get the array of all but the last value :
(@columns >>,>> @separators).map(|*).head(*-1)
(@columns >>,>> @separators).map(|*).head(*-1)
For :
("column1", ",", "column2", "|", "column3")
("column1", ",", "column2", "|", "column3")
And finally join it with nothing :
(@columns >>,>> @separators).map(|*).head(*-1).join("")
(@columns >>,>> @separators).map(|*).head(*-1).join("")
Final result :
column1,column2|column3
column1,column2|column3
Changing the number of columns or separators will not make a difference.
I think
[^(*-1)] would be clearer if written as .head(*-1)– Brad Gilbert
12 hours ago
[^(*-1)]
.head(*-1)
Good point. Fixed it.
– Scimon
2 mins ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You could try
say ((@columns Z @separators), @columns[*-1]).flat.join("")– Håkon Hægland
15 hours ago