Hello, User!
Another handy function, the opposite of say
, is ask
: it prints a prompt and asks for a line of input from the user. Save this code in a file called meow-user.ktn
and run it using kitten meow-user.ktn
.
"What is your name? " ask -> name;
"Meow, " print
name print
"!" say
There are a few new things here. print
is the same as say
except that it does not add a final newline. If you write "meow" say "meow" say
, the output will be:
meow
meow
But if you write "meow" print "meow" say
, then the output will be:
meowmeow
The syntax -> name;
is a local variable declaration: it means “take the top of the stack and store it in a variable called name
”. After creating a local variable, you can push its value onto the stack by writing its name, just like calling a function word.
So in this program we first print
a prompt, then ask
for a line of input and store it in the local variable name
, and finally use print
and say
to meow greet the user by that name.
We can clean up this code in a few ways. For example, we could build the response up in a single line of code before displaying it by using the +
operator to build a single text value passed to say
:
("Meow, " + name + "!") say
Concatenating together a sequence of lists—in this case, lists of characters—is a very common operation. So there is a word in the standard library called concat
which does just that: you can enter a list of values by putting them in square brackets ([]
) and separating them with commas (,
).
>>> ["abc", "def", "ghi"] concat
"abcdefghi"
Exercise: Change
meow-user.ktn
to useconcat
instead of the+
operator.
All the elements of a list must have the same type. Try entering the following commands at the interpreter to determine the types of the lists.
>>> //type [1, 2, 3]
>>> //type ["foo", "bar", "baz"]
>>> //type []
The expression 1
is an integer literal, with a type of Int32
, a signed 32-bit integer with the range −231 … +(231−1), so a list of integer literals like [1, 2, 3]
has type List<Int32>
.
The text literal "meow"
has type List<Char>
(“list of char”), where Char
represents a (UTF-32) Unicode code point. A list of text literals therefore has type List<List<Char>>
(“list of list of char”). A Char
can be created with the character literal syntax using single quotes, so the text literal "meow"
is syntactic sugar for the list literal:
['m', 'e', 'o', 'w']
Notice that the empty list literal []
has the strange-looking type <T> (-> List<T>)
. This is a generic type, which we’ll get to shortly. For now, just understand that an empty list literal can represent any type of list: []
is a valid List<Char>
(equivalent to ""
) and also a valid List<Int32>
, and even a valid List<List<Int32>>
.