Test integerness: Difference between revisions

Content added Content deleted
m (→‎version 1a Extra Credit: corrected two misspellings (of is'nt).)
m (→‎{{header|Perl 6}}: Combine into a single file for ease of testing)
Line 1,695:
In Perl 6, all numeric types have a method called <tt>narrow</tt>, which returns an object with the same value but of the most appropriate type. So we can just check if ''that'' object is an <tt>Int</tt>. This works even with floats with large exponents, because the <tt>Int</tt> type supports arbitrarily large integers.
 
For the extra credit task, we can add another multi candidate that checks the distance between the number and it's nearest integer, but then we'll have to handle complex numbers specially:.
<lang perl6>multi is-int ($n) { $n.narrow ~~ Int }</lang>
 
<lang perl6>multi is-int ($n) { $n.narrow ~~ Int }</lang>
For the extra credit task, we can add another multi candidate that checks the distance between the number and it's nearest integer, but then we'll have to handle complex numbers specially:
 
<lang perl6>multi is-int ($n, :$tolerance!) {
abs($n.round - $n) <= $tolerance
}
 
multi is-int (Complex $n, :$tolerance!) {
is-int($n.re, :$tolerance) && abs($n.im) < $tolerance
}
}</lang>
 
# Testing:
 
<lang perl6>for 25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, Inf, NaN, 5.0+0.0i, 5-5i {
printf "%-7s %-9s %-5s %-5s\n", .^name, $_,
is-int($_),