Use map to process list of lines from stdin?

Started by t3o, December 11, 2012, 01:57:54 PM

Previous topic - Next topic

t3o

hi,



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


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


(map (fn(line)
    (println ..)
    (read-line)
)


What is wrong with that?



Thanks

   t3o

jopython

#1
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

#2
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:


(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

#3
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?

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

; echo -e "foofoonblablan"| ./echo.lsp


thanks

  t3o

William James

#4

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

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