[plt-dev] Racket web page

From: Ryan Culpepper (ryanc at ccs.neu.edu)
Date: Wed May 26 13:17:50 EDT 2010


On 05/26/2010 10:32 AM, Carl Eastlund wrote:
> On Wed, May 26, 2010 at 10:27 AM, Matthias Felleisen
> <matthias at ccs.neu.edu> wrote:
>>
>> On May 25, 2010, at 8:48 PM, Matthew Flatt wrote:
>>
>>> #lang racket
>>> ;; Report each unique line from stdin:
>>> (let ([saw (make-hash)])
>>>   (for ([line (in-lines)])
>>>     (unless (hash-ref saw line #f)
>>>       (displayln line))
>>>     (hash-set! saw line #t)))
>>
>> I would prefer to sacrifice one line to avoid the repetition of
>> the test (leakage). I doubt Perl and friends do that:
>>
>> #lang racket
>> ;; Report each unique line from stdin:
>> (define saw (make-hash))
>> (for ([line (in-lines)])
>>  (hash-ref saw line
>>    (lambda ()
>>      (displayln line)
>>      (hash-set! saw line #t))))
> 
> To anyone who isn't intimately familiar with hash-ref, both versions
> are kind of obscure; the second one more so.  [...]

I agree. I think tricks with hash-ref and hash-ref! are too subtle for
bite-size examples. Why not use sets instead of hash tables?

#lang racket
;; Report each unique line from stdin:
(void
 (for/fold ([seen (set)]) ([line (in-lines)])
   (unless (set-member? seen line)
     (displayln line))
   (set-add seen line)))

or

#lang racket
;; Report each unique line from stdin:
(let ([seen (set)])
  (for ([line (in-lines)])
    (unless (set-member? seen line)
      (displayln line)
      (set! seen (set-add seen line)))))

Ryan


Posted on the dev mailing list.