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.
Clojure training!
Very exciting -- Rich Hickey and Stu Halloway will be giving Clojure training in early 2010 in Northern Virginia. Sign up here for news as soon as it happens: http://pragmaticstudio.com/clojure
I wanted a macro, but needed recursion
Standard disclaimer: Clojure is a new hobby.
It's easier for me to start things than complete them. That seemed like bad news when I just couldn't figure out how to generalize a small bit of Clojure code. One long week went by as I repeatedly got very close but couldn't quite solve the problem. While eventually I figured it out, the process of getting there made me look forward to writing more Clojure.
My last exploration of Clojure taught me to avoid for loops while splitting a string into overlapping character pairs. This exploration into Clojure was going to generalize that code to emit any width of overlapping character chunks.
Here is the old, inflexible code:
(map
(fn [l r] (str l r))
(seq text)
(rest (seq text))))
A quick summary of that:
- Defines a function named split-bigrams
- It accepts one untyped parameter, here named
text - The method body contains one function call to
map, which takes three arguments: one anonymous function taking two arguments, and two sequences. mappulls one character from each sequence and passes them to the anonymous function, which turns them into a string
The trick? Two iterators over one string, with the second iterator starting at the second character. Then just iterate over the lists and mash the items together. Problem is, to get character triplets I would need a third iterator starting at the third character. That's no way to live! Just a big fat FALE WHALE.
I desperately hoped that macros could somehow magically generate all the lists for map. I like macros. Clojure likes macros! My poor little train of thought couldn't scale this mountain. I thought I could, I thought I could, but between tucking in kids and dog walks I was too tired/busy. So I gave up and looked for another option.
Howzabout recursion? I spent several days rewriting variants of this:
(when (nthnext seq (- n 1))
(take n seq)))
(defn nice-try [n str]
(when-let [chars (take-chunk n str)]
(prn chars)
(recur n (rest str))))
This prints the values I want... it just doesn't put them into a collection! I feebly tried incorporating map and reduce. Not sure how many infinite loops were created and cancelled...
Finally, I decided to read the source code of Clojure to see how they do things like this. That was a great decision. core.clj is clean, clear, and full of goodness. Somewhere in there I found recur being used how I needed it: do something to a collection, call itself with the output until the input was exhausted, and return the aggregated output:
(let [ngram (take-chunk n chars)]
(if ngram
(recur n (rest chars) (cons ngram ngrams))
ngrams)))
This is probably a basic recursion pattern. I feel a little silly taking so long to figure it out. Just a little silly though, as the coding I do for a living doesn't encourage recursion.
At this point I am almost convinced that Clojure is the optimal language for me to grow as a programmer. Lisp itself is a low-level high-level language; you have to really understand how things are going to work, but not worry about things like garbage collection. The "homegrown VM" and "no library" problems just don't exist in Clojure. The APIs are clean and clear. Best of all the dogma is minimal and pragmatic. HUZZAH!
Reduce your way into good Clojure
Standard disclaimer: Clojure is a new hobby.
In my previous post I discussed replacing for loops with the (map) function. That works, until it doesn't.
Another step needed to generate the cosine similarity for two strings is to create a frequency histogram, or how many times each character pair occurs in a string. This is a pretty good fit for a hash map, where the keys are the character pairs, and the values the occurrences.
Here was my initial try. This code meant to do well... but went far, far away from where I wanted. Let's take a detailed look at my failings:
(let [hm (hash-map)]
(map
(fn [key val]
(assoc hm key val))
["a" "b" "a"]
[1 2 3]))
What I wanted: a map like this => {"b" 2, "a" 3}. What I got was three hash maps, each with one key/value pair => ({"a" 1} {"b" 2} {"a" 3}). The intent was to use map to iterate over the sequences, and use assoc to put the key and value into one hash map. And now, for the parade of errors...
- Use the zipmap function to build hashmaps like this:
(zipmap ["a" "b" "a"] [1 2 3])=>{"b" 2, "a" 3} - Variables in the let block cannot be changed...
- ... but I really needed to update the hash map defined in the let block.
Rather than continue to stew uselessly I used Emacs to hop into the #clojure IRC channel. A wonderful person suggested the reduce function; I'd used it once in Ruby where it is best known as inject. I'm going to skimp on my description of reduce a little since that article is so well done.
reduce iterates over a collection like map, but it passes a mutable context to each callback. The return value of reduce is the final value of the context... essentially. I am still coming up to speed on it obviously.
Anyhow, enough yammering. Here is reduce in action:
(reduce
(fn [product key]
(+ product
(* (get l_histo key 0)
(get r_histo key 0))))
0
(keys l_histo)))
Key points:
[l_histo r_histo]-- these are the arguments to the dot-product function.(fndefines an anonymous function.(getgets the value for the specified key from the specified map, returning the final argument when the key is absent.0is the default value forproduct(keysreturns the keys of the specified hash map- Clojure really wins a lot by delegating to Java. This happened for free:
(Math/sqrt 100)=>10.0
So, reduce is a critical step for people coming from imperative programming languages looking to do basic things with collections.
Put that for loop down
Standard disclaimer: Clojure is a new hobby.
I've been spending a lot of time with Clojure recently to prepare for the ICFP 2009 contest. It hasn't been the easiest thing, but the difficulty has come from trying to grasp many new concepts at once. The documentation has been pretty good, and the IRC channel has been pretty worthwhile.
I'm trying to settle on a specific task to accomplish when learning a new language. Something concrete but still a little academic... implementing cosine similarity using character bigrams isn't much code, but it covers enough bases to be useful.
Part of the process involves splitting a string into overlapping character pairs.
Bad old me instinctively thinks "for loop".
Good new me thinks... bad old me probably has it right. But it doesn't feel very Clojure-y. This solution is a little more Clojuriffic, probably still a long shot from idiomatic:
(map
(fn [l r] (str l r))
(seq text)
(rest (seq text))))
Bad old me (BOM) would have iterated over the string using a for loop with an index variable, cycling length - 1 times.
Good new me (GNM) had to take a different approach. I converted the string into two sequences; the first was just the string, but the second was the string minus the first character.
sequence A': [B C D E F]
The (map) function takes a callback and a number of sequences. The callback function gets the nth element from each sequence, and the output from the callback is collected and returned by (map). I don't have to specify a length or repetition count, as (map) stops processing when any of the collections run out of data.
("AB" "BC" "CD" "DE" "EF")
This hasn't taken a lot of time, but more than I like. It has taken A LOT of patience, energy, and focus during that time. But I like finding new ways to solve problems. Now I have a new tool in my nerdbelt, one that pushes the for loop back a little bit.
Clojure for the ICFP 2009 contest?
So the programming contest for the 12th International Conference on Functional Programming is coming up soon -- June 26th - 29th. Last year team Foognostic submitted a Ruby-based solution which made it to the second round. This year we will take another stab at it, this time with Clojure. Anyone else interested?
Last year I installed Trac to help organize things and that was fun, but this year I think BitBucket is the way to go. More features that someone else maintains -- woo!
This year another Foognostic solution will be submitted, barring unexpected events that weekend. For the sake of trying to look cool I will be using Clojure, mostly as an exercise to really explore a Lisp. I'm more familiar with Emacs Lisp, but Clojure is sitting right on top of all those featuriffic Java APIs.
The countdown timer stands at a little more than two weeks. That should be enough time to come up to speed, right? ... or have I just uttered famous last words?
In any event, watch this space for updates!
- The ICFP 2009 contest site.
- The ICFP 2008 task description.
Configuring projects in org mode, or defining variables in Lisp is strange
Org mode in GNU Emacs makes it somewhat easy to publish its files as a small static website. You define the files to publish, how to convert them, where to publish them, and so on. The bad news is that you need to manually write a big data structure in Emacs Lisp. Not what a Lisp newbie really wanted to hear (no customize page?) but I decided org mode was worth the pain. Speaking of pain, here's the data structure:
0: (set 1: (quote org-publish-project-alist) 2: ' 3: ( 4: ( 5: "tsn" 6: :base-directory "~/Documents/foog/tsn" 7: :base-extension "org" 8: :publishing-directory "/dev/null" 9: :publishing-function org-publish-org-to-html 10: ) 11: ) 12: )
All that work just to define a list of lists? I could just write it in Ruby as:
# pretend this function exists in Ruby
# def org_publish_to_html() end
org_publish_project_alist = [
[ "tsn",
:base_directory, "~/Documents/foog/tsn",
:base_extension, "org",
:publishing_directory, "~/Documents/foog/tsn_export",
:publishing_function, org_publish_to_html ]
];
The major difference is all this set and quote nonsense. How many function calls does it take to initialize a variable in Lisp?? It turned out that answering that question well required some spelunking into Lisp. It kind of makes me appreciate GNU Emacs Lisp as a low-level high-level language.
And now, we plunge through the rabbit hole!
So, why call the (quote) function when defining a variable? I didn't realize what a good question this was. The answer means paying close attention to references and values. Let's take a quick look at a function which determines whether its argument is a value or a reference:
(symbolp (quote 123)) => nil ;; 123 passes through...
(symbolp (quote "abc")) => nil ;; abc passes through
(symbolp (quote foo)) => t ;; but foo is a symbol.
Okay, so now we can distinguish between a value and a reference. The next step is assigning a value to a reference. This is where (quote) is essential.
That silly Lisp interpreter, trying to get a value while we are in the middle of setting it. That's where (quote) comes in. The function call to quote is evaluated, and the result is passed as the first argument to (set). That makes some sense, but because variable definition happens ALL THE TIME in imperative programming languages Emacs Lisp has tried to make this as easy as possible:
(set 'foo 456) =>; 456 ;; 'foo = (quote foo)
(setq foo 789) =>; 789 ;; People do this one.
INTERMISSION
Now that variable assignment has been hashed out we can pick up speed a bit and finish this off:
- Line 1 specifies the symbol we want to use.
- Line 2 is just a macro for (quote), so the contents will be returned without being evaluated.
- Line 3 starts a list. To me this implies that the variable org-publish-project-alist will contain an array of ... well, not sure yet.
- Line 4 starts a list. This list will be the first item in the list defined by org-publish-project-alist.
- Line 5 is just a string. It is the first element in the list. Calling (car) on the list started at line 4 would return "tsn".
- Line 6 contains the 2nd and 3rd items in the list. :base-directory is a keyword symbol ((symbolp :base-directory) => t). "~/Documents/foog/tsn" is the next element in the list.
- Lines 7-9 define the remnant of the list started at line 4.
- The remaining lines are the obligatory closing parens.
Probably because I am very new to Lisp I don't understand why flat lists are used to store this data. Key value pairs are a great fit for hash maps or associative lists (the variable name ends with alist...). My first attempt to restructure the data would be:
(setq org-projects
'(
("tsn"
(:base-directory . "~/Documents/foog/tsn")
(:base-extension . "org")
(:publishing-directory . "~/Documents/foog/tsn_export")
(:publishing-function . org-publish-org-to-html))
("css"
(:base-directory . "~/Documents/foog/tsn/css")
(:base-extension . "css"))
("img"
(:base-directory . "~/Documents/foog/tsn/images")
(:base-extension . "jpg|png"))
))
The difference being that key value pairs are stored in an associative list. This lets you take advantage of built in functions for getting property values.
(mapcar
(lambda (elt)
(let
((project (car elt))
(properties (cdr elt)))
(print (format "Project %s has base extension %s"
project
(cdr (assoc :base-extension properties))))))
org-projects)
Output: ("Project tsn has base extension org" "Project css has base extension css" "Project img has base extension jpg|png")
Wow, look at all the rambling. At least now I understand how to manually configure org mode's projects.
Lisp is neat.


