Rebol3 Code Examplex


Fractran

Execute Conway’s FRACTRAN list-processing arithmetic language.

Rebol [
    title: "Rosetta code: Fractran"
    file:  %Fractran.r3
    url:   https://rosettacode.org/wiki/Fractran
]

fractran: function/with [
    input [string! file! url!]
    start [integer!]
    terms [integer!]
][
    unless string? input [ input: read/string input ]
    ;; --- parse fractions into [numerator denominator] pairs ---
    fractions: parse input [collect [fraction some [separator fraction]]]
    ;; --- interpreter loop ---
    out: append copy [] n: start
    while [terms > length? out] [
        forall fractions [
            frac: fractions/1
            if zero? mod n frac/y [         ;; fraction applies: n is divisible
                n: n / frac/y * frac/x      ;; advance: multiply n by fraction
                append out to integer! n    ;; keep the result
                fractions: head fractions   ;; restart from first fraction
                break
            ]
            if tail? fractions [return out] ;; no fraction applied: halt
        ]
    ]
    out
][
    digit:     charset "0123456789"
    fraction:  [copy p [some digit] #"/" copy q [some digit] keep (as-pair to integer! p to integer! q)]
    separator: [some #" "]
]

print "First 100 terms of the sequence:"
out: fractran "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" 2 100
forall out [
    prin pad out/1 9
    if zero? mod index? out 10 [print ""]
]

Output:

First 100 terms of the sequence:
2        15       825      725      1925     2275     425      390      330      290      
770      910      170      156      132      116      308      364      68       4        
30       225      12375    10875    28875    25375    67375    79625    14875    13650    
2550     2340     1980     1740     4620     4060     10780    12740    2380     2184     
408      152      92       380      230      950      575      2375     9625     11375    
2125     1950     1650     1450     3850     4550     850      780      660      580      
1540     1820     340      312      264      232      616      728      136      8        
60       450      3375     185625   163125   433125   380625   1010625  888125   2358125  
2786875  520625   477750   89250    81900    15300    14040    11880    10440    27720    
24360    64680    56840    150920   178360   33320    30576    5712     2128     1288