2009-09-09 45 views
6

我剛開始使用LISP,來自C語言的背景。到目前爲止,儘管它有着令人難以置信的學習曲線(我也是emacs新手),但它很有趣。subq(LISP)的簡單問題

無論如何,我在解析來自c源代碼的include語句時遇到了一個愚蠢的問題 - 如果任何人都可以對此進行評論並提出解決方案,那將會有很大幫助。

(defun include-start (line) 
    (search "#include " line)) 

(defun get-include(line) 
    (let ((s (include-start line))) 
    (if (not (eq NIL s)) 
     (subseq line s (length line))))) 

(get-include "#include <stdio.h>") 

我希望最後一行返回

"<stdio.h>" 

但是實際結果是

"#include <stdio.h>" 

有什麼想法?

回答

6
(defun include-start (line) 
    "returns the string position after the '#include ' directive or nil if none" 
    (let ((search-string "#include ")) 
    (when (search search-string line) 
     (length search-string)))) 

(defun get-include (line) 
    (let ((s (include-start line))) 
    (when s 
     (subseq line s)))) 
+1

*啪啪額頭*當然,我的邏輯顯然是錯誤的 - 我們會看到第二天的結局如何:-) – Justicle 2009-09-09 23:33:30

1

我覺得replace-in-string容易得多。

(replace-in-string "#include <stdio.h>" "#include +" "") 
    => "<stdio.h>" 

爲您的代碼,include-start返回比賽開始,顧名思義。您正在尋找include-end這可能是(+ (include-start ....) (length ....))

+0

哪裏是「代替,在字符串」 - 它是一個標準的功能?我在達爾文使用Closure Common Lisp。 – Justicle 2009-09-09 07:28:09

+0

哦,我以爲你在使用elisp。 – 2009-09-09 08:22:26

1
(defun get-include (s) 
    (subseq s (mismatch "#include " s)))