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

时间:2015-03-04 12:29:13

标签: lisp common-lisp

我有两个类似的功能完美地工作。但我想将它们组合成一个函数。拜托我需要你的帮忙。谢谢!

功能1

(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 ...) 

功能2

(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 ...)

2 个答案:

答案 0 :(得分:2)

当我读到它时,两个函数之间的区别仅在于 他们读取的文件的名称,所以您需要做的就是传递名称 该函数的文件:

(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

答案 1 :(得分:0)

最后我发现了如何。我的问题是如何选择要打开的文件。我只是通过条件提到它,第一个:如果变量='代码,则打开此文件,如果变量=' char,则打开该文件。一切都好。

感谢您试图帮助我,也许下次你会。