I want to read a file which contains a list of words (one word per line) into a list.
(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)))
This function reads the file into a list listA
Assuming I have in wordlist.txt
Lemon
Orange
Lime
Mango
Pawpaw
Strawberry
Apple
Watermelon
Banana
I get
> (read-my-file "wordlist.txt")
true
> listA
("Lemon" "Orange" "Lime" "Mango" "Pawpaw" "Strawberry" "Apple" "Watermelon" "Banana")
2 parameters
I now want to have a function which reads the file into a list where I can specify the name.
(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)))
However the call
(read-wordlist2 "wordlist.txt" 'myWordList)
gives the error
ERR: array, list or string expected in function append : myWordList
called from user defined function read-my-file2
How do I change the definition of read-wordlist2
to make it work?
You're not quoting your lists:
But also there are probably much better ways to do this.
read-file
is useful here.extend
andpush
are better ways to add to lists. And contexts provide dictionary and hash features which are generally faster and more useful.Slightly more idiomatic would be:
More straightforward:
Reference: parse