2010/8/10 Alan <a...@malloys.org>:
> I have the following function as part of a card-game system I'm
> developing:
>
> (defn make-suit
>  [suit owner ranks]
>    {suit (map (partial struct-map card
>                        :suit suit
>                        :owner owner
>                        :rank)
>                ranks)})
>
> (make-suit :spade :west [9 5]) yields
>
> {:spade
>  ({:suit :spade, :owner :west, :rank 9}
>   {:suit :spade, :owner :west, :rank 5})}
>
> which is exactly what I want. But I have failed countless times to
> define a make-hand function - I'd like to be able to call (make-
> hand :west {:spade [9 5], :club [10]}) and get back
>
> {:spade
>  ({:suit :spade, :owner :west, :rank 9}
>  {:suit :spade, :owner :west, :rank 5}),
>  :club
>  ({:suit :club, :owner :west, :rank 10})}
>
> Can someone put me on the right track? I'm sure the solution for this
> is trivially simple but I can't quite find it.
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clojure@googlegroups.com
> Note that posts from new members are moderated - please be patient with your 
> first post.
> To unsubscribe from this group, send email to
> clojure+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
>

My attempt:

  (defn make-hand [owner cards]
    (into {} (for [[suit ranks] cards]
               [suit (for [rank ranks]
                       {:suit suit
                        :owner owner
                        :rank rank})])))

Notice that a sequence of a map is a sequence of its [key value]
pairs. The keys are in this case the suits and the values which ranks
of that suits that should be included. To generate a map, it is often
useful to make [key value] pars and conj them into an empty map using
'into'. The generated map has the suits as its key, and for each suit
the ranks are looped over. A card map, including suit, rank and owner
is generated for each rank. The "current" suit and owner is accessed
through the for body's closure.

// raek

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to