gpt4 book ai didi

clojure - 这段代码如何将数字翻译成英文?

转载 作者:行者123 更新时间:2023-12-02 14:31:18 24 4
gpt4 key购买 nike

我是 Clojure 新手,发现有一段代码如下

user=> (def to-english (partial clojure.pprint/cl-format nil 
"~@(~@[~R~]~^ ~A.~)"))
#'user/to-english

user=> (to-english 1234567890)
"One billion, two hundred thirty-four million, five hundred sixty-seven
thousand, eight hundred ninety"

https://clojuredocs.org/clojure.core/partial#example-542692cdc026201cdc326ceb 。我知道 partial 的作用,并且我检查了 clojure.pprint/cl-format doc 但仍然不明白它如何将整数翻译为英语单词。猜测 secret 隐藏在 "~@(~@[~R~]~^ ~A.~)" 后面,但我没有找到阅读它的线索。

任何帮助将不胜感激!

最佳答案

文档提到了这一点,但一个很好的资源是 A Few FORMAT Recipes摘自 Seibel 的实用 Common Lisp。另外,检查§22.3 Formatted Output来自 HyperSpec。

在 Common Lisp 中:

CL-USER> (format t "~R" 10)
ten
  • ~@(...~^...) 是大小写转换,其中 @ 前缀表示大写(仅第一个单词大写)。它包含一个向上转义操作~^,在此上下文中标记大小写转换的结束。当没有更多可用参数时,它也会退出当前上下文。
  • ~@[...] 是条件格式:只有当值非零时,内部格式才会应用于该值。
  • 最后的 ~A 意味着该函数应该能够接受另一个参数并打印它。

事实上,您的示例看起来像 §22.3.9.2 中的示例:

If ~^ appears within a ~[ or ~( construct, then all the commands up to the ~^ are properly selected or case-converted, the ~[ or ~( processing is terminated, and the outward search continues for a ~{ or ~< construct to be terminated. For example:

 (setq tellstr "~@(~@[~R~]~^ ~A!~)")
=> "~@(~@[~R~]~^ ~A!~)"
(format nil tellstr 23) => "Twenty-three!"
(format nil tellstr nil "losers") => " Losers!"
(format nil tellstr 23 "losers") => "Twenty-three losers!"

关于clojure - 这段代码如何将数字翻译成英文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085825/

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