gpt4 book ai didi

format - CL 格式配方 : Dealing with nil as a value

转载 作者:行者123 更新时间:2023-12-04 13:59:15 24 4
gpt4 key购买 nike

我一直在浏览格式化食谱,但我无法完全找到我要找的东西......
(format nil CONTROL-STRING day name num-apples)
假设我不想更改上述表单中的参数,只需 CONTROL-STRING .
daynum-apples将始终为非零,但 name可能为零。

name为零,我希望输出看起来像
"Today is Monday. Hello, you have 3 apples."
但是当 name已定义,我希望它看起来像
"Today is Monday. Hello Adam, you have 3 apples."
所以控制字符串需要看name , 在非 nil 的情况下使用它,在 nil 的情况下不使用它,但在两种情况下都消耗它。

也许它可以通过消耗 nil 并将其打印为 "" 来完成。 ?如果是这样,我不知道该怎么做。

最佳答案

您链接的问题,Lisp format directive that interprets nil argument to empty string instead of "NIL" , 确实包含一个显示如何执行此操作的答案,但未引用任何文档。由于您正在生成英文文本,因此您可能还需要考虑其他一些选项。

一、用 ~@[结果~] ,您可以处理后果 format 指令只是在参数非零的情况下,并且参数为 ~@[ 没有被消耗,所以它仍然可用。一般来说,
22.3.7.2 Tilde Left-Bracket: Conditional Expression描述了很多选项,但关于 ~@[ 它说:

~@[consequent~] tests the argument. If it is true, then the argument is not used up by the ~[ command but remains as the next one to be processed, and the one clause consequent is processed. If the arg is false, then the argument is used up, and the clause is not processed. The clause therefore should normally use exactly one argument, and may expect it to be non-nil.



您可以按如下方式使用它:
(defun test (day name n-apples)
(format nil "Today is ~a. Hello~@[ ~a~], you have ~a apples."
day name n-apples))
CL-USER> (test 'monday 'adam 2)
"Today is MONDAY. Hello ADAM, you have 2 apples."
CL-USER> (test 'tuesday nil 42)
"Today is TUESDAY. Hello, you have 42 apples."

为了使其更加健壮,您应该考虑使用 ~p for pluralization ,这样你就会得到“1 个苹果”和“3 个苹果 s ”。
(defun test (day name n-apples)
(format nil "Today is ~a. Hello~@[ ~a~], you have ~a apple~:P."
day name n-apples))
CL-USER> (test 'monday 'john 2)
"Today is MONDAY. Hello JOHN, you have 2 apples."
CL-USER> (test 'tuesday 'john 1)
"Today is TUESDAY. Hello JOHN, you have 1 apple."
CL-USER> (test 'wednesday nil 0)
"Today is WEDNESDAY. Hello, you have 0 apples."

最后,由于您正在生成文本,您可能会喜欢一些大小写规范化(例如,打印带有首字母大写的专有名词),并在文本中写入数字:
(defun test (day name n-apples)
(format nil "Today is ~:(~a~). Hello~@[ ~:(~a~)~], you have ~r apple~:P."
day name n-apples))
CL-USER> (list
(test 'monday 'adam 4)
(test 'tuesday 'john 1)
(test 'wednesday 'mary\ sue 42)
(test 'thursday 'jim-bob 0))
("Today is Monday. Hello Adam, you have four apples."
"Today is Tuesday. Hello John, you have one apple."
"Today is Wednesday. Hello Mary Sue, you have forty-two apples."
"Today is Thursday. Hello Jim-Bob, you have zero apples.")

关于format - CL 格式配方 : Dealing with nil as a value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com