The Squirrel interpreter. See http://www.squirrel-lang.org/
samples/generators.nut@3:7268a3ceaffc, 2014-12-16 (annotated)
- Committer:
- jhnwkmn
- Date:
- Tue Dec 16 11:39:42 2014 +0000
- Revision:
- 3:7268a3ceaffc
- Parent:
- 0:97a4f8cc534c
Accepts \r as line terminator as well.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
jhnwkmn | 0:97a4f8cc534c | 1 | /* |
jhnwkmn | 0:97a4f8cc534c | 2 | *Random number function from The Great Computer Language shootout |
jhnwkmn | 0:97a4f8cc534c | 3 | *converted to a generator func |
jhnwkmn | 0:97a4f8cc534c | 4 | */ |
jhnwkmn | 0:97a4f8cc534c | 5 | |
jhnwkmn | 0:97a4f8cc534c | 6 | function gen_random(max) { |
jhnwkmn | 0:97a4f8cc534c | 7 | local last=42 |
jhnwkmn | 0:97a4f8cc534c | 8 | local IM = 139968; |
jhnwkmn | 0:97a4f8cc534c | 9 | local IA = 3877; |
jhnwkmn | 0:97a4f8cc534c | 10 | local IC = 29573; |
jhnwkmn | 0:97a4f8cc534c | 11 | for(;;){ //loops forever |
jhnwkmn | 0:97a4f8cc534c | 12 | yield (max * (last = (last * IA + IC) % IM) / IM); |
jhnwkmn | 0:97a4f8cc534c | 13 | } |
jhnwkmn | 0:97a4f8cc534c | 14 | } |
jhnwkmn | 0:97a4f8cc534c | 15 | |
jhnwkmn | 0:97a4f8cc534c | 16 | local randtor=gen_random(100); |
jhnwkmn | 0:97a4f8cc534c | 17 | |
jhnwkmn | 0:97a4f8cc534c | 18 | print("RAND NUMBERS \n") |
jhnwkmn | 0:97a4f8cc534c | 19 | |
jhnwkmn | 0:97a4f8cc534c | 20 | for(local i=0;i<10;i+=1) |
jhnwkmn | 0:97a4f8cc534c | 21 | print(">"+resume randtor+"\n"); |
jhnwkmn | 0:97a4f8cc534c | 22 | |
jhnwkmn | 0:97a4f8cc534c | 23 | print("FIBONACCI \n") |
jhnwkmn | 0:97a4f8cc534c | 24 | function fiboz(n) |
jhnwkmn | 0:97a4f8cc534c | 25 | { |
jhnwkmn | 0:97a4f8cc534c | 26 | local prev=0; |
jhnwkmn | 0:97a4f8cc534c | 27 | local curr=1; |
jhnwkmn | 0:97a4f8cc534c | 28 | yield 1; |
jhnwkmn | 0:97a4f8cc534c | 29 | |
jhnwkmn | 0:97a4f8cc534c | 30 | for(local i=0;i<n-1;i+=1) |
jhnwkmn | 0:97a4f8cc534c | 31 | { |
jhnwkmn | 0:97a4f8cc534c | 32 | local res=prev+curr; |
jhnwkmn | 0:97a4f8cc534c | 33 | prev=curr; |
jhnwkmn | 0:97a4f8cc534c | 34 | yield curr=res; |
jhnwkmn | 0:97a4f8cc534c | 35 | } |
jhnwkmn | 0:97a4f8cc534c | 36 | return prev+curr; |
jhnwkmn | 0:97a4f8cc534c | 37 | } |
jhnwkmn | 0:97a4f8cc534c | 38 | |
jhnwkmn | 0:97a4f8cc534c | 39 | foreach(val in fiboz(10)) |
jhnwkmn | 0:97a4f8cc534c | 40 | { |
jhnwkmn | 0:97a4f8cc534c | 41 | ::print(">"+val+"\n"); |
jhnwkmn | 0:97a4f8cc534c | 42 | } |