[plt-dev] Racket web page

From: Eli Barzilay (eli at barzilay.org)
Date: Tue May 25 15:30:49 EDT 2010

On May 25, Carl Eastlund wrote:
> On Thu, May 20, 2010 at 4:31 PM, Matthew Flatt <mflatt at cs.utah.edu> wrote:
> >
> > We'd like to have more 7-line programs for the middle slideshow, so
> > please contribute.
> 
> Command line tool to simulate rolling M dice with N sides each, for
> each input of the form "MdN":
> 
> #lang racket
> (for ([s (current-command-line-arguments)])
>   (match (regexp-match #px"(\\d+)d(\\d+)" s)
>     [(list _ (app string->number m)
>              (app string->number n))
>      (for ([i (in-range m)])
>        (printf "~a\n" (+ 1 (random n))))]))

Does it help to use `app'?  (It shows off a feature, but an obscure
one...)

Anyway, you would obviously be too focused on the game to sum up your
7d20:

  #lang racket
  (for ([s (current-command-line-arguments)])
    (match s
      [(regexp #px"(\\d+)d(\\d+)" (list _ m n))
       (let ([rolls (for/list ([i (in-range (string->number m))])
                      (+ 1 (random (string->number n))))])
         (printf "~s => ~a\n" rolls (apply + rolls)))]))

It's a really nice idea, IMO -- tempting to extend to a full dice app
thing.  How about adding a delta:

  #lang racket
  (for ([s (current-command-line-arguments)])
    (match s
      [(regexp #px"(\\d+)d(\\d+)([+-]\\d+)?" (list _ m n d))
       (let ([rolls (for/list ([i (in-range (string->number m))])
                      (+ 1 (random (string->number n))))])
         (printf "~s~a => ~a\n" rolls (or d "")
                 (apply + (string->number (or d "0")) rolls)))]))

Or just make it into a language (except that Scheme took away the NdN
syntax):

  #lang racket
  (provide (except-out (all-from-out racket) #%top)
           (rename-out [top #%top]))
  (define (roll m n d)
    (for/fold ([s (or d 0)]) ([i (in-range m)]) (+ s 1 (random n))))
  (define-syntax (top stx)
    (syntax-case stx ()
      [(_ . id)
       (identifier? #'id)
       (let ([m (regexp-match #px"(\\d+)dd(\\d+)([+-]\\d+)?"
                              (symbol->string (syntax->datum #'id)))])
         (if m
           (with-syntax ([(m n d) (map (lambda (s) (and s (string->number s)))
                                       (cdr m))])
             #'(roll m n d))
           #'(#%top . id)))]))

  #lang s-exp "that"
  (list 1dd10 10dd10)


-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                    http://barzilay.org/                   Maze is Life!


Posted on the dev mailing list.