Perl 6: 17
The first thing that comes to mind is
[+] 1337.base(2).comb; # returns 6
Although this doesn't have any arbitrary limits ( the only limits are how much memory you have, and how long you are willing to wait )
[+] ( uint64.Range.max * 2 + 1 ).base(2).comb; # returns 65
# 340282366920938463463374607431768211455
my $uint128-max = :2( 1 x 128 );
[+] $uint128-max.base(2).comb; # returns 128
my $uint8192-max = :2( 1 x 8192 ); # 2467 digit Int
[+] $uint8192-max.base(2).comb; # returns 8192 (takes about a second currently)
Without making it into a Callable the shortest way to write this is to put the Int into the "default" variable $_
. ( .method
is always short for $_.method
)
$_ = 1337;
[+] .base(2).comb;
given 1337 { # Perl6's with/switch statement
[+] .base(2).comb
}
[+] .base(2).comb given 1337; # ditto
if 1337 -> $_ { # pointy block
[+] .base(2).comb
}
If you want to create a Callable you could just put it into a Block.
my $code-ref = {[+] .base(2).comb};
# if it is called with an argument it places it in $_
# if called without an argument uses the $_ from an outer scope
If you really want to call it as a normal subroutine:
my &f={[+] .base(2).comb}; # sub f($_){[+] .base(2).comb}
say f 1337; # 6
$_ = 1337;
say f; # 6
Based on your requirements I'd guess that the answer you are looking for is:
[+] .base(2).comb
This assumes that the value is already in $_
. It would most likely be the last statement in a subroutine, the right side of an assignment, or an argument to a subroutine or method. ( Otherwise it calculates the result only to throw it away, unless the compiler notices that the result is unused )
In case you were wondering [+] 1, 2, 3
can be considered short for (1,2,3).reduce(&[+])
.
Where &[+]
is short for &infix:< + >
the collection of multi subs available in the current scope that are responsible for the numerical infix addition operator +
.