6

Is there an idiomatic way or a built-in method to concatenate two Sets of strings?

Here's what I want:

> my Set $left = <start_ begin_>.Set
set(begin_ start_)
> my Set $right = <end finish>.Set
set(end finish)
> my Set $left_right = ($left.keys X~ $right.keys).Set
set(begin_end begin_finish start_end start_finish)

Or, if there are more than two of them:

> my Set $middle = <center_ base_>.Set
> my Set $all = ([X~] $left.keys, $middle.keys, $right.keys).Set
set(begin_base_end begin_base_finish begin_center_end begin_center_finish start_base_end start_base_finish start_center_end start_center_finish)
Eugene Barsky
  • 5,780
  • 3
  • 17
  • 40
  • Why would we add a feature that is only used in this one circumstance? Especially since it wouldn't make the code any more clear. One of the design goals is to reduce the number of special cases. I think the best you could hope for is having `X` behave specially if given two Sets so that the `.keys` can be removed. – Brad Gilbert Nov 19 '17 at 20:10
  • What I dislike in my solution is using `.keys`, thus converting `Set` to `Seq`, then concatenating and then returning to `Set`. Maybe I'm wrong of course, and now I'm absolutely happy with the way I do it. :) – Eugene Barsky Nov 19 '17 at 20:19

1 Answers1

10

You can use the reduce function to go from an arbitrary number of sets to a single set with everything concatenated in it:

my Set @sets = set(<start_ begin_>),
               set(<center_ base_>),
               set(<end finish>);
my $result = @sets.reduce({ set $^a.keys X~ $^b.keys });
say $result.perl
# =>
Set.new("start_base_end","begin_center_finish","start_center_finish",
        "start_center_end","start_base_finish","begin_base_end",
        "begin_center_end","begin_base_finish")

That seems clean to me.

timotimo
  • 4,299
  • 19
  • 23
  • 1
    This Xop answer inspired me to write a new example on this repo: https://github.com/dataf3l/perl6-examples/blob/master/p65.p6 I hope this helps whomever is reading about perl6 and learning, perhaps these examples are basic, but who knows, maybe somebody will find them useful :) – Felipe Valdes Nov 22 '17 at 05:23
  • So, what I'm trying to say, Is thank you for your contribution! – Felipe Valdes Nov 22 '17 at 05:23