Use map to process list of lines from stdin?

Q&A's, tips, howto's
Locked
t3o
Posts: 7
Joined: Tue Dec 11, 2012 9:50 pm

Use map to process list of lines from stdin?

Post 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

jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

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

Post 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.

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

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

Post 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)).

t3o
Posts: 7
Joined: Tue Dec 11, 2012 9:50 pm

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

Post 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

William James
Posts: 58
Joined: Sat Jun 10, 2006 5:34 am

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

Post by William James »

Code: Select all

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

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

Locked