如何在 Racket 中重新排列配对列表(具有字符或数字)的顺序?
如何在 Racket 中将所有带有“A 'K 'Q 'J”字符的牌移动到我的手牌前面,并将所有数字 1-10 移动到最后?
例如: ((4 . ♠) (9 . ♣) (10 . ♠) (Q . ♠) (A . ♠))
变为
((A . ♠) (Q . ♠) (10 . ♠) (9 . ♣ ) (4 . ♠))
我在这里遇到的困难是处理数字和字符的混合。我可以使用排序函数对数字进行排序,但是一旦出现字符就会出现错误。
How can I move all cards with characters 'A 'K 'Q 'J to the front of my hand and all the numbers 1-10 to the end in Racket?
Ex: ((4 . ♠) (9 . ♣) (10 . ♠) (Q . ♦) (A . ♠))
becomes
((A . ♠) (Q . ♦) (10 . ♠) (9 . ♣) (4 . ♠))
My struggle here is dealing with the mixture of numbers and char. I can sort the numbers with the sort function but I get errors as soon as a char appears.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上
sort
有一个可选的less-than?
函数,您可以在其中检查第一个参数是否小于第二个参数。例如。想象一下,我想按卡片的值 1-10 对卡片进行排序,而 J、Q、K、A 是 11-14:由于您遵循相反的顺序,因此您应该传递
card-greater?
而不是card-less?
和sort
的相反会颠倒顺序吗?如果您使用
#langracket
,您可以利用两个额外的可选值并使其无需无卡?
:Basically
sort
has an optionalless-than?
function you can provide where you check if first argument is less than second. eg. Imagine I want to sort cards by their value 1-10 and that J,Q,K,A are 11-14:Since you are after the opposite order you should pass a
card-greater?
instead that does the opposite ofcard-less?
andsort
will reverse the order.If you are using
#lang racket
you can make use of the two extra optional values and make it withoutcard-less?
:您可以使用排序功能,例如这个:
(排序顺序过程)
。 过程可能如下所示:您可以开发
(check ...)
函数并删除(if ...)
,因为检查将返回适合排序的值。如果你想进一步对字母进行排序,你需要在check中比较
a
和b
。You use the sort function like this:
(sort sequence procedure)
. The procedure could look like this:You can develop the
(check ...)
function and also drop the(if ...)
, as checking will return the value fitted for sort.If you want to further sort the letters, you need to compare
a
andb
within check.