如何定义一个函数来读取一个wordlist

时间:2014-07-03 07:19:30

标签: lisp newlisp

我想在一个列表中读取一个包含单词列表(每行一个单词)的文件。

(define (read-wordlist myFile)
  (begin 
   (set 'listA '()) 
   (set 'in-file (open myFile "read")) 
   (while (read-line in-file) 
       (set 'listA (append listA (list (current-line))))) 
   (close in-file)))

此函数将文件读入列表listA

假设我有wordlist.txt

Lemon
Orange
Lime
Mango
Pawpaw
Strawberry
Apple
Watermelon
Banana

我得到了

> (read-my-file "wordlist.txt")
true
> listA
 ("Lemon" "Orange" "Lime" "Mango" "Pawpaw" "Strawberry" "Apple" "Watermelon" "Banana")

2个参数

我现在想要一个函数将文件读入一个列表,我可以在其中指定名称。

(define (read-wordlist2 myFile myList)
  (begin
    (set myList '())
    (set 'in-file (open myFile "read")) 
      (while (read-line in-file) 
         (set myList (append myList (list (current-line)))))
    (close in-file)))

然而是电话

 (read-wordlist2 "wordlist.txt" 'myWordList)

给出错误

ERR: array, list or string expected in function append : myWordList
called from user defined function read-my-file2

如何更改read-wordlist2的定义以使其有效?

1 个答案:

答案 0 :(得分:2)

您没有引用您的列表:

(define (read-wordlist2 myFile myList)
  (begin
    (set 'myList '())
    (set 'in-file (open myFile "read"))
      (while (read-line in-file)
         (set 'myList (append myList (list (current-line)))))
    (close in-file)))

但也有更好的方法可以做到这一点。 read-file在这里很有用。 extendpush是添加到列表的更好方法。并且上下文提供字典和哈希特征,这些特征通常更快且更有用。

稍微更惯用的是:

(define (read-wordlist my-file)
    (let ((in-file  (open my-file "read"))
           my-list '())
      (while (read-line in-file)
          (extend my-list (list (current-line))))
      (close in-file)
      my-list))

(set 'word-list (read-wordlist "/tmp/wordlist.txt"))

更直接:

(set 'word-list (parse (read-file "/tmp/wordlist.txt") "\n" 0))

参考parse