Page 1 of 1

Use map to process list of lines from stdin?

Posted: Tue Dec 11, 2012 9:57 pm
by t3o
hi,

I am new to newlisp and I managed to read and process lines from stdin this way:

Code: Select all

(while (read-line)
	(println (slice (current-line) (div (length (current-line) ) 2)))
)
= print half of each line. A friend needed that.

I would like to do this by calling a function for each line of input but I cannot get it running. I thought of something like this:

Code: Select all

(map (fn(line)
    (println ..)
    (read-line)
)
What is wrong with that?

Thanks
t3o

Re: Use map to process list of lines from stdin?

Posted: Wed Dec 12, 2012 1:42 am
by jopython
Nothing wrong with that.
But map is for transforming a list into a different one based on the function you apply.
You are throwing away the transformed list by just using a print function.

Re: Use map to process list of lines from stdin?

Posted: Wed Dec 12, 2012 9:48 am
by cormullion
To get a line of input, you use (current-line), which returns a string. However, map applies a function to a list (as jopython says), rather than to a string. It's not clear whether you want to apply a function to each line, or to map a function over a list of every character in the current line.

For example, if you wanted to use map to print the integer code of each character, do this:

Code: Select all

(while (read-line)
    (map 
       (fn (character)
           (print (char character)))  
       (explode (current-line)))
    (println)
    )
Notice that the anonymous function 'character' (which prints the integer code of a character) is applied to every item in the list of characters produced by (explode (current-line)).

Re: Use map to process list of lines from stdin?

Posted: Sat Dec 15, 2012 9:58 pm
by t3o
hi and thanks for your answers!

My fault (or one of mine) was to think a call to "read-line" would result in a list of lines that I could process with "map": I wanted to map a shrink function on each of the lines.

Now I know that a call to "read-line" results in only a single line read. Hence its name ;-)

Is the code below the best (shortest; most newlispish) solution for my problem to print only a half of each line of input?

Code: Select all

#!/usr/bin/newlisp
(while (read-line)
	(println (slice (current-line) (div (length (current-line) ) 2)))
)

; echo -e "foofoo\nblabla\n"| ./echo.lsp
thanks
t3o

Re: Use map to process list of lines from stdin?

Posted: Fri Dec 21, 2012 2:47 pm
by William James

Code: Select all

(define (half-string str)
  ((div (length str) 2) str))

(while (read-line)
  (println (half-string (current-line))))