[racket] a small programming exercise

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Thu Oct 14 11:30:51 EDT 2010

On Oct 14, 2010, at 10:57 AM, Justin Zamora wrote:

> Since Shriram seemed to be encouraging cleverness in representation, I
> submit the following solution, which assumes the inputs and outputs
> are in binary.
> (define (benford l)
>   '(1 1.00000))
> Justin
> _________________________________________________
>  For list-related administrative tasks:
>  http://lists.racket-lang.org/listinfo/users

I love this solution but let me supply a solution in ASL, the teaching language: 

;; ASL 
(require racket) ; (only-in ... hash->list)
;; I could have used the key for sort to get around the second lambda 

;; [Listof String] -> [Listof (cons Digit Nat)]
;; compute a frequency count of the leading digit in the number of lon 
;; assume: the digits are positive 
(define (collect lon)
  (local ((define loch (map (compose string->list number->string) lon))
          (define (upd c H) (hash-set H c (+ (hash-ref H c 0) 1)))
          (define hash (foldl (lambda (x H) (upd (first x) H)) #hash() loch))
          (define loh# (hash->list hash))
          (define srtd (sort loh# (lambda (l r) (> (cdr l) (cdr r))))))
    (map (lambda (x) (cons (string->number (string (car x))) (cdr x))) srtd)))

(check-expect (collect '(123 124 125 126 23 24 31))
              (list (cons 1 4) (cons 2 2) (cons 3 1)))

If actual I/O is required, I'd use batch-io to read CSV files and 
display the list above in a batch action. 

Posted on the users mailing list.