Den ons. 20. feb. 2019 kl. 22.25 skrev Dave McDaniel <mcdanield...@gmail.com
>:

> Hello,
>
> I have interest in picking up racket and have done some koans and also
> have been doing the racket track on exercism.
>
> There is a fairly simple exercise called `etl` on exercism related to
> taking a hash for scoring scrabble letters and unpacking it into a flatter,
> more efficient structure for lookups.
>
> The input hash has score as the key and a list of letters of that score as
> the value.  The output is a hash of letter -> score.  One pair per letter
> instead of one pair per score.
>
> It was easy enough to solve with `for-each` using side-effects to update a
> mutable hash, however I think using a generator is a cleaner approach and
> doesn't require mutability.
>

FWIW here is a solution using immutable hashes. I see `for` and friends as
Racket "generators".

/Jens Axel


#lang racket
(require racket/hash)

; In Scrabble each letter gives a certain number of points.
; In the old data we have for each point a list of numbers,
; that awarded the given number of points.

(define old-data
  ; list of associations from point to list of strings (letters)
  '((1  "A" "E" "I" "O" "U" "L" "N" "R" "S" "T")
    (2  "D" "G")
    (3  "B" "C" "M" "P")
    (4  "F" "H" "V" "W" "Y")
    (5  "K")
    (8  "J" "X")
    (10 "Q" "Z")))


; Each point list needs to be transformed to a
; hash table from letters to points.

(define (transform association)
  (match association
    [(list point letters ...)
     (for/hash ([letter letters])
       (values (string-downcase letter) point))]))

; Now we only need to combine the hash lists.
(define ht
  (apply hash-union
       (hash)
       (for/list ([association old-data])
         (transform association))))

(define (lookup letter)
  (hash-ref ht letter #f))

(lookup "e")
(lookup "x")

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to