Pokerface value
This post came from a short-lived blog I tried to run (tail-recursion.net) where I wanted to write up a short bit of code I'd written that week.
I was working through "120-hour epic sax marathon", a Clojure MOOC, and I had to solve a problem that relied on Clojure's Lisp-1 properties.
The problem given was:
Write the function (value hand), which returns the value of a hand according to the table [below].
; (value high-seven) ;=> 0
; (value pair-hand) ;=> 1
; (value two-pairs-hand) ;=> 2
; (value three-of-a-kind-hand) ;=> 3
; (value straight-hand) ;=> 4
; (value flush-hand) ;=> 5
; (value full-house-hand) ;=> 6
; (value four-of-a-kind-hand) ;=> 7
; (value straight-flush-hand) ;=> 8
Here is my solution:
(defn value [hand]
Checkers is a set of check pairs. Each of the functions
high-card?, pair?, ... is a function that, given a hand,
returns true if the cards passed in satisfies this hand.
(let [checkers #{[high-card? 0] [pair? 1]
[two-pairs? 2] [three-of-a-kind? 3]
[straight? 4] [flush? 5]
[full-house? 6] [four-of-a-kind? 7]
[straight-flush? 8]}]
(apply max
(sort
The map runs through each checker, getting the value of
the first element in the pair (a function); if there is a
match, return the score indicated by the second
element. Otherwise, return a -1 to score this less than the
lowest-scoring hand.
(map (fn [checker]
(if ((first checker) hand)
(second checker)
-1))
checkers)))))