gpt4 book ai didi

lisp - 如何定义一个函数来读取单词列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:45 26 4
gpt4 key购买 nike

我想将一个包含单词列表(每行一个单词)的文件读入列表。

(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 的定义以使其正常工作?

最佳答案

你没有引用你的列表:

(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

关于lisp - 如何定义一个函数来读取单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24547395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com