Flabber. Gasted.
The previous post got a LOT of attention: constructive criticism (yay!), confusion, doubt, and even vivid scorn. After a LOT of thinking I think it's worth taking a new look at the way I blog.
Reviewing the technical flaws of the previous post will have to wait -- my broader personal flaws will do for now.
Before Web 2.0 brought rounded corners and AJAX I blogged at LiveJournal. Eventually one of my programmer acquaintances politely suggested I find a new place for some of the nerdier stuff. After overreacting for a few days, I finally saw the logic and created a blog where I could nerd out shamelessly: foognostic.
Six years later LiveJournal has given way to WordPress. I'm still using Emacs but finally I have found a Lisp I want to learn. It will be a slow painful process, but I don't really care. Clojure is the language I want to use for its own sake.
If people are going to pay attention at random times then these posts need to be more specific and narrowly focused. Code samples with explanations do not trump rambling generalizations and lack of focus.
Thanks for reading alllll the way down here. I'll buy you a beer tomorrow!
The path of least resistance in Clojure
(Edit 2: Standard disclaimer: Clojure is a new hobby.)
Immutable data structures seem like an odd idea, but they are on the path of least resistance in Clojure. This is not the case in languages like Java. In this post I will rewrite a snippet of Java into Clojure and explain the major differences.
The snippet of Java comes from Martin Fowler's bliki posting on Fluent Interfaces. I picked this code snippet because it is concise, reads easily, and fills a common need.
customer.newOrder()
.with(6, "TAL")
.with(5, "HPK").skippable()
.with(3, "LGV")
.priorityRush();
}
This code clearly links an existing customer to a new, rush order of three items. Consider the "skippable" method... that is probably on the Order object yet works on an OrderLine. The Order code probably finds the newest OrderLine and updates its skippable property. Modifying objects is the path of least resistance in Java, or rather creating objects in an incomplete state and updating them until complete.
Modifying objects in Clojure is not on the path of least resistance. Many Clojure methods return a new, lazy version of the input. Working with return values like this encourages creating complete objects and then using them. Here's an example -- please temporarily ignore the unfamiliar functions and low level of abstraction.
(let [lines [(struct order-line 6, "TAL")
(struct-map order-line :quantity 5,
:code "HPK", :skippable? true)
(struct order-line 3, "LGV")]
order (struct-map order :lines lines,
:rush? true)]
(merge customer
{:orders (conj (get customer
:orders []) order)})))
- (struct foo 123 "abc") is basically calling the constructor for the foo class with two arguments.
- (struct-map foo :num 123, :text "abc") calls the constructor with named params rather than positional params
- (let) is how you define local variables, lines and order in the above example.
- (merge old-map new-map) creates a new map by merging existing maps
- (conj) creates a new collection from its arguments
- (get) returns the value for a key in a hash map, or a default value if specified.
It's not obvious but the return value is the output from (merge). That is the last statement in the (let) block, which is the only statement in the body of the (add-order) function. Values flowing like this is in the path of least resistance in Clojure.
Besides doing things in a different order than Java, there is one more very important but subtle difference. Let's say a customer wants two orders:
Some quick code to show how it works:
(def me (add-order (struct customer "seth")))
;; how many orders?
(count (me :orders)) ;; 1
;; I'd like another order, please...
(add-order me)
;; Hey, where'd that go?
(count (me :orders)) ;; 1
;; Is the function even working?
(count (:orders (add-order me))) ;; 2, so yes
The new order has been lost because the return value from the function was not captured. This is a silent runtime failure -- not a fun type of problem to chase down. One solution is to rebind "me":
(count (me :orders)) ;; 2
I've been a little dishonest here talking about "objects" in Clojure. As seen here they are little different than hash maps.
clojure.lang.PersistentArrayMap
example> (defstruct foo :bar)
#'example/foo
example> (. (struct foo) getClass)
clojure.lang.PersistentStructMap
For anyone who is interested, the entire source listing for this example follows. Thanks for reading!
Announcing Pokerepl
Standard disclaimer: Clojure is a new hobby.
Clojure code to perform a very little bit of Texas Hold'em has been uploaded to BitBucket. Fire up a REPL and paste in the contents of poker.clj, then try it out with something like:
BitBucket supports Mercurial. If it's installed, here's the clone URL: hg clone https://seths@bitbucket.org/seths/pokerepl/
Otherwise, here's a quick link to a bz2 of the source. This link will only ever get the first version of the code... so consider installing Mercurial or hitting the project page.
Much work remains to make this code interactive.
- A little more work on judging hands (identifies groups but not by suit)
- Add support for chips
- Add support for checking, calling, raising
- Add support for folding
- BIG: very simplistic logic for having CPU players bet/call/fold
- VERY BIG: Rewrite most of everything with agents and refs in order to...
- HUGE: Support network based play with real people
Lastly, this is my first foray into the functional fray so don't spare the code reviews. PLEASE. Fork it mercilessly!
More poker with Clojure: what’s in a hand?
Standard disclaimer: Clojure is a new hobby.
In a previous post I wrote some code to create and shuffle a deck of cards. This post demonstrates one way to figure out what a hand is worth according to basic 5 card draw rules.
The implementation is basically one switch statement from a C/Java/Ruby/Groovy/Python perspective. Ruby and Groovy coders will recognize that the return value of the function is the value of the last expression evaluated. So an if statement returns either the value of the true expression or the value of the false expression.
"good, 1 < 2 < 3"
"what? someone file a bug report!")
;; "good, 1 < 2 < 3"
When conditional logic returns values like this, there is no need to use a stack variable to store a return value.
A quick introduction to some of the functions used in the code:
- (if): Aside from returning its true/false expression result, no major difference than Java.
- (cond): Basically a switch statement, returning a value just like (if)
- (let): Defines and initializes "variables" which are immutable.
- #(): This defines an anonymous function. Believe this is a macro for (fn).
- #{}: This defines a set data structure; unordered and no duplicates. Also see the (set). function
- {}: This defines a map data structure, populated with unordered key/value pairs. Bonus: (map key) AND (key map) both return the value for key in a map.
With some minimal descriptions listed, let's dig into the code:
When judging a hand it's critical to know how many of each suit are present AND how many of each value are present. One way to model this is to build histograms for suit and value.
(take 5 (shuffle deck))
:suit
suits)
;; {:clubs 2, :diamonds 2, :spades 0, :hearts 1}
(build-property-histogram
(take 5 (shuffle deck))
:name
names)
;; {:queen 2, :king 1, :jack 0, :seven 1, :eight 0,
;; :six 0, :nine 0, :five 0, :ace 0, :ten 0, :three 1,
;; :two 0, :four 0}
The implementation behind that is not an easy read (probably because it's not great Clojure). Basically this code iterates over the pool of attributes (suits or values) and uses (conj) to aggregate maps into one big map. In the middle a filter function finds all cards matching the current property and then the total number is counted up.
(reduce
(fn [sieve value]
(conj sieve
{ value
(count (filter
(fn [card] (= value (card property-name)))
cards)) }))
{}
property-pool))
Only one more helper method to go. This method determines whether the hand is a straight, whether all of its cards have consecutive values. The approach taken was a little odd. An array of all possible straight values is built and then segmented into overlapping hands. For example, the first two arrays would be [ace, two, three, four, five] and [two, three, four, five, six]. Each of these possibilities is matched against the hand, using Clojure's facility to compare sets easily.
(some
(fn [straight] (= (set (map :name hand)) (set straight)))
(partition 5 1 [:ace, :two, :three, :four, :five, :six, :seven, :eight,
:nine, :ten, :jack, :queen, :king, :ace])))
(some) is a function which returns true when its filter function returns true for any of the collection items it examines.
After all that, here is the hand judging function. It's basically a few local "variables" and a switch statement. Some additional conditional logic appears inside the switch statement as well. This is required to determine whether a hand with three of a kind is a full house (are the remaining cards a pair?).
(let [suit-histo (build-property-histogram cards :suit suits)
value-histo (build-property-histogram cards :name names)
max-per-suit (apply max (vals suit-histo))
max-per-value (apply max (vals value-histo))]
(cond
(= 4 max-per-value)
:quads
(= 3 max-per-value)
(if (some #(= 2 %) (vals value-histo))
:full-house
:trips)
(= 2 max-per-value)
(if (< 1 (count (filter #(= 2 %) (vals value-histo))))
:two-pair
:pair)
(and (straight? cards) (> 5 max-per-suit))
:straight
(and (not (straight? cards)) (= 5 max-per-suit))
:flush
(= 5 max-per-suit)
(if (= #{:ace, :king, :queen, :jack, :ten} (set (map :name cards)))
:royal-flush
:straight-flush)
true
:high-card)))
In the near future all this code will be cleaned up and moved out to BitBucket. Ideally some basic chip tracking and logic would be added so you could actually play poker from a REPL. That's probably much more difficult than it seems, but hopefully this has been useful so far. Please don't hesitate to contact me (goof at foognostic dot net) with any questions!
Shuffling cards with Clojure
Standard disclaimer: Clojure is a new hobby.
One of my friends and coworkers has been gently cluesticking me into learning poker. Along the way he suggested I write a very simple hand generator to get a feel for how the number of players changes the relative strength of your hole cards. Shuffling cards is one small step along the way, and that seemed like a good place to start.
First, let's create a poker namespace to work in and then define some basic constants as keywords in sets.
(def suits #{:hearts, :diamonds, :clubs, :spades})
(def names #{:two, :three, :four, :five, :six,
:seven, :eight, :nine, :ten, :jack,
:queen, :king, :ace})
Next, let's "define a class." I'm quoting that because a struct in Clojure is just a map with some keys to be expected.
Next we actually need, you know, a full deck of cards to shuffle. This was harder than I expected. At first I tried two loops, first iterating over suits and then values. This resulted in a list of ... four lists of... thirteen cards.
(map (fn [suit]
(map (fn [name]
(struct card suit name))
names))
suits))
(count sequence-of-suits) ;; 4
(count (first sequence-of-suits)) ;; 13
Unfortunately (map) didn't work as hoped. I decided to try a list comprehension. This was something I remembered from using once in Python. It turned out to be exactly what I needed:
(for [suit suits, name names]
(struct-map card :suit suit :name name)))
This yields a lot of text, so let's inspect the output programmatically. (filter) is a function which takes a function and a list; the output consists of the list items for which the function inspects and returns true.
;; 52
(first deck)
;; {:suit :hearts, :name :queen}
(last deck)
;; {:suit :clubs, :name :four}
(defn heart? [card]
(= :hearts (card :suit)))
(count (filter heart? deck))
;; 13
(defn king? [card]
(= :king (card :name)))
(count (filter king? deck))
;; 4
(defn king-of-hearts? [card]
(and (king? card) (heart? card)))
(filter king-of-hearts? deck)
;; ({:suit :hearts, :name :king})
Now that we have the deck straightened out, it's time to shuffle it. I'm getting the feeling there is a beautiful mathmatical way to sort 52 cards involving permutations which would be easy to code functionally. Unfortunately I'm not there yet on either side. This implementation is really crude.
For example, this random-card implementation instantiates java.util.Random each time it is called (and without a seed value). (nth) returns the nth item of a sequence; (seq) is being used here because deck is a hashmap, which doesn't support ordered extraction.
(nth (seq deck)
(. (new java.util.Random)
nextInt
(count deck))))
Continuing on with the vulgar display of crude code... here is the shuffle method:
([deck]
(shuffle [] deck))
([clean dirty]
(if (empty? dirty)
clean
(let [pick (random-card dirty)]
(shuffle (conj clean pick)
(disj (set dirty) pick))))))
Let's ignore the lack of comments of any sort here. This implementation uses variable arity. That means when the function is passed one parameter the following code will run:
(shuffle [] deck))
And when two parameters are passed the following code runs:
(if (empty? dirty)
clean
(let [pick (random-card dirty)]
(shuffle (conj clean pick)
(disj (set dirty) pick))))))
This is a feature of Clojure. I kind of like it. The way recursion was used here the variable arity made the code simple to read. I probably could have used (recur) for a very similar amount of code, but the dogs had to go out.
So the second chunk of (shuffle) picks a card at random from the unsorted pile, uses (conj) to include it in the sorted pile, uses (disj) to exclude the picked card from the unsorted pile, and then GOTO 10.
And now, with lots of gory code I'm not proud of, here is my first hand of 5 card draw:
({:suit :diamonds, :name :three}
{:suit :clubs, :name :ten}
{:suit :diamonds, :name :four}
{:suit :spades, :name :three}
{:suit :hearts, :name :three})
Wow, three of a kind. It's almost as if I programmed in a "be nice to Seth" bit somewhere...
Macros make Elvis better
Standard disclaimer: Clojure is a new hobby.
The C programming language provides a ternary operator. It's a terse if/else expression:
const char *text = (str != NULL) ? str : "null";
printf("%s\n", text);
}
The team behind the Groovy programming language took a look at the ternary operator and realized something. Developers frequently use it during a variable assignment to take the value of the test expression when not null, otherwise take the value of the "else" expression. A new operator was added to the language to support exactly this usage and was dubbed the Elvis operator.
The Scala programming language does not have an Elvis operator, but Daniel Spiewak posted an impressive implementation.
This led me to thinking about defining the Elvis operator in Clojure, my current spare-time language. Clojure is a Lisp hosted on the JVM (with some plans for the CLR). This was a fun exercise but I make no claims that this is a good way to be Elvis-ish in Clojure.
First, here's a naïve implementation:
(if-not (nil? a) a b))
It works:
123
user> (elvis_fn nil 456)
456
But it always evaluates the "else" expression. FALE.
(println (format "Sleeping for %d ms" duration))
(Thread/sleep duration)
duration)
user> (elvis_fn (nap 123) (nap 456))
Sleeping for 123 ms
Sleeping for 456 ms
123
So that's bad. Let's make a macro version. This should prevent the expressions from being evaluated before Elvis gets a chance to do his thing:
(if-not (nil? a) a b))
user> (elvis_macro (nap 123) (nap 456))
Sleeping for 123 ms
123
To verify this, I added
before the (if-not) form and called the method and the macro again:
Sleeping for 123 ms
Sleeping for 456 ms
Blue suede shoes
123
user> (elvis_macro (nap 123) (nap 456))
Blue suede shoes
Sleeping for 123 ms
123
So it was easy to avoid evaluating things by simply making the function into a macro. I'm sure there are many things above and beyond what I am doing here, but it was a nice experiment.


