Instructor: In this lesson, we'll write a ClojureScript program that handles command line arguments, a program called greet, that when invoked with your name, will say hello to you. Let's open a file called greet.
We'll start off like this. The first line sets Lumo as the interpreter for our script. If you don't have Lumo installed, you can refer to this webpage for several ways to install it. I chose to use NPM. Here's our documentation.
Clojure and ClojureScript ignore anything from a semicolon to the end of the line. It's common to introduce a whole line comment with two semicolons. When a Clojure or ClojureScript program starts up, a var named command-line-arguments, spelled like this with dashes and stars on the sides, is bound to a sequence of the command line arguments.
They're called vars, rather than variables, because they don't vary. They're immutable. Let's see what it looks like if I print it out. We invoke the built-in function, printLine, by enclosing it and any arguments in parentheses.
First, we have to make the file executable. Now, run the program with my name, Allen, as an argument. The output is a list, indicated by parentheses, containing a single element, the string Allen. What I want to do is to get that string and use it to greet myself.
I can get the first item in the list with the first function. Let's run it again. We have Allen by itself. Now, rather than immediately printing out that value, I'd like to give it a name that I can call it by. The easiest way to do that in Clojure is with def.
def binds the value obtained by evaluating the first command line args to the symbol user. Now, let's define a function that returns a greeting for a user. For that, we defn, define function, instead of def. We define the function greeting to expect one parameter, user, indicated by the square brackets.
Greeting calls the str function, which concatenates the string representations of its arguments. There's no need to say return in a Clojure function. The function returns whatever its last expression evaluates to.
Having defined the symbol user and the function greeting, we can now say printLine, greeting, user. That's our program. We run it, and it says, "Hello, Allen."