reading file to list

André Thieme address.good.until.2009.may.11 at justmail.de
Sat Jan 17 15:30:49 EST 2009


Xah Lee schrieb:
> comp.lang.lisp,comp.lang.scheme,comp.lang.functional,comp.lang.python,comp.lang.ruby
> 
> Here's a interesting toy problem posted by Drew Krause to
> comp.lang.lisp:
> 
> ------------------------
> On Jan 16, 2:29 pm, Drew Krause wrote [paraphrased a bit]:
> 
> OK, I want to create a nested list in Lisp (always of only integers)
> from a text file, such that each line in the text file would be
> represented as a sublist in the 'imported' list.
> 
> example of a file's content
> 
> 3 10 2
> 4 1
> 11 18
> 
> example of programing behavior
> (make-list-from-text "blob.txt") => ((3 10 2) (4 1) (11 18))
> 
> w_a_x_... at yahoo.com gave a ruby solution:
> 
>   IO.readlines("blob.txt").map{|line| line.split }
> 
> augumented by Jilliam James for result to be numbers:
> 
>   IO.readlines("blob.txt").map{|line| line.split.map{|s| s.to_i }}
> 
> Very beautiful.
> 
> -------------------
> 
> That's really the beauty of Ruby.
> 
> This problem and ruby code illustrates 2 fundamental problems of lisp,
> namely, the cons problem, and the nested syntax pain. Both of which
> are practically unfixable.

*Of course* Xah is wrong, as always.
Who would expect anything else?
In the Lisp style Clojure for example one does exactly the same as
Jillian James (JJ) did in Ruby:
(map #(map (fn [s] (Integer/parseInt s)) (.split % "\\s")) (line-seq 
(reader "blob.txt")))

This is slightly longer, simply because the functions have longer names.
Integer/parseInt  vs  to_i

Also the function split takes a regexp, so I have to add the "\\s" here.
I don’t know though if Jillians version also handles any kind of
whitespac per line.
And the last thing is, that the function reader returns a BufferedReader.
So in general this is more valuable in real programs as opposed to one-
line scripts. If we combine line-seq and reader into readline and apply
the two other changes we would say:
(map #(map (fn [s] (to_i s)) (.split %)) (readlines "blob.txt"))
vs
IO.readlines("blob.txt").map{|line| line.split.map{|s| s.to_i }}

So, obviously Xah is far away from any reality.
It took him hours of his life to write up all his ideas about Lisp.
Sad to see that all that time was wasted. All of it was wrong.
Poor Xah :(


And btw, Drew Krause is just a Lisp newbie. No Lisper would ever store
data for his programs in the format
3 10 2
4 1
11 18

but instead as
(3 10 2)
(4 1)
(11 18)

And then read it back into the program with:
(map read-string (line-seq (reader "blob.txt")))


André
-- 



More information about the Python-list mailing list