在 LISP 中创建一个新的排序
Create a new Sort in LISP
我想在 LISP 中定义一个遵循这个公式的新排序方法。
2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > J > Q > K > A
如扑克中所见。
所以例如我称它为:
(mysortmethod '((3 H)(2 H)(J D)(8 C)(5 C)))
我会得到这个:
((2 H)(3 H)(5 C)(8 C)(J D))
作为排序列表,其中每个括号中的第二个元素被忽略。
我完全不知道该怎么做。有人可以指出正确的方向或者向我解释一种方法吗?
这是一个非常标准的 Lisp 练习。首先,您需要一种方便的方法来计算顺序。一个简单的方法是保留一个点序列(如果你有很多,也许哈希 table 将点映射到位置会更好)和一个比较它们位置的函数:
(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+)))
然后您可以使用标准 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 从每张牌中获取点数(因为您将牌表示为点数和花色的列表):
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))
我想在 LISP 中定义一个遵循这个公式的新排序方法。
2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > J > Q > K > A
如扑克中所见。
所以例如我称它为:
(mysortmethod '((3 H)(2 H)(J D)(8 C)(5 C)))
我会得到这个:
((2 H)(3 H)(5 C)(8 C)(J D))
作为排序列表,其中每个括号中的第二个元素被忽略。
我完全不知道该怎么做。有人可以指出正确的方向或者向我解释一种方法吗?
这是一个非常标准的 Lisp 练习。首先,您需要一种方便的方法来计算顺序。一个简单的方法是保留一个点序列(如果你有很多,也许哈希 table 将点映射到位置会更好)和一个比较它们位置的函数:
(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+)))
然后您可以使用标准 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 从每张牌中获取点数(因为您将牌表示为点数和花色的列表):
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))