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

Pages: 1-

Racket

Name: Anonymous 2011-02-06 8:20

I'm new to Racket so as an exercise I decided to port the first example from this book: http://github.com/perl6/book/downloads.

The task is to parse a file which contains the scores of tennis matches and then print the players and their overall results in order of the amount of matches they won, or if some players won the same amount of matches - in order of all sets they won. The first line lists the names of players.

Beth Ana Charlie Dave
Ana vs Dave | 3:0
Charlie vs Beth | 3:1
Ana vs Beth | 2:3
Dave vs Charlie | 3:0
Ana vs Charlie | 3:1
Beth vs Dave | 0:3


Now tell me /prog/, is it good enough or should I read MORE SICP?

#lang racket
(define file (open-input-file "data.txt"))
(define names (regexp-split " " (read-line file)))
(define format (pregexp "(\\w+) vs (\\w+) \\| (\\d+):(\\d+)"))

(define-values (sets matches)
  (for/fold ([sets (hash)] [matches (hash)]) ([line (in-lines file)])
    (match-let* ([(list _ p1 p2 r1 r2) (regexp-match format line)]
                 [(list r1 r2) (map string->number (list r1 r2))])
      (values (hash-update (hash-update sets p1 (curry + r1) 0) p2 (curry + r2) 0)
              (hash-update matches (if (> r1 r2) p1 p2) add1 0)))))

(let ([sorted (sort (sort names #:key (curry hash-ref sets) >)
                    #:key (curry hash-ref matches) >)])
  (for ([n (in-list sorted)])
    (printf "~a has won ~a matches and ~a sets\n"
            n (hash-ref matches n) (hash-ref sets n))))

Name: Anonymous 2011-02-06 8:29

>>1
Wait for Doctor Racket.

But ``for'' considered harmful, (sort (sort considered what the fuck.

Name: Doctor Racket !RACKET/.HY 2011-02-06 9:03

>>2
Actually, his code is good, and the (sort (sort makes sense. Maybe too much over engineered, but showed he knows his tools.

>>1
Congratulations, I'd never say that's code from a beginner. My only suggestion is to not abuse of fors for iteration when possible, it's just not idiomatic.
If you need something to read, take a look to HtDP (http://www.htdp.org/)

Name: Anonymous 2011-02-06 9:56

(sort (sort
Nice.

I spring a boner every time someone mentions Racket.
Is this normal?

Name: Anonymous 2011-02-06 10:11

Name: Doctor Racket !RACKET/.HY 2011-02-06 10:46

>>4
You should see a doctor.

>>5
file->bytes
I needed that, thank you.

Name: Anonymous 2011-02-06 11:48

(sort (sort
In Python, I'd normally make the temporary key as key=lambda x: (x.sets, x.matches). Wouldn't that be preferable here, too?

Name: Anonymous 2011-02-06 19:00

>>7
Er, except opposite, of course.

Name: Anonymous 2011-02-07 1:27

Pretty cool, although that double sort is a bit funny.

Name: Anonymous 2011-02-07 6:01

>>9
double sort
A new sorting algorithm?

Name: Anonymous 2011-02-18 13:47

<-- check 'em dubz
Don't change these.
Name: Email:
Entire Thread Thread List