Price fraction: Difference between revisions

Content added Content deleted
(Added Maple implementation.)
(→‎{{header|Perl 6}}: Clean up the "chained conditionals" solution, and use `when` instead of the ternary operator.)
Line 2,164: Line 2,164:
}</lang>
}</lang>


Yet another approach is to use the conditional operator to encode the table.
Yet another approach is to use <tt>when</tt> statements to encode the table.
This allows each endpoint to be written once, avoiding duplication. The <tt>Rat()</tt>
This allows each endpoint to be written once, avoiding duplication.

type in the signature coerces any numeric type to a rational.
<lang perl6>sub price_fraction ( Rat() $n where { $^n >= 0 and $^n <= 1 } ) {
<lang perl6>sub price-fraction ($n where 0..1) {
( $n < 0.06 ) ?? 0.10
when $n < 0.06 { 0.10 }
!! ( $n < 0.11 ) ?? 0.18
when $n < 0.11 { 0.18 }
!! ( $n < 0.16 ) ?? 0.26
when $n < 0.16 { 0.26 }
!! ( $n < 0.21 ) ?? 0.32
when $n < 0.21 { 0.32 }
!! ( $n < 0.26 ) ?? 0.38
when $n < 0.26 { 0.38 }
!! ( $n < 0.31 ) ?? 0.44
when $n < 0.31 { 0.44 }
!! ( $n < 0.36 ) ?? 0.50
when $n < 0.36 { 0.50 }
!! ( $n < 0.41 ) ?? 0.54
when $n < 0.41 { 0.54 }
!! ( $n < 0.46 ) ?? 0.58
when $n < 0.46 { 0.58 }
!! ( $n < 0.51 ) ?? 0.62
when $n < 0.51 { 0.62 }
!! ( $n < 0.56 ) ?? 0.66
when $n < 0.56 { 0.66 }
!! ( $n < 0.61 ) ?? 0.70
when $n < 0.61 { 0.70 }
!! ( $n < 0.66 ) ?? 0.74
when $n < 0.66 { 0.74 }
!! ( $n < 0.71 ) ?? 0.78
when $n < 0.71 { 0.78 }
!! ( $n < 0.76 ) ?? 0.82
when $n < 0.76 { 0.82 }
!! ( $n < 0.81 ) ?? 0.86
when $n < 0.81 { 0.86 }
!! ( $n < 0.86 ) ?? 0.90
when $n < 0.86 { 0.90 }
!! ( $n < 0.91 ) ?? 0.94
when $n < 0.91 { 0.94 }
!! ( $n < 0.96 ) ?? 0.98
when $n < 0.96 { 0.98 }
!! 1.00
default { 1.00 }
;
}
}


while prompt("value: ") -> $value {
while prompt("value: ") -> $value {
last if $value ~~ /exit|quit/;
last if $value ~~ /exit|quit/;
say price_fraction(+$value);
say price-fraction(+$value);
}</lang>
}</lang>