Reputation: 511
I want to define a new sorting method in LISP that sticks to this formula.
2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > J > Q > K > A
As seen in Poker.
So for example I called it on this:
(mysortmethod '((3 H)(2 H)(J D)(8 C)(5 C)))
I would get this:
((2 H)(3 H)(5 C)(8 C)(J D))
as the sorted list where the 2nd element in each bracket is ignored.
I have absolutely no idea how to do this. Could someone point me in the right direction or perhaps explain to me a method?
Upvotes: 0
Views: 251
Reputation: 85823
This is a pretty standard type of Lisp exercise. First you need a convenient way to figure out the ordering. One easy way to is to keep a sequence of the pips (if you have lots, maybe a hash table mapping pips to positions would be better) and a function that compares their positions:
(defconstant +pips+ #(2 3 4 5 6 7 8 9 10 J Q K A))
(defun pip< (pip1 pip2)
(< (position pip1 +pips+)
(position pip2 +pips+)))
Then you can use the standard sort function (remember, it's destructive, so save the result, and don't call it with quoted data, since you shouldn't modify literal data), passing pip< as the predicate and first as the key, because you use first to get the pip from each card (since you're representing cards as lists of a pip and a suit):
CL-USER> (let ((hand (copy-tree '((3 H)(2 H)(J D)(8 C)(5 C)))))
(sort hand 'pip< :key 'first))
;=> ((2 H) (3 H) (5 C) (8 C) (J D))
Upvotes: 4