[racket] Challenge: <impressive function> in 140 chars or less

From: Neil Toronto (neil.toronto at gmail.com)
Date: Thu Feb 23 13:43:48 EST 2012

On 02/23/2012 11:04 AM, Robby Findler wrote:
>> >
>> >  (define (r n)
>> >    (for/fold ([s 1] [l '()]) ([i n])
>> >      (values (/ 1 (- (* 2 (floor s)) s -1)) (cons s l))))
>> >
>> >  I tweeted this to make sure it fit. I had 23 characters to spare, could
>> >  squeeze a bit of whitespace out, then use the rest to make it more elegant,
>> >  but I have actual work to do... --PR
> What is this thing? It seems coolly symmetric in this view:
>
> (require plot)
> (plot (points (let-values ([(n l) (r (expt 2 12))])
>                  (for/list ([i (in-naturals)]
>                             [x (in-list l)])
>                    (vector i x)))))

I thought it looked like some kind of ruler that way, leading me to 
Thomae's function... but it's not quite. (Thomae's function assigns a 
rational number to each rational, and 0 to each irrational.) But there's 
something about rationals here...

I think it's enumerating all the positive rational numbers. Look at the 
list in reverse: (1 1/2 2 1/3 3/2 2/3 3 1/4 4/3 3/5 ...).


#lang racket

(require plot)

(define (r n)
   (for/fold ([s 1] [l '()]) ([i n])
     (values (/ 1 (- (* 2 (floor s)) s -1)) (cons s l))))

(define (rational->vector q)
   (vector (numerator q) (denominator q)))

(define (r-vectors n)
   (define-values (_ l) (r n))
   (map rational->vector l))

(plot (lines (r-vectors (expt 2 10)) #:x-max 100 #:y-max 100))
(plot (lines (r-vectors (expt 2 12)) #:x-max 100 #:y-max 100))


Neil ⊥

Posted on the users mailing list.