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?
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))))