Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl6-ish expression for the bits of an integer

Tags:

raku

I've been trying to exercise my Perl 6 chops by looking at some golfing problems. One of them involved extracting the bits of an integer. I haven't been able to come up with a succinct way to write such an expression.

My "best" tries so far follow, using 2000 as the number. I don't care whether the most or least significant bit comes first.

A numeric expression:

map { $_ % 2 }, (2000, * div 2 ... * == 0)

A recursive anonymous subroutine:

{ $_ ?? ($_ % 2, |&?BLOCK($_ div 2)) !! () }(2000)

Converting to a string:

2000.fmt('%b') ~~ m:g/./

Of these, the first feels cleanest to me, but it would be really nice to be able to generate the bits in a single step, rather than mapping over an intermediate list.

Is there a cleaner, shorter, and/or more idiomatic way to get the bits, using a single expression? (That is, without writing a named function.)

like image 764
Sean Avatar asked Dec 06 '16 18:12

Sean


1 Answers

The easiest way would be:

2000.base(2).comb

The .base method returns a string representation, and .comb splits it into characters - similar to your third method.

like image 169
smls Avatar answered Sep 17 '22 19:09

smls