Search code examples
inputj

Read input from line in J


I am very new to J (learning it for fun) and I am trying to read data from keyboard. I have tried to make a tiny script which reads in a string and reverses it:

|.(1!:1 3)

When I run it, I get a rank error. (I'm using 1!:1 3 instead of defining a verb because codegolf...) Is there a command that can check the rank of 1!:1 3?


Solution

  • That's a common mistake with foreigns.

    The definition for foreign 1!:1 doesn't help, because it really reads:

    1!:1 y      Read. y is a file name or a file number (produced by 1!:21); the 
    result is a string of the file contents., e.g. 1!:1 <'abc.q'. The following 
    values for y are also permitted:
    
    1 read from the keyboard (does not work within a script)
    3 read from standard input (stdin) 
    

    And so replacing y with 3 should work, right? Well, not quite, because what you're really giving as an argument in writing:

    1!:1 3
    

    is an array made of 1 3. Sort of like giving it:

    1!:(1 3)
    

    when you want:

    1!:1 (3)
    

    For code golf purposes, use a right bracket:

    1!:1]3