Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

basic C

Name: Anonymous 2010-11-24 12:17

can you help create a program that will accept an amount and output its denomination.

example

amount: 5670.45

1000: 5
500: 6
200: 0
100: 6
50: 1
20: 1
10: 0
.25: 1
.05: 3

Name: Anonymous 2010-11-24 21:59

>>19
Sure.

.reduce is a list method which takes a coderef. Each pass it eats &code.arity (here 2) elements from a copy of the list, and puts the return value back onto the head of the copy. It does this until there's only one element left in the list copy, which is the reduced answer. So @list.reduce({$^a+$^b}); is the same as a simple summation reduction, [+] @list; ($^a etc simply introduce $a as the a-th argument and can be used to calculate arity.)

The logic in the closure is to propagate the first element as the amount (less the value of denominations printed out) down the list until it runs out of denominations. So, in reduce, the head is always the current $amt, and the tail is the list of remaining denominations to be evaluated. (If a denomination is greater than the amount, $x remains at zero, so $a (the current amount) is propagated unaltered.)

In this code "return" can't be used because the closure will return from the enclosing context so implicit returns (which are different) are used instead. A sub could have been used instead, and returns would have been okay. (IIRC there's also a keyword which will do the same as the implicit return in this case.)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List