方案中的 Printf
Printf in scheme
我将如何在方案中执行以下操作?
printf("I went to the park at %d with %s", 4, "Bob");
我现在最接近的是:
(define TIME 4)
(define NAME "Bob")
(display "I went to the park at ") (display TIME) (display " with ") (display NAME) (display ".")
这实际上取决于您使用的 Scheme 解释器。例如,在 Racket 中,您可以使用 printf
来达到类似的效果:
(printf "I went to the park at ~a with ~a" 4 "Bob")
=> I went to the park at 4 with Bob
查看 documentation 以获得更多格式修饰符。
您不能在标准 Scheme 中执行此操作。许多 Scheme 实现都有一个 format
过程,它是在 Common Lisp format
上建模的。例如,Chez Scheme 有一个非常完整的 format
实现,还有 printf
只是 format
的包装器。我已经习惯使用 format
以至于我从没想过在 lisps 中使用 printf
:
> (format #t "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
> (printf "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
这里format
当第一个参数为#t
时将输出发送到当前输出端口; printf
自动将输出发送到当前输出端口。 Common Lisp style format directives 以波浪号 (~
) 为前缀。 ~A
或美学指令以人类可读的形式打印对象,这正是您大多数时候想要的。还有其他格式化数字的指令;我添加了 ~%
指令,它发出一个换行符。您的原始示例不包含换行符,并且 printf
,至少在 C 中,不会在输出末尾添加换行符(通常这是可取的)。 format
过程应该比所有 printf
的母体,即 C 的 fprintf
.
更能控制结果
打印格式化输出的具体工具将取决于实现,但 Chez Scheme、MIT Scheme、Gauche Scheme 和 Guile 都实现了 format
。 Chicken Scheme 实现了 format
,还实现了 printf
、fprintf
和 sprintf
,它们都使用与 format
相同的格式指令。 Racket 有许多格式化输出程序,包括 format
、printf
和 fprintf
;所有这些也都使用 Common Lisp 风格的格式指令。
您将不得不查阅特定实现的文档以了解支持哪些格式指令以及它们如何工作; Chez Scheme 文档包含一些信息,但建议查阅 Common Lisp HyperSpec 以获取完整文档。
还有 SRFI-28 (Basic Format Strings) and SRFI-48 (Intermediate Format Strings) 为支持它们的实现提供了一些这样的功能。
我将如何在方案中执行以下操作?
printf("I went to the park at %d with %s", 4, "Bob");
我现在最接近的是:
(define TIME 4)
(define NAME "Bob")
(display "I went to the park at ") (display TIME) (display " with ") (display NAME) (display ".")
这实际上取决于您使用的 Scheme 解释器。例如,在 Racket 中,您可以使用 printf
来达到类似的效果:
(printf "I went to the park at ~a with ~a" 4 "Bob")
=> I went to the park at 4 with Bob
查看 documentation 以获得更多格式修饰符。
您不能在标准 Scheme 中执行此操作。许多 Scheme 实现都有一个 format
过程,它是在 Common Lisp format
上建模的。例如,Chez Scheme 有一个非常完整的 format
实现,还有 printf
只是 format
的包装器。我已经习惯使用 format
以至于我从没想过在 lisps 中使用 printf
:
> (format #t "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
> (printf "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
这里format
当第一个参数为#t
时将输出发送到当前输出端口; printf
自动将输出发送到当前输出端口。 Common Lisp style format directives 以波浪号 (~
) 为前缀。 ~A
或美学指令以人类可读的形式打印对象,这正是您大多数时候想要的。还有其他格式化数字的指令;我添加了 ~%
指令,它发出一个换行符。您的原始示例不包含换行符,并且 printf
,至少在 C 中,不会在输出末尾添加换行符(通常这是可取的)。 format
过程应该比所有 printf
的母体,即 C 的 fprintf
.
打印格式化输出的具体工具将取决于实现,但 Chez Scheme、MIT Scheme、Gauche Scheme 和 Guile 都实现了 format
。 Chicken Scheme 实现了 format
,还实现了 printf
、fprintf
和 sprintf
,它们都使用与 format
相同的格式指令。 Racket 有许多格式化输出程序,包括 format
、printf
和 fprintf
;所有这些也都使用 Common Lisp 风格的格式指令。
您将不得不查阅特定实现的文档以了解支持哪些格式指令以及它们如何工作; Chez Scheme 文档包含一些信息,但建议查阅 Common Lisp HyperSpec 以获取完整文档。
还有 SRFI-28 (Basic Format Strings) and SRFI-48 (Intermediate Format Strings) 为支持它们的实现提供了一些这样的功能。