Tuesday, September 6, 2011

echo

One of the most basic unix utilities is echo, which is used to "display a line of text". Below, I show how to implement this in Factor.

The usage for echo is usually written like this:

echo [-n] [string ...]

The -n option is to "not print the trailing newline character". We can make a word that checks the first argument for -n, and returns a boolean and the remaining arguments for formatting:

: -n? ( args -- ? args' )
    [ first "-n" = ] keep over [ rest ] when ;

Since the string arguments are separated by a single blank space, we can join and write them, optionally printing a trailing newline.

: echo-args ( args -- )
    -n? " " join write [ nl ] unless ;

We can define a "main" word that allows our vocabulary to be directly run or deployed:

: run-echo ( -- )
    command-line get [ nl ] [ echo-args ] if-empty ;

MAIN: run-echo

The code for this is on my Github.

No comments: