How to define a function to read a wordlist

162 Views Asked by At

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?

1

There are 1 best solutions below

4
On BEST ANSWER

You're not quoting your lists:

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

But also there are probably much better ways to do this. read-file is useful here. extend and push 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:

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

More straightforward:

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

Reference: parse