This article is old and is being consolidated into the book.
Please refer to the corresponding chapter(s) therein.
If the chapters or sections are not completed yet, you can use this article.
Refer to the examples as they are tested against the latest code.
Values, Variables and Data StrcuturesBy James Jianbo Huang October 2001 UPDATED: July 2003 non-printer versionAbstract JudoScript has primitive data types and data structures including arrays, linked lists, structs, ordered maps, stacks and queues, and table data. Primitive data types include number, string and date/time and secret. String can also represent URL and file. Arrays can be sorted and filtered with custom comparator and filter functions. The Objects' keys can be obtained in array, either in undetermined order, or sorted and/or filtered by keys or by the values. Comparator and filter functions are frequently defined as lambda functions.
1. Variables and Constants
JudoScript is a dynamically typed language, meaning that its variables and constants are not typed, but their values, however, belong to one of these supported types: number, string, date and time, secret, compound data types (data structures), Java objects and arrays, and built-in object types. Variables are not required to be declared first. Value types are interpreted in the program based on the context at runtime. For instance, a boolean expression will interpret the values as integers. This articles discusses the primitive types and data structures.
Variable names start with a letter, underscore or dollar sign ( Constant names start with a pound sign (a = 1; # ). They are defined like this:
To check whether a constant has been defined or not, use theconst #PI = 3.1415927; defined
operator:
Theif defined #PI { println #PI; } println command can be abbreviated as a dot (.).
2. Primitive Data Types
JudoScript supports these primitive data types: integer, floating-point number,
string and date/time. Boolean values are just numbers: 0 stands for false,
non-zero for true. They can be assigned a The following program demonstrates how values are used:
If this is your first glance of any JudoScript code, it may look too much. But if
you look closely, it is really very natural. The start of script and lines 31 and 34 form a
try-catch block; when an exception happens, its message is printed and the
execution is resumed (line 33). I wish Java had Let us see the result of the run and dive into the gory details of numbers, strings and expressions: First of all, strings can be quoted either by single quotes or double quotes (line 4). When single quotes are used, double quote characters can appear as normal text and vice versa. Its concatenation operator is% java judo simple_vars.judo A) a = 1: 1 B) a = 1.00: 1.0 C) a = '1.00': 1.00 D) a = 1.5e5: 150000.0 E) a = null: a = 1.0: 1.0 F) a += 2: 3.0 a = 1.1 1.1 G) a *= 4: 4.4 a = 10: 10 H) b = a / 2.5: 4.0 a = 3.5: 3.5 b = 2.5: 2.5 I) a % b = 1 a = 5.0: 5.0 J) a - c = 5.0 K) a + "abc" = EXCEPTION: Invalid floating-point value L) "abc" + a = EXCEPTION: Invalid floating-point value M) "abc" @ a = abc5.0 a @= "xyz": 5.0xyz N) a + "0x0a" = EXCEPTION: Invalid integer value O) a + "0x0m" = EXCEPTION: Invalid integer value P) a + "007" = EXCEPTION: Invalid integer value Q) a + "008" = EXCEPTION: Invalid integer value a = 5: 5 R) a + "0x0a" = 15 S) a + "0x0m" = EXCEPTION: Invalid integer value T) a + "007" = 12 U) a + "008" = EXCEPTION: Invalid integer value @ (line 20). Integers can be expressed as decimal (line 3),
octal (starts with 0 but not "0x"; line 29) or hexadecimal (starts with
"0x" or "0X"; line 27). Floating-point numbers can be decimal and
fraction digits (line 7) or in scientific notion (line 5).
Lines 7 through 17 demonstrates the auto-detection of number types: JudoScript always tries to use a higher-precision type, that is, floating points over integers. Based on context, a string is evaluated to a number by its "face value" (lines 22, 27 and 29); if the string is not in a valid number format, an exception is thrown (lines 18, 19, 22 through 25, 28 and 30). Conversions and Formatting
There are times where a specific data type or value range is intended. The simple values have methods for such controls.
On line 9, etc., These methods are specifically for formatting numbers:
Using JudoScript command-line program execution feature, you have a calculator:println '1 > 2 is ', (1 > 2).fmtBool(); println (231).fmtHex(); dur = ( (2 * 24 + 3) * 3600 + 35 * 60 + 9 ) * 1000; println dur.fmtDuration(); // => 2 days 3:35:09 The last ';' can be omitted. I create an alias "jx" for "java judo -x", so the above lines become really compact.%java judo -x println (231).fmtHex() E7 %java judo -x println 0xE7 231 String Processing
A JudoScript string supports most Java's
The Thes = '2001/10/01||XYZ|12.00|10000'; a = s.csv('|'); println 'Date: ', a[0]; println 'Name: ', a[1]; // => null println 'Symbol: ', a[2]; println 'Quote: ', a[3]; println 'Volume: ', a[k]; isEmpty() and isNotEmpty() checks if a string is empty
or not. A string is considered empty if it is null or only contains whitespace
characters. Method neverEmpty() takes a default string parameter; if
the current string value is empty, that parameter is returned. If no parameters
specified, when empty it returns a space (which is "empty" itself but what
else?) The replace() and replaceIgnoreCase() methods replace
substrings with new ones, which is more powerful than Java counterpart
(replace(char,char) ) that only replaces characters. The following is
an application dealing with HTML content:
The following example shows how to use file system commands to rename all files with extension of ".htm" or ".HTM" to ".html".expr = " <add_expr> ::= <expr> '+' <expr> "; exprHtml = expr.replace('<', '<') .replace('>', '>') .replace('&', '&') .replace("'", '"'); println <htmlFile> exprHtml; println <htmlFile> '<td>', x.neverEmpty(' '), '</td>'; This program prints out an ASCII table for 32 to 255:list '*.htm, *.HTM'; // result is an array stored in $$fs_result for x in $$fs_result { if x.toLower().endsWith('.htm') { rename x to x.replaceIgnoreCase('.htm', '.html'); } }
Lines 2 and 3 print out the header. On line 2, the 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: ! " # $ % & ' ( ) * + , - . / 30: 0 1 2 3 4 5 6 7 8 9 : ; < = > ? 40: @ A B C D E F G H I J K L M N O 50: P Q R S T U V W X Y Z [ \ ] ^ _ 60: ` a b c d e f g h i j k l m n o 70: p q r s t u v w x y z { | } ~
String has other methods. Enhanced Here-Doc
In the make utility, feature here-doc is used to specify a chunk of text to be enclosed in two user-defined markers and used verbatim by the script. JudoScript supports the same feature with the extension that expressions can be embedded. The markers arelastname = "Robinson"; prodname = "Dry Cleaner"; representative = "Cleo Rubinstein"; letter = [[* Dear Mr. (* lastname *), Thank you very much for your interest in our product, (* prodname *). For more information, please visit our web site at (* url *). Sincerely, (* representative *) *]]; flush letter; [[* and *]] . Embedded expressions are
enclosed in between (* and *) . The lines' indentations
are removed, so is the first empty new line following the [[*
marker, so the code can appear nice and neat. Use [[[* instead
of [[* to turn off automatic indentation stripping.
Date and Time
Three system functions create dates and times: Oct1_2001 = date(2001,10,1); timestamp = date(2001,10,1,15,30,0); noon = time(12); tonight6_30pm = timeToday(18,30); date() takes parameters of year, month, day, hour, minute and second.
time() creates a date object with year, month and day fields all
initialized to 0. timeToday() is a convenience method that creates a
time in today.
Date values (objects) have a list of attributes, some are settable and others
read-only. See language specification
for a complete listing. It also have a method,
Review Questions
Secret Value
Secret values appear to be regular values but are used only by known parties,
such as statements that take passwords. If it is attempted to be printed, it
will throw illegal-access exception. To obtain one, use the system function
The decryptor is an object that implements the method decrypt() ,
which takes a string and returns another. It does not matter whether it is
implemented in JudoScript or Java, though most likely it is in Java. The encrypted
value must be a text string. How to obtain it is up to your crypto package
that your decryptor is part of. If no decryptor is specified, by default the
value is returned as-is for now. However, this behavior may change, that is,
a default decryptor may be used, which is specified in the runtime
environment. Let us see an example. Suppose you have run some utility and
encrypted your password to "XI,8aM4/", and the decryptor is a Java class.
const #dbPass = secret('XI,8aM4/', javanew com.xxx.util.MyCrypto);
3. Special-Purpose String Methods
Strings also represents URLs and file names. String has
You can treat a string as a file path and get various parts: The following example shows string's file methods:a = [ '/usr/bin/java', 'c:/temp/Test.java', '~/alfa', 'judo.jar' ]; for x in a { println x.getFilePath(), ' : ', x.getFileName(), ' : ', x.getFileExt(); }
Review Questions
4. Maths
Numeric values have a list of mathematic methods. See language specification for a complete listing. The following is some trigonometric examples: println '------ trigonometry ------'; const #PI = 3.1415927; println "60' in radian: angle = ", angle = #PI / 3; println 'angle.degree() = ', angle.degree().fractionDigits(3); println 'angle.sin() = ', angle.sin().fractionDigits(3); println 'angle.cos() = ', angle.cos().fractionDigits(3); println 'angle.tan() = ', angle.tan().fractionDigits(3); println 'f = ', f = 1.0; println 'f.asin() = ', f.asin().fractionDigits(3); println 'f.acos() = ', f.acos().fractionDigits(3); println 'f.atan() = ', f.atan().fractionDigits(3); println "60' in degrees: angle = ", angle = 60; println 'angle.radian() = ', angle.radian().fractionDigits(3); println 'angle.sin_d() = ', angle.sin_d().fractionDigits(3); println 'angle.cos_d() = ', angle.cos_d().fractionDigits(3); println 'angle.tan_d() = ', angle.tan_d().fractionDigits(3); println 'f.asin_d() = ', f.asin_d().fractionDigits(3); println 'f.acos_d() = ', f.acos_d().fractionDigits(3); println 'f.atan_d() = ', f.atan_d().fractionDigits(3); Review Questions
5. Array and Linked List
Array is one of the most important data structures. A JudoScript can contain any variables, including numbers, strings, Java objects and other data structures including arrays. To define or initialize an array: arr = []; // empty array arr = [ 1, 'abc', date(2001,10,1), javanew java.util.Hashtable() ]; arr = [ [ 1, 2 ], [ 3, 4 ] ]; // multi-dimension arr = new Array; // another way to create. arr = new Array( 1, 'abc', date(2001,10,1) ); Linked lists are desirable over arrays in certain algorithms for performance reasons. In JuduScript both share a common interface; the only difference is its declaration: Thelst = linkedList[]; // empty list lst = linkedList[ 1, 'abc', date(2001,10,1), javanew java.util.Hashtable() ]; lst = [ linkedList[ 1, 2 ], linkedList[ 3, 4 ] ]; length or size attribute is the number of elements.
To add elements, call its add() or append() with one or
more values; use prepend() to insert elements to the front; or use
insert() to insert at a particular position. Array index is 0-based.
You can merge all the elements from another array by appendArray()
or prependArray() . Obtain a portion of an array via subarray() .
Method clear() removes all the elements, where remove()
removes an element at a specific location. To find the index of an element,
use indexOf() . reverse() is a convenience method that
reverses all the elements.
To enumerate all the elements in an array, do one of these: If the index is not used, the last form is the easiest. If the index is used, the second form is more concise.for idx=0; idx < arr.length; ++idx { local x = arr[idx]; println idx, ' ', x; } for idx from 0 to arr.lastIndex() { local x = arr[idx]; println idx, ' ', x; } for x in arr { println x; }
Arrays can also be created via Statistics
These methods collect some basic statistics about all the numeric elements
in the array: Sort, Filter and Convert
JudoScript has some powerful sorting capabilities for arrays and linked lists via
the
Lines 5 through 14 defines a custom comparator. Comparator functions must take two parameters, and return -1, 0 or 1. On line 1, we have an array of things that look like book sections. Normal string comparison fails to yield correct order. Our comparator takes apart the section number to an array (lines 6 and 7), and compares each parts. Line 2 shows how to pass a function to a method: the ampersand notion. The result is: As a convenience, JudoScript has0 1.2 1 1.2.1 2 1.10 3 2.3 4 3 5 3 6 3.9 sortAsNumber() , sortAtDate()
and sortAsString() methods. The last one is not really necessary,
just for the sake of naming consistency.
Sometimes you need to pick "qualified" elements in an array. JudoScript's array
filtering feature makes this easy. Array have a
Lines 1 through 4 shows how a filter function, which takes a parameter
and returns a boolean, is used by the
On line 6, the second parameter is Our last topic of this seciton is converting elements in arrays. This is done by the methodf1 = &size_filter; f2 = lambda elem { return elem.length() >= 5; }; println a.filter(f1); println a.filter(f2); convert() , which, not surprisingly,
takes a conversion function that must accept one parameter and return
a value.
Review Questions
6. Object and Ordered Map
A struct and an ordered map are virtually the same compound data structures
that holds variable number of named attributes. In JudoScript there is no need to
define a struct; simply assign values to an attribute name. Therefore, "map"
may be a more appropriate name for struct. Objects and ordered maps are
created by the To access an attribute, use the dot operator; if the attribute name has non-identifier characters, have it quoted. If an attribute is not defined, aa = new Object; a = new OrderedMap; a = new Object( name = 'Sanjay Deepak', title = 'Software Engineer', sex = 'm', age = 34 ); a = new Object( 'last name' = 'Deepak', 'first name' = 'Sanjay', title = 'Software Engineer' ); null is returned.
To remove an attribute, useprintln a.'first name'; // access by name field = 'first name'; // access by expression println a.(field); remove() or delete() .
Method size() returns the number of attributes, and
clear() removes them all.
Method Keys (attributes) or their values can be sorted or filtered. This is a powerful feature that makes in-memory data processing extremely easy. The methods area = new Object( alfa = 'A', beta = 'B', gamma = 'C', delta = 'D' ); for x in a.keys() { println x, ' => ', a.(x); } keysSorted() , keysFiltered() ,
keysSortedByValue() , keysFilteredByValue() and
keysSortedAndFilteredByValue() . All of them may take a
comparator function and/or filter function. The following example shows
how to use the latter three to achieve some kind of in-memory queries.
Lines 1 through 6 create an Object whose attributes are keys and values
are a struct containing various pieces of information. Line 8 defines a
comparator function that compares values with the system function
Review Questions
Stack and Queue
Stacks ane queues are essential to deal with recursive data structures
(such as trees and graphs) and algorithms. To create a stack or queue,
use the
Stacks have these methods:
Lines 1 through 9 defines a class. In the constructor, lines 4 mandates that an attributed called "name" must be initialized, and line 5 creates an array attribute "children". A stack is used for depth-first traversal, and a queue for bread-first. On line 33 the for loop runs in backward order so the "left" child is processed first. The tree and the result of run is shown below: ROOT / \ A B /| / | \ A1 A2 B1 B2 B3 Depth-first traverse: ROOT A A1 A2 B B1 B2 B3 Breadth-first traverse: ROOT A B A1 A2 B1 B2 B3 Review Questions
7. Summary
JudoScript variables and constants are weakly typed. The primitive types include
integer, floating point number, string and date/time and secret. Data
structures include struct, ordered map, array, linked list, stack and
queue. Other variables include Java objects (and arrays) and built-in
objects. Numbers and strings can be used interchangeably in expressions.
They can be explicitly converted to intended types. Numbers and strings
have a set of methods that covers conversion, formatting, mathematical,
and string processing. Strings also represent URLs and file, they have
methods like A chunk of text can be used via the enhanced here-doc mechanism. Text can be aligned and the indentation is stripped. Expressions can be embedded. Date and time values can be created in various ways. They have a number of attributes, some are writable.
Arrays and linked lists share the same interface. The only difference is
their creation. They can be initialized; elements can be added to the end
or front. Other arrays/lists can be merged in. The best way to enumerate
an array is the Objects and ordered maps stores a number of name-value mapping. Ordered maps maintain the order of the keys that were added to it, where structs don't. The keys can be returned as an array, which is the way to enumerate sturcts; they may be returned sorted or filtered (by user-defined functions); they can even be sorted and/or filtered based on the values. Stacks and queues are also supported.
8. Code Listings
|