Baseball Scores
May 19, 2015
We’ve done this exercise before, writing a program that gets a weather forecast, and we steal the code to fetch a url from that exercise. We also use string-split
and string-find
from the Standard Prelude, and we write a perfectly awful string-replace
(it has quadratic performance, but a proper implementation would be linear — even so, it is dead simple and sufficient for the task at hand) that you can see at ideone. Given all that, we need only two functions to get Cardinals’ baseball scores: parse-mlb-lines
fetches the scores from ESPN’s BottomLine API into a list, and cardinals
extracts the Cardinals’ score from that report:
(define (parse-mlb-lines)
(let ((lines #f))
(with-input-from-url
"http://sports.espn.go.com/mlb/bottomline/scores"
(lambda ()
(let loop ((xs (list)))
(if (not (eof-object? (peek-char)))
(loop (cons (read-char) xs))
(set! lines (list->string (reverse xs)))))))
(map (lambda (xs) (list (car xs) (string-replace (cadr xs) "%20" " ")))
(map (lambda (s) (string-split #\= s))
(map (lambda (s) (substring s 6 (string-length s)))
(cdr (string-split #\& lines)))))))
(define (cardinals)
(let loop ((lines (parse-mlb-lines)))
(when (pair? lines)
(if (not (string-find "St. Louis" (cadar lines)))
(loop (cdr lines))
(let ((num (substring (caar lines) 4
(string-length (caar lines)))))
(let loop ((lines lines))
(when (not (string=? (caar lines)
(string-append "right" num "_count")))
(display (cadar lines)) (newline)
(loop (cdr lines)))))))))
Here’s a sample:
> (cardinals)
St. Louis 0 NY Mets 0 (TOP 2ND)
You can see all the code assembled at http://ideone.com/ErWtao.
Heres How I did it, Kinda I thought this was cool so I tried it on the leader boards for a game I like to play with some friends, But I don’t think I did as well as it could be or like the example did since i’m only 19.