我有一个 Racket 程序(包含文件)的其他几个文件,其中一些包含我想使用主程序中的函数更新的 Racket 代码。 IE。这就是我要编辑的文件的样子(基本上)
(define somethings '(
(some list)
(some other list)
(yet another list)))
我希望能够在列表中添加更多内容,我认为有更好的方法可以做到这一点,但由于我是新手,因此我首先尝试了以下方法:
(define (update-file arg1 arg2 arg3 . args)
(call-with-output-file "somefile.rkt" #:exists 'append
(lambda (output-port)
(print "\b\b" output-port) ;; have tried several variations of this they all
(do other things) ;; print the backspaces literally rather than
(display "))" output-port) ;; removing characters
(newline output-port))))
我认为问题是 A:我正在使用 append,它大概只是把东西粘在最后(但更新和截断似乎不是答案)和 B:打印\b 不能像我尝试的那样工作使用它... :)
我现在绝望地浏览了 Racket 的文档,但我是编程新手,所以其中很大一部分还没有任何意义。是否有某种方法可以使该特定功能起作用,如果是这样,是否值得,或者是否有更好的方法来实现相同的结果?
非常感谢
最佳答案
试试这个:
(call-with-input-file "somefile.rkt"
(lambda (in)
(let* ((input (call-with-input-string (port->string in) read))
(output (list (car input) ; define
(cadr input) ; somethings
(list 'quote
(append
(car (cdaddr input)) ; old list
'((do other things))))))) ; new elements
(call-with-output-file "somefile.rkt" #:exists 'replace
(lambda (out)
(write output out))))))
这是正在发生的事情:
read
"somefile.rkt"
的内容到一个名为 input
的变量中,结果是一个 S 表达式列表 write
结果返回到同一个文件中,覆盖之前的内容最后,
"somefile.rkt"
将包含以下文本:(define somethings
(quote
((some list)
(some other list)
(yet another list)
(do other things))))
不用担心
quote
,这和写 '
是一样的.唯一的警告是文本的原始格式将丢失,所有内容都显示在一行中。
关于text - 使用 Racket 编辑文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589751/