lisp - 如何将两个相似的函数合并为一个函数

标签 lisp common-lisp

我有两个相似的功能,效果很好。但我想将它们合并为一个函数。拜托我需要你的帮忙。谢谢!

函数一

(defun  read_char_into_list (&aux (list nil)) 
    (setq char                     ; link this variable with open the file
        (open "fichier-char.txt"     ; open the file
            :direction :input :if-does-not-exist :error)) 
    (loop 
        (cond 
            ((not (setq line (read-line char nil nil))) (return)) 
            ((push (read-from-string line) list)) ) ) 
    (close char)    
    (reverse list) )  

(read_char_into_list) ==> (... e è é ê ë F f ...) 

函数二

(defun  read_code_into_list (&aux (list nil)) 
    (setq code 
        (open "fichier-code.txt" 
            :direction :input :if-does-not-exist :error)) 
    (loop 
        (cond 
            ((not (setq line (read-line code nil nil))) (return)) 
            ((push (read-from-string line) list)) ) ) 
    (close code)    
    (reverse list) ) 

(read_code_into_list) ==> (...65 192 194 196 198 ...)

功能统一

(defun  read-into-list (fichier &aux (list nil) )
    (setq fichier 'code or 'char)  
    (setq code
        (open (string-concat "alphabet_"   (string 'code)  ".txt")
            :direction :input :if-does-not-exist :error)
    (setq char
        (open (string-concat "alphabet_"   (string 'char)  ".txt")
            :direction :input :if-does-not-exist :error) ) 
    (loop
        (cond
            ((not (setq line (read-line (or code char) nil nil)))        (return))  
            ((push (read-from-string line) list)) ) )
    (close code) 
    (close char)   
    (reverse list) ) )

(read-into-list 'code) ==> should give (...65 192 194 196 198 ...)
(read-into-list 'char) ==> should give (... e è é ê ë F f ...)

最佳答案

正如我所读,这两个函数之间的区别仅在于 他们从中读取的文件的名称,因此您需要做的就是传递名称 文件的函数:

(defun read-into-list (file-name)
  (with-open-file (in file-name) ; :direction defaults to :input
    (loop :for line = (read-line in nil nil)
      :while line
      :collect (read-from-string line))))

并将其命名为

(read-into-list "fichier-char.txt")

(read-into-list "fichier-code.txt")

为了满足你的调用要求,你可以这样做

(defun read-into-list-1 (what)
  (read-into-list (concatenate 'string "fichier-" (string what) ".txt")))

请注意 string可能会返回 an upper-case string :

(string 'code)
==> "CODE"

另请注意 with-open-file确保即使出现错误也关闭文件,例如 read-from-string .

关于lisp - 如何将两个相似的函数合并为一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28854558/

相关文章:

lisp - lisp中的循环指针

lisp:lambda 作用域

Lisp:如何获得最终的循环值?

lisp - 在 Scheme 中编写评估程序?

lisp - Lisp代码是如何构造的?什么是包和系统?

let 语句的 Lisp 评估

common-lisp - 不知道如何给数组赋值

size - 如何减小 Clozure Common Lisp 可执行文件的大小?

configuration - 如何使用 Clozure Common Lisp 创建应用程序(在 Microsoft Windows 上)

lisp,如何消除重启