On Wed, Feb 20, 2019 at 4:25 PM Dave McDaniel <[email protected]>
wrote:
> 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. In python using generators would be very
> straightforward:
>
>
>
Generators are a common tool in Python, but not in Racket. (I've written a
lot of Racket code over many years and have used generators, I think, once.)
I'd do this as a fold over the input hash:
===
#lang racket/base
(define mixed-case-input
(hash 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")))
(define (reverse-hash h)
(for*/fold ([result (hash)])
([(score letters) (in-hash h)]
[letter (in-list letters)])
(hash-set result letter score)))
===
All of the `for*` operations do nested iteration (as opposed to the `for`
operations without the asterisk, where sequences are iterated in parallel).
So, in this case, we get each `(score letters)` pair fro the hash, and for
each of those, we iterate over the list of letters. On each iteration,
we're updating our accumulator (`result`). The result of the whole
expression is the final value of the accumulator.
- Jon
--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.