picolisp-3.1.5.2.orig/ 0000755 0000000 0000000 00000000000 12265263724 013150 5 ustar root root picolisp-3.1.5.2.orig/doc/ 0000755 0000000 0000000 00000000000 12265263724 013715 5 ustar root root picolisp-3.1.5.2.orig/doc/ref_.html 0000644 0000000 0000000 00000043004 12265263724 015517 0 ustar root root
(! . exe) -> any
exe
is
displayed, and a read-eval-print-loop is entered (with !
as its
prompt character), to evaluate expressions and examine the current program
environment. An empty input line terminates the read-eval-print-loop, the
environment and I/O channels are restored, and the result of exe
is
returned. !
is normally inserted into existing programs with the
debug
function. See also e
, ^
and
*Dbg
.
: (de foo (N) (and (println 1) (! println N) (println 2)))
-> foo
: (foo 7)
1 # Executed '(println 1)'
(println N) # Entered breakpoint
! N # Examine the value of 'N'
-> 7
! (e) # Evaluate '^', i.e. (println N)
7
-> 7
! (e @) # Evaluate '@' -> the result of '(println 1)'
-> 1
! # Empty line: continue
7 # Executed '(println N)'
2 # Executed '(println 2)'
-> 2
($ sym|lst lst . prg) -> any
sym|lst
is printed
to the console with a proper indentation, followed by a colon :
. If
a function is traced, the first argument is the function symbol, else if a
method is traced, it is a cons pair of message and class. The second argument
lst
should be a list of symbols, identical to the function's
argument list. The current values of these symbols are printed, followed by a
newline. Then prg
is executed, and its return value printed in a
similar way (this time with an equals sign =
instead of a colon)
and returned. $
is normally inserted into existing programs with
the trace
function.
: (de foo (A B) ($ foo (A B) (* A B)))
-> foo
: (foo 3 4)
foo : 3 4 # Function entry, arguments 3 and 4
foo = 12 # Function exit, return value 12
-> 12
($dat 'sym1 ['sym2]) -> dat
sym1
in ISO format to a date
, optionally using a delimiter character
sym2
. See also dat$
,
$tim
, strDat
and expDat
.
: ($dat "20070601")
-> 733134
: ($dat "2007-06-01" "-")
-> 733134
($tim 'sym) -> tim
time
. The
minutes and seconds are optional and default to zero. See also tim$
and $dat
.
: (time ($tim "10:57:56"))
-> (10 57 56)
: (time ($tim "10:57"))
-> (10 57 0)
: (time ($tim "10"))
-> (10 0 0)
(% 'num ..) -> num
num
arguments. The sign of the result is that of the first argument. When one of the
arguments evaluates to NIL
, it is returned immediately. See also
/
and */
.
: (% 17 5)
-> 2
: (% -17 5) # Sign is that of the first argument
-> -2
: (% 5 2)
-> 1
: (% 15 10)
-> 5
: (% 15 10 2) # (% 15 10) -> 5, then (% 5 2) -> 1
-> 1
(& 'num ..) -> num
AND
of all num
arguments. When
one of the arguments evaluates to NIL
, it is returned immediately.
See also |
, x|
and bit?
.
: (& 6 3)
-> 2
: (& 7 3 1)
-> 1
(* 'num ..) -> num
num
arguments. When one of the
arguments evaluates to NIL
, it is returned immediately. See also
/
, */
, +
and
-
.
: (* 1 2 3)
-> 6
: (* 5 3 2 2)
-> 60
(** 'num1 'num2) -> num
num1
to the power of
num2
.
: (** 2 3)
-> 8
: (** 100 100)
-> 10000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000
(*/ 'num1 ['num2 ..] 'num3) -> num
num1
and all following num2
arguments, divided by the num3
argument. The result is rounded to
the nearest integer value. When one of the arguments evaluates to
NIL
, it is returned immediately. Note that */
is
especially useful for fixed point arithmetic, by multiplying with (or dividing
by) the scale factor. See also *
,
/
, +
, -
and
sqrt
.
: (*/ 3 4 2)
-> 6
: (*/ 1234 2 10)
-> 247
: (*/ 100 6)
-> 17
: (scl 2)
-> 2
: (format (*/ 3.0 1.5 1.0) *Scl)
-> "4.50"
(+ 'num ..) -> num
num
arguments. When one of the arguments
evaluates to NIL
, it is returned immediately. See also inc
, -
,
*
, /
and */
.
: (+ 1 2 3)
-> 6
(- 'num ..) -> num
num
argument and all
following arguments. If only a single argument is given, it is negated. When one
of the arguments evaluates to NIL
, it is returned immediately. See
also dec
, +
, *
,
/
and */
.
: (- 7)
-> -7
: (- 7 2 1)
-> 4
(-> any [num]) -> any
any
(typically a Pilog variable, or an expression of variables) at top
level (or level num
) in the current environment. See also prove
and unify
.
: (? (append (1 2 3) (4 5 6) @X) (^ @ (println 'X '= (-> @X))))
X = (1 2 3 4 5 6)
@X=(1 2 3 4 5 6)
-> NIL
(/ 'num ..) -> num
num
argument successively divided by all
following arguments. When one of the arguments evaluates to NIL
, it
is returned immediately. See also *
,
*/
, %
, +
and
-
.
: (/ 12 3)
-> 4
: (/ 60 -3 2 2)
-> -5
(: sym|0 [sym1|cnt ..]) -> any
any
from the properties of a symbol, or from a
list, by applying the get
algorithm to
This
and the following arguments. Used typically in methods or
with
bodies. (: ..)
is
equivalent to (; This ..)
. See also ;
, =:
and
::
.
: (put 'X 'a 1)
-> 1
: (with 'X (: a))
-> 1
(:: sym [sym1|cnt .. sym2]) -> var
sym
or sym2
from a symbol. That symbol is This
(if no other arguments are
given), or a symbol found by applying the get
algorithm to This
and the
following arguments. The property (the cons pair, not just its value) is
returned, suitable for direct (destructive) manipulations with functions
expecting a var
argument. Used typically in methods or with
bodies. See also =:
, prop
and :
.
: (with 'X (=: cnt 0) (inc (:: cnt)) (: cnt))
-> 1
(; 'sym1|lst [sym2|cnt ..]) -> any
any
from the properties of a symbol, or from a
list, by applying the get
algorithm to
sym1|lst
and the following arguments. See also :
, =:
and
::
.
: (put 'A 'a 1)
-> 1
: (put 'A 'b 'B)
-> B
: (put 'B 'c 7)
-> 7
: (; 'A a)
-> 1
: (; 'A b c)
-> 7
(< 'any ..) -> flg
T
when all arguments any
are in strictly
increasing order. See also Comparing.
: (< 3 4)
-> T
: (< 'a 'b 'c)
-> T
: (< 999 'a)
-> T
(<= 'any ..) -> flg
T
when all arguments any
are in strictly
non-decreasing order. See also Comparing.
: (<= 3 3)
-> T
: (<= 1 2 3)
-> T
: (<= "abc" "abc" "def")
-> T
(<> 'any ..) -> flg
T
when not all any
arguments are equal
(structure equality). (<> 'any ..)
is equivalent to (not (=
'any ..))
. See also Comparing.
: (<> 'a 'b)
-> T
: (<> 'a 'b 'b)
-> T
: (<> 'a 'a 'a)
-> NIL
(= 'any ..) -> flg
T
when all any
arguments are equal
(structure equality). See also Comparing.
: (= 6 (* 1 2 3))
-> T
: (= "a" "a")
-> T
: (== "a" "a")
-> T
: (= (1 (2) 3) (1 (2) 3))
-> T
(=0 'any) -> 0 | NIL
0
when any
is a number with value zero.
See also n0
, lt0
, le0
, ge0
and gt0
.
: (=0 (- 6 3 2 1))
-> 0
: (=0 'a)
-> NIL
(=: sym|0 [sym1|cnt .. sym2|0] 'any)
any
for a property key sym
or
sym2
(or in the symbol value for zero) in a symbol. That symbol is
This
(if no other arguments are given), or a symbol found by
applying the get
algorithm to
This
and the following arguments. Used typically in methods or
with
bodies. See also put
, :
and ::
.
: (with 'X (=: a 1) (=: b 2))
-> 2
: (get 'X 'a)
-> 1
: (get 'X 'b)
-> 2
(== 'any ..) -> flg
T
when all any
arguments are the same
(pointer equality). See also n==
and Comparing.
: (== 'a 'a)
-> T
: (== 'NIL NIL (val NIL) (car NIL) (cdr NIL))
-> T
: (== (1 2 3) (1 2 3))
-> NIL
(==== ['sym ..]) -> NIL
sym
arguments are (re-)inserted into the transient index.
See also extern
and intern
.
: (setq S "abc") # Read "abc"
-> "abc"
: (== S "abc") # Read again, get the same symbol
-> T
: (====) # Close scope
-> NIL
: (== S "abc") # Read again, get another symbol
-> NIL
(=T 'any) -> flg
T
when any
is the symbol T
.
(=T X)
is equivalent to (== T X)
. See also nT.
: (=T 0)
-> NIL
: (=T "T")
-> NIL
: (=T T)
-> T
(> 'any ..) -> flg
T
when all arguments any
are in strictly
decreasing order. See also Comparing.
: (> 4 3)
-> T
: (> 'A 999)
-> T
(>= 'any ..) -> flg
T
when all arguments any
are in strictly
non-increasing order. See also Comparing.
: (>= 'A 999)
-> T
: (>= 3 2 2 1)
-> T
(>> 'cnt 'num) -> num
num
argument by cnt
bit-positions. If cnt
is negative, a corresponding left shift is
performed.
: (>> 1 8)
-> 4
: (>> 3 16)
-> 2
: (>> -3 16)
-> 128
: (>> -1 -16)
-> -32
(? [sym ..] [pat 'any ..] . lst) -> flg
?
is a non-evaluating front-end to the query
function. It displays each result, waits
for console input, and terminates when a non-empty line is entered. If a
preceding list of (non-pattern-) symbols is given, they will be taken as rules
to be traced by prove
. The list of
variable/value pairs is passed to goal
for an initial Pilog environment. See also pilog
and solve
.
: (? (append (a b c) (d e f) @X))
@X=(a b c d e f)
-> NIL
: (? (append @X @Y (a b c)))
@X=NIL @Y=(a b c)
@X=(a) @Y=(b c)
@X=(a b) @Y=(c)
@X=(a b c) @Y=NIL
-> NIL
: (? (append @X @Y (a b c)))
@X=NIL @Y=(a b c). # Stopped
-> NIL
: (? append (append @X @Y (a b c))) # Trace 'append'
1 (append NIL (a b c) (a b c))
@X=NIL @Y=(a b c)
2 (append (a . @X) @Y (a b c))
1 (append NIL (b c) (b c))
@X=(a) @Y=(b c). # Stopped
-> NIL
@
@
Result
). When @
is used as a formal parameter in lambda expressions, it denotes a variable number of
evaluated arguments.
@@
@ Result
).
@@@
@ Result
).
^
debug
, !
, e
and
*Dbg
.
: (* (+ 3 4) (/ 7 0))
!? (/ 7 0)
Div/0
? ^
-> (/ 7 0)
(| 'num ..) -> num
OR
of all num
arguments. When
one of the arguments evaluates to NIL
, it is returned immediately.
See also x|
, &
and bit?
.
: (| 1 2)
-> 3
: (| 1 2 4 8)
-> 15
(c) Software Lab. Alexander Burger
The Pilog select/3 predicate is rather complex, and quite different from other predicates. This document tries to explain it in detail, and shows some typical use cases.
select
takes at least three arguments:
We will describe these arguments in the following, but demonstrate them first on a concrete example.
The examples in this document will use the demo application in "app/*.l" (see also "A Minimal Complete Application"). To get an interactive prompt, start it as
$ pil app/main.l -main +
:
As ever, you can terminate the interpreter by hitting Ctrl-D
.
For a first, typical example, let's write a complete call to solve that returns a list of articles with numbers between 1 and 4, which contain "Part" in their description, and have a price less than 100:
(let (Nr (1 . 4) Nm Part Pr '(NIL . 100.00))
(solve
(quote
@Nr Nr
@Nm Nm
@Pr Pr
(select (@Item)
((nr +Item @Nr) (nm +Item @Nm) (pr +Item @Pr))
(range @Nr @Item nr)
(part @Nm @Item nm)
(range @Pr @Item pr) ) )
@Item ) )
This expression will return, with the default database setup of "app/init.l",
a list of exactly one item ({3-2})
, the item with the number 2.
The let
statement assigns values to
the search parameters for number Nr
, description Nm
and price Pr
. The Pilog query (the first argument to
solve
) passes these values to the Pilog variables @Nr
,
@Nm
and @Pr
. Ranges of values are always specified by
cons pairs, so (1 . 4)
includes the numbers 1 through 4, while
(NIL . 100.00)
includes prices from minus infinite up to one
hundred.
The list of unification variables is
(@Item)
The list of generator clauses is
((nr +Item @Nr) (nm +Item @Nm) (pr +Item @Pr))
The filter clauses are
(range @Nr @Item nr)
(part @Nm @Item nm)
(range @Pr @Item pr)
As stated above, the first argument to select
should be a list
of variables. These variables communicate values (via unify
) from the select
environment to the enclosing Pilog environment.
The first variable in this list (@Item
in the above example) is
mandatory, it takes the direct return value of select
. Additional
optional variables may be unified by clauses in the body of select
,
and return further values.
The second argument to select
is a list of "generator clauses".
Each of these clauses specifies some kind of database B-Tree +index
, to be traversed by
select
, step by step, where each step returns a suitable single
database object. In the simplest case, they consist like here just of a relation
name (e.g. nr
), a class (e.g. +Item
), an optional hook
specifier (not in this example), and a pattern (values or ranges, e.g. (1 . 4)
or "Part").
The generator clauses are the core of 'select'. In some way, they behave
analog to or/2
, as each of them
generates a sequence of values. However, the generator clauses behave different,
as they will not generate an exhaustive set of values upon backtracking, one
after the other, where the next gets its turn when the previous one is
exhausted. Instead, all clauses will generate their values quasi-parallel, with
a built-in optimization so that successful clauses will be called with a higher
probability. "Successful" means that the returned values successfully pass
select
's filter clauses.
In its basic form, a generator clause is equivalent to the db/3
predicate, stepping through a single
B-Tree. The clause
(nr +Item @Nr)
generates the same values as would be produced by a stand-alone Pilog clause
(db nr +Item @Nr @Item)
as can be seen in the following two calls:
: (? (db nr +Item (1 . 4) @Item))
@Item={3-1}
@Item={3-2}
@Item={3-3}
@Item={3-4}
-> NIL
: (? (select (@Item) ((nr +Item (1 . 4)))))
@Item={3-1}
@Item={3-2}
@Item={3-3}
@Item={3-4}
-> NIL
select
is mostly useful if more than one generator clause is
involved. The tree search parameters of all clauses are meant to form a logical
AND
. Only those objects should be returned, for which all search
parameters (and the associated filter clauses) are valid. As soon as one of the
clauses finishes stepping through its database (sub)tree, the whole call to
select
will terminate, because further values returned from other
generator clauses cannot be part of the result set.
Therefore, select
would find all results most quickly if it
could simply call only the generator clause with the smallest (sub)tree.
Unfortunately, this is usually not known in advance. It depends on the
distribution of the data in the database, and on the search parameters to each
generator clause.
Instead, select
single-steps each generator clause in turn, in a
round-robin scheme, applies the filter clauses to each generated object, and
re-arranges the order of generator clauses so that the more successful clauses
will be preferred. This process usually converges quickly and efficiently.
A generator clause can also combine several (similar) indexes into a single one. Then the clause is written actually as a list of clauses.
For example, a generator clause to search for a customer by phone number is
(tel +CuSu @Tel)
If we want to search for a customer without knowing whether a given number is a
normal or a mobile phone number, then a combined generator clause searching both
index trees could look like
((tel +CuSu @Tel mob +CuSu @Tel))
The generator will first traverse all matching entries in the +Ref
tree of the tel
relation, and
then, when these are exhausted, all matching entries in the mob
index tree.
But generator clauses are not limited to the direct B-Tree interaction of
db/3
. They can also traverse trees of
associated objects, and then follow +Link
/ +Joint
relations, or tree relations like
+Ref
to arrive at database objects
with a type suitable for return values from select
.
To locate appropriate objects from associated objects, the generator clause can contain - in addition to the standard relation/class/pattern specification (see Generator Clauses above) - an arbitrary number of association specifiers. Each association specifier can be
+Link
or
+Joint
will be followed, or a
+List
of those will be traversed to
locate appropriate objects.
+index
to be traversed to locate appropriate
objects.
+Ord
(order) objects. Orders can
be searched for order number and date, customer name and city, item description
and supplier name:
(select (@@)
((nr +Ord @Nr) (dat +Ord @Dat)
(nm +CuSu @Cus (cus +Ord))
(ort +CuSu @Ort (cus +Ord))
(nm +Item @Item (itm +Pos) ord)
(nm +CuSu @Sup (sup +Item) (itm +Pos) ord) )
While (nr +Ord @Nr)
and (dat +Ord @Dat)
are direct
index traversals, (nm +CuSu @Cus (cus +Ord))
iterates the
nm
(name) index of customers/suppliers +CuSu
, and then
follows the +Ref
+Link
of the cus
relation to the
orders. The same applies to the search for city names via ort
.
The most complex example is (nm +CuSu @Sup (sup +Item) (itm +Pos)
ord)
, where the supplier name is searched in the nm
tree of
+CuSu
, then the +Ref
tree
(sup +Item)
tree is followed to locate items of that supplier, then
all positions for those items are found using (itm +Pos)
, and
finally the ord
+Joint
is followed to arrive at the order object(s).
In the most general case, a generator clause can be an arbitrary Pilog query.
Often this is a query to a database on a remote machine, using the remote/2
predicate, or some other resource
not accessible via database indexes, like iterating a +List
of +Link
s or +Joint
s.
Syntactically, such a generator clause is recognized by the fact that its CAR is a Pilog variable to denote the return value.
The second argument is a list of Pilog variables to communicate values (via
unify
) from the surrounding
select
environment.
The third argument is the actual list of clauses for the nested query.
Finally, an arbitrary number of association specifiers may follow, as described in the Indirect Object Associations section.
We can illustrate this with a somewhat useless (but simple) example, which replaces the standard generators for item number and supplier name
(select (@Item)
(
(nr +Item @Nr)
(nm +CuSu @Sup (sup +Item))
)
...
with the equivalent form
(select (@Item)
(
(@A (@Nr) ((db nr +Item @Nr @A)))
(@B (@Sup) ((db nm +CuSu @Sup @B)) (sup +Item))
)
That is, a query with the db/3
tree
iteration predicate is used to generate appropriate values.
The generator clauses produce - independent from each other - lots of
objects, which match the patterns of individual generator clauses, but not
necessarily the desired result set of the total select
call.
Therefore, the filter clauses are needed to retain the good, and throw away the
bad objects. In addition, they give feedback to the generator for optimizing its
traversal priorities (as described in Generator Clauses).
select
then collects all objects which passed through the
filters into a unique list, to avoid duplicates which would otherwise appear,
because most objects can be found by more than one generator clause.
Technically, the filters are normal Pilog clauses, which just happen to be
evaluated in the context of select
. Arbitrary Pilog predicates can
be used, though there exist some predicates (e.g. isa/2
, same/3
, bool/3
, range/3
, head/3
, fold/3
, part/3
or tolr/3
) especially suited for that task.
Assume we want to know how many pieces of item #2 were sold in the year 2007.
Then we must find all +Pos
(position) objects referring to that
item and at the same time belonging to orders of the year 2007 (see the class
definition for +Pos
in "app/er.l"). The number of sold pieces is
then in the cnt
property of the +Pos
objects.
As shown in the complete select
below, we will hold the item
number in the variable @Nr
and the date range for the year in
@Year
.
Now, all positions referred by item #2 can be found by the generator clause
(nr +Item @Nr (itm +Pos))
and all positions sold in 2007 can be found by
(dat +Ord @Year pos)
However, the combination of both generator clauses
(select (@Pos)
((nr +Item @Nr (itm +Pos)) (dat +Ord @Year pos)) )
will probably generate too many results, namely all positions with item #3 OR from the year 2007. Thus, we need two filter clauses. With them, the full search expression will be:
(?
@Nr 2 # Item number
@Year (cons (date 2007 1 1) (date 2007 12 31)) # Date range 2007
(select (@Pos)
((nr +Item @Nr (itm +Pos)) (dat +Ord @Year pos)) # Generator clauses
(same @Nr @Pos itm nr) # Filter item number
(range @Year @Pos ord dat) ) ) # Filter order date
For completeness, let's calculate the total count of sold items:
(let Cnt 0 # Counter variable
(pilog
(quote
@Nr 2
@Year (cons (date 2007 1 1) (date 2007 12 31))
(select (@Pos)
((nr +Item @Nr (itm +Pos)) (dat +Ord @Year pos))
(same @Nr @Pos itm nr)
(range @Year @Pos ord dat) ) )
(inc 'Cnt (get @Pos 'cnt)) ) # Increment total count
Cnt ) # Return count
As mentioned under Filter Clauses, some predicates
exists mainly for select
filtering.
Some of these predicates are of general use: isa/2
can be used to check for a type,
same/3
checks for a definite vaue,
bool/3
looks if the value is
non-NIL
. These predicates are rather independent of the +relation
type.
range/3
checks whether a value
is within a given range. This could be used with any +relation
type, but typically it will be
used for numeric (+Number
) or time
( +Date
and +Time
) relations.
Other predicates make only sense in the context of a certain +relation
type:
head/3
is mainly intended for
(+Key +String)
or (+Ref +String)
relations,
fold/3
is useful for (+Fold +Ref +String)
relations,
part/3
for (+Fold +Idx +String)
relations, and
tolr/3
for (+Sn +Idx +String)
relations.
(c) Software Lab. Alexander Burger
This document demonstrates some aspects of the PicoLisp system in detail and example. For a general description of the PicoLisp kernel please look at the PicoLisp Reference.
This is not a Lisp tutorial, as it assumes some basic knowledge of programming, Lisp, and even PicoLisp. Please read these sections before coming back here: Introduction and The PicoLisp Machine. This tutorial concentrates on the specificities of PicoLisp, and its differences with other Lisp dialects.
If not stated otherwise, all examples assume that PicoLisp was started from a global installation (see Installation) from the shell prompt as
$ pil +
:
It loads the PicoLisp base system and the debugging environment, and waits
for you to enter input lines at the interpreter prompt (:
). You can
terminate the interpreter and return to the shell at any time, by either hitting
the Ctrl-D
key, or by executing the function (bye)
.
Please note that special handling is done during character input. This one
is incompatible with rlwrap
for example but is more powerful.
vi
-like command-line editing (typos fixes and history with ESC,
h
, j
, k
and l
but not
arrows),"
appear).If you prefer to use Emacs, please use the picolisp-mode bundled in the "el/" directory (that is "@lib/el" for a local installation, or some system dependent directory for a global installation).
If you feel that you absolutely have to use an IDE, rlwrap
or
another input front-end, please create an empty "~/.pil/editor" file. This
effectively disables the command line editor. Note that in this case, however,
you will not have the TAB symbol completion feature available during command
line editing.
If you are new to PicoLisp, you might want to read the following sections in the given order, as some of them assume knowledge about previous ones. Otherwise just jump anywhere you are interested in.
PicoLisp permanently reads input from the current input channel (i.e. the console in interactive mode), evaluates it, and prints the result to the current output channel. This is called a "read-eval-print-loop" (REPL).
This is the default line editor, as it needs less system resources and works also on dumb terminals. It is similar to - though simpler than - the 'vi' edit modes of the 'korn' and 'bash' shells. For an analog 'emacs' style editor, please see below.
It is very helpful - though not absolutely necessary - when you know how to
use the vi
text editor.
To alleviate the task of manual line input, a command line editor is provided
which is similar to (though much simpler than) the readline
feature
of the bash
shell. Only a subset of the vi
mode is
supported, which is restricted to single-key commands (the "real"
vi
supports multi-key commands and the modification of most
commands with count prefixes). It is loaded at startup in debug mode, you find
its source in "lib/led.l".
You can enter lines in the normal way, correcting mistypes with the BACKSPACE key, and terminating them with the ENTER key. This is the Insert Mode.
If you hit ESC, you get into Command Mode. Now you can navigate
horizontally in the current input line, or vertically in the history of
previously entered lines, with key commands borrowed from the vi
editor (only h
, j
, k
and l
and not arrows). Note, however, that there is always only a single line visible.
Let's say you did some calculation
: (* (+ 2 3) (- 7 2))
-> 25
:
If you want to repeat a modified version of this command, using
8
instead of 7
, you don't have to re-type the
whole command, but type
k
to get one line "up"
f
and 7
to "find" the character 7
r
and 8
to "replace" with 8
Then you hit ENTER to execute the modified line. Instead of jumping to the
7
with the "find" command, you may also type l
(move
"right") repeatedly till you reach the correct position.
The key commands in the Command Mode are listed below. Some commands change the mode back to Insert Mode as indicated in parentheses. Deleting or changing a "word" take either the current atom (number or symbol), or a whole expression when the cursor is at a left parenthesis.
k
- Go up one line
j
- Go down one line
l
- Go right one character
h
- Go left one character
w
- Go right one word
b
- Go back (left) one word
0
- Go to the beginning of the line
$
- Go to the end of the line
i
- Enter Insert Mode at the cursor position
a
- Append (Insert Mode) after the cursor position
A
- Append (Insert Mode) at the end of the line
I
- Insert (Insert Mode) at the beginning of the line
x
- Delete the character at the cursor position
X
- Delete the character left of the cursor position
r
- Replace the character at the cursor position with the next key
s
- Substitute the character at the cursor position (Insert Mode)
S
- Substitute the whole line (Insert Mode)
d
- Delete the word at the cursor position (Insert Mode)
D
- Delete the rest of the line
c
- Change the word at the cursor position (Insert Mode)
C
- Change the rest of the line (Insert Mode)
f
- Find next key in the rest of the current line
p
- Paste data deleted with x
, X
, d
or D
after the cursor position
P
- Paste data deleted with x
, X
, d
or D
before the cursor position
/
- Accept an input pattern and search the history for it
n
- Search for next occurrence of pattern (as entered with /
)
N
- Search for previous occurrence of pattern
%
- Go to matching parenthesis
~
- Convert character to opposite (lower or upper) case and move right
u
- Undo the last change (one level only)
U
- Undo all changes of the current line
g
- Display current contents of cut buffer (not in vi
)
Notes:
d
command corresponds to the dw
command of the
vi
editor, and c
corresponds to cw
.
@
" characters as wildcards.
The following two key-combinations work both in Insert and Command Mode:
Ctrl-D
will immediately terminate the current process.
Ctrl-X
discards all input, abandons further processing, and
returns to the interpreter's top level (equivalent to invoking quit
). This is also useful when the program
stopped at a breakpoint (see single-stepping Debugging), or
after program execution was interrupted with Ctrl-C
.
Besides these two keys, in Insert Mode only the following keys have a special meaning:
Ctrl-H
) and DEL erase the character to the left
Ctrl-V
inserts the next key literally
Ctrl-E
lets you edit
the history
You can switch the command line editor to an 'emacs' style, if you call the
function (em)
(i.e. without arguments). A single call is enough.
Alternatively, you could invoke PicoLisp at least once with the -em
command line option
$ pil -em +
:
The style will be remembered in a file "~/.pil/editor", and used in all subsequent PicoLisp sessions.
To switch back to 'vi' style, call (vi)
, use the
-vi
command line option, or simply remove "~/.pil/editor".
Please take some time to experiment and to get used to command line editing. It will make life much easier in the future :-)
PicoLisp provides some functionality for inspecting pieces of data and code within the running system.
print
,
size
...
But you will appreciate some more powerful tools like:
match
, a predicate which
compares S-expressions with bindable wildcards when matching,The most commonly used tool is probably the show
function. It takes a symbolic argument,
and shows the symbol's name (if any), followed by its value, and then the
contents of the property list on the following lines (assignment of such things
to a symbol can be done with set
,
setq
, and put
).
: (setq A '(This is the value)) # Set the value of 'A'
-> (This is the value)
: (put 'A 'key1 'val1) # Store property 'key1'
-> val1
: (put 'A 'key2 'val2) # and 'key2'
-> val2
: (show 'A) # Now 'show' the symbol 'A'
A (This is the value)
key2 val2
key1 val1
-> A
show
accepts an arbitrary number of arguments which are
processed according to the rules of get
, resulting in a symbol which is showed then.
: (put 'B 'a 'A) # Put 'A' under the 'a'-property of 'B'
-> A
: (setq Lst '(A B C)) # Create a list with 'B' as second argument
-> (A B C)
: (show Lst 2 'a) # Show the property 'a of the 2nd element of 'Lst'
A (This is the value) # (which is 'A' again)
key2 val2
key1 val1
-> A
Similar to show
is edit
. It takes an arbitrary number of symbolic
arguments, writes them to a temporary file in a format similar to
show
, and starts the vim
editor with that file.
: (edit 'A 'B)
The vim
window will look like
A (This is the value)
key1 val1
key2 val2
(********)
B NIL
a A # (This is the value)
(********)
Now you can modify values or properties. You should not touch the
parenthesized asterisks, as they serve as delimiters. If you position the cursor
on the first character of a symbol name and type 'K
' ("Keyword
lookup"), the editor will be restarted with that symbol added to the editor
window. 'Q
' (for "Quit") will bring you back to the previous view.
edit
is also very useful to browse in a database. You can follow
the links between objects with 'K
', and even - e.g. for low-level
repairs - modify the data (but only if you are really sure about what you are
doing, and don't forget to commit
when you are done).
The pretty-print function pp
takes a symbol that has a function defined (or two symbols that specify message
and class for a method definition), and displays that definition in a formatted
and indented way.
: (pp 'pretty)
(de pretty (X N . @)
(setq N (abs (space (or N 0))))
(while (args)
(printsp (next)) )
(if (or (atom X) (>= 12 (size X)))
(print X)
(while (== 'quote (car X))
(prin "'")
(pop 'X) )
(let Z X
(prin "(")
(cond
((and (pair (car X)) (> (size @) 12))
(pretty (pop 'X) (- -3 N)) )
((memq (print (pop 'X)) *PP)
(cond
((memq (car Z) *PP1)
(if (and (pair (car X)) (pair (cdar X)))
(when (>= 12 (size (car X)))
(space)
(print (pop 'X)) )
(space)
(print (pop 'X))
(when (or (atom (car X)) (>= 12 (size (car X))))
(space)
(print (pop 'X)) ) ) )
((memq (car Z) *PP2)
(inc 'N 3)
(loop
(prinl)
(pretty (cadr X) N (car X))
(NIL (setq X (cddr X)) (space)) ) )
((or (atom (car X)) (>= 12 (size (car X))))
(space)
(print (pop 'X)) ) ) )
((and (memq (car Z) *PP3) (>= 12 (size (head 2 X))))
(space)
(print (pop 'X) (pop 'X)) ) )
(when X
(loop
(T (== Z X) (prin " ."))
(T (atom X) (prin " . ") (print X))
(prinl)
(pretty (pop 'X) (+ 3 N))
(NIL X) )
(space) )
(prin ")") ) ) )
-> pretty
The style is the same as we use in source files:
size
is greater than 12), pretty-print the CAR
on the current line, and each element of the CDR recursively on its own line.
more
is a simple tool that displays
the elements of a list one by one. It stops after each element and waits for
input. If you just hit ENTER, more
continues with the next element,
otherwise (usually I type a dot (.
) followed by ENTER) it
terminates.
: (more (1 2 3 4 5 6))
1 # Hit ENTER
2. # Hit '.' and ENTER
-> T # stopped
Optionally more
takes a function as a second argument and
applies that function to each element (instead of the default print
). Here, often show
or
pp
(see below) is used.
: (more '(A B)) # Step through 'A' and 'B'
A
B
-> NIL
: (more '(A B) show) # Step through 'A' and 'B' with 'show'
A (This is the value) # showing 'A'
key2 val2
key1 val1
# Hit ENTER
B NIL # showing 'B'
a A
-> NIL
The what
function returns a list of
all internal symbols in the system which match a given pattern (with
'@
' wildcard characters).
: (what "prin@")
-> (prin print prinl print> printsp println)
The function who
returns "who
contains that", i.e. a list of symbols that contain a given argument
somewhere in their value or property list.
: (who 'print)
-> (query pretty pp msg more "edit" view show (print> . +Date) rules select
(print> . +relation))
A dotted pair indicates either a method definition or a property entry. So
(print> . +relation)
denotes the print>
method of
the +relation
class.
who
can be conveniently combined with more
and
pp
:
: (more (who 'print) pp)
(de query ("Q" "Dbg") # Pretty-print these functions one by one
(use "R"
(loop
(NIL (prove "Q" "Dbg"))
(T (=T (setq "R" @)) T)
(for X "R"
(space)
(print (car X))
(print '=)
(print (cdr X))
(flush) )
(T (line)) ) ) )
(de pretty (X N . @)
...
The argument to who
may also be a pattern list (see match
):
: (who '(print @ (val @)))
-> (show)
: (more (who '(% @ 7)) pp)
(de day (Dat Lst)
(get
(or Lst *DayFmt)
(inc (% (inc Dat) 7)) ) )
(de _week (Dat)
(/ (- Dat (% (inc Dat) 7)) 7) )
The function can
returns a list
which indicates which classes can accept a given message. Again, this
list is suitable for iteration with pp
:
: (can 'del>) # Which classes accept 'del>' ?
-> ((del> . +List) (del> . +Entity) (del> . +relation))
: (more (can 'del>) pp) # Inspect the methods with 'pp'
(dm (del> . +List) (Obj Old Val)
(and ((<> Old Val) (delete Val Old)) )
(dm (del> . +Entity) (Var Val)
(when
(and
Val
(has> (meta This Var) Val (get This Var)) )
(let Old (get This Var)
(rel>
(meta This Var)
This
Old
(put This Var (del> (meta This Var) This Old @)) )
(when (asoq Var (meta This 'Aux))
(relAux This Var Old (cdr @)) )
(upd> This Var Old) ) ) )
(dm (del> . +relation) (Obj Old Val)
(and ((<> Old Val) Val) )
dep
shows the dependencies in a
class hierarchy. That is, for a given class it displays the tree of its
(super)class(es) above it, and the tree of its subclasses below it.
To view the complete hierarchy of input fields, we start with the root class
+relation
:
: (dep '+relation)
+relation
+Bag
+Any
+Blob
+Link
+Joint
+Bool
+Symbol
+String
+Number
+Time
+Date
-> +relation
If we are interested in +Link
:
: (dep '+Link)
+relation
+Link
+Joint
-> +Link
This says that +Link
is a subclass of +relation
, and has a single subclass
(+Joint
).
Most of the time during programming is spent defining functions (or methods).
In the following we will concentrate on functions, but most will be true for
methods as well except for using dm
instead of de
.
The notorious "Hello world" function must be defined:
: (de hello ()
(prinl "Hello world") )
-> hello
The ()
in the first line indicates a function without arguments.
The body of the function is in the second line, consisting of a single
statement. The last line is the return value of de
, which here is
the defined symbol. From now on we will omit the return values of examples when
they are unimportant.
Now you can call this function this way:
: (hello)
Hello world
A function with an argument might be defined this way:
: (de hello (X)
(prinl "Hello " X) )
# hello redefined
-> hello
PicoLisp informs you that you have just redefined the function. This might be a useful warning in case you forgot that a bound symbol with that name already existed.
: (hello "world")
Hello world
: (hello "Alex")
Hello Alex
Normally, PicoLisp evaluates the arguments before it passes them to a function:
: (hello (+ 1 2 3))
Hello 6
: (setq A 1 B 2) # Set 'A' to 1 and 'B' to 2
-> 2
: (de foo (X Y) # 'foo' returns the list of its arguments
(list X Y) )
-> foo
: (foo A B) # Now call 'foo' with 'A' and 'B'
-> (1 2) # -> We get a list of 1 and 2, the values of 'A' and 'B'
In some cases you don't want that. For some functions (setq
for example) it is better if the function
gets all arguments unevaluated, and can decide for itself what to do with them.
For such cases you do not define the function with a list of parameters, but give it a single atomic parameter instead. PicoLisp will then bind all (unevaluated) arguments as a list to that parameter.
: (de foo X
(list (car X) (cadr X)) ) # 'foo' lists the first two arguments
: (foo A B) # Now call it again
-> (A B) # -> We don't get '(1 2)', but '(A B)'
: (de foo X
(list (car X) (eval (cadr X))) ) # Now evaluate only the second argument
: (foo A B)
-> (A 2) # -> We get '(A 2)'
As a logical consequence, you can combine these principles. To define a function with 2 evaluated and an arbitrary number of unevaluated arguments:
: (de foo (X Y . Z) # Evaluate only the first two args
(list X Y Z) )
: (foo A B C D E)
-> (1 2 (C D E)) # -> Get the value of 'A' and 'B' and the remaining list
More common, in fact, is the case where you want to pass an arbitrary number
of evaluated arguments to a function. For that, PicoLisp recognizes the
symbol @
as a single atomic parameter and remembers all evaluated
arguments in an internal frame. This frame can then be accessed sequentially
with the args
, next
, arg
and rest
functions.
: (de foo @
(list (next) (next)) ) # Get the first two arguments
: (foo A B)
-> (1 2)
Again, this can be combined:
: (de foo (X Y . @)
(list X Y (next) (next)) ) # 'X' and 'Y' are fixed arguments
: (foo A B (+ 3 4) (* 3 4))
-> (1 2 7 12) # All arguments are evaluated
These examples are not very useful, because the advantage of a variable number of arguments is not used. A function that prints all its evaluated numeric arguments, each on a line followed by its squared value:
: (de foo @
(while (args) # Check if there are some args left
(println (next) (* (arg) (arg))) ) ) # Call the last arg (next) returned
: (foo (+ 2 3) (- 7 1) 1234 (* 9 9))
5 25
6 36
1234 1522756
81 6561
-> 6561
This next example shows the behaviour of args
and
rest
:
: (de foo @
(while (args)
(next)
(println (arg) (args) (rest)) ) )
: (foo 1 2 3)
1 T (2 3)
2 T (3)
3 NIL NIL
Finally, it is possible to pass all these evaluated arguments to another
function, using pass
:
: (de foo @
(pass println 9 8 7) # First print all arguments preceded by 9, 8, 7
(pass + 9 8 7) ) # Then add all these values
: (foo (+ 2 3) (- 7 1) 1234 (* 9 9))
9 8 7 5 6 1234 81 # Printing ...
-> 1350 # Return the result
quote
will do what you want (see
also this FAQ entry).
: ((quote (X) (* X X)) 9)
-> 81
: (setq f '((X) (* X X))) # This is equivalent to (de f (X) (* X X))
-> ((X) (* X X))
: f
-> ((X) (* X X))
: (f 3)
-> 9
There are two major ways to debug functions (and methods) at runtime: Tracing and single-stepping.
In this section we will use the REPL to explore the debugging facilities, but in the Scripting section, you will learn how to launch PicoLisp scripts with some selected functions debugged:
$ pil app/file1.l -"trace 'foo" -main -"debug 'bar" app/file2.l +
Tracing means letting functions of interest print their name and arguments when they are entered, and their name again and the return value when they are exited.
For demonstration, let's define the unavoidable factorial function (or just
load
the file "@doc/fun.l
"):
(de fact (N)
(if (=0 N)
1
(* N (fact (dec N))) ) )
With trace
we can put it in trace
mode:
: (trace 'fact)
-> fact
Calling fact
now will display its execution trace.
: (fact 3)
fact : 3
fact : 2
fact : 1
fact : 0
fact = 1
fact = 1
fact = 2
fact = 6
-> 6
As can be seen here, each level of function call will indent by an additional
space. Upon function entry, the name is separated from the arguments with a
colon (:
), and upon function exit with an equals sign
(=
) from the return value.
trace
works by modifying the function body, so generally it
works only for functions defined as lists (lambda expressions, see Evaluation). Tracing a C-function is possible, however,
when it is a function that evaluates all its arguments.
So let's trace the functions =0
and
*
:
: (trace '=0)
-> =0
: (trace '*)
-> *
If we call fact
again, we see the additional output:
: (fact 3)
fact : 3
=0 : 3
=0 = NIL
fact : 2
=0 : 2
=0 = NIL
fact : 1
=0 : 1
=0 = NIL
fact : 0
=0 : 0
=0 = 0
fact = 1
* : 1 1
* = 1
fact = 1
* : 2 1
* = 2
fact = 2
* : 3 2
* = 6
fact = 6
-> 6
To reset a function to its untraced state, call untrace
:
: (untrace 'fact)
-> fact
: (untrace '=0)
-> =0
: (untrace '*)
-> *
or simply use mapc
:
: (mapc untrace '(fact =0 *))
-> *
Single-stepping means to execute a function step by step, giving the
programmer an opportunity to look more closely at what is happening. The
function debug
inserts a breakpoint
into each top-level expression of a function. When the function is called, it
stops at each breakpoint, displays the expression it is about to execute next
(this expression is also stored into the global variable ^
) and enters a read-eval-loop. The programmer can
then
(d)
to recursively debug the
next expression (looping through subexpressions of this expression)
(e)
to evaluate the next
expression, to see what will happen without actually advancing on
Thus, in the simplest case, single-stepping consists of just hitting ENTER repeatedly to step through the function.
To try it out, let's look at the stamp
system function. You may need to have a
look at
=T
(T test),date
and time
(grab system date and time)
default
(conditional
assignments)
pack
(kind of concatenation), and
dat$
and tim$
(date and time formats)
: (pp 'stamp)
(de stamp (Dat Tim)
(and (=T Dat) (setq Dat (date T)))
(default Dat (date) Tim (time T))
(pack (dat$ Dat "-") " " (tim$ Tim T)) )
-> stamp
: (debug 'stamp) # Debug it
-> T
: (stamp) # Call it again
(and (=T Dat) (setq Dat (date T))) # stopped at first expression
! # ENTER
(default Dat (date) Tim (time T)) # second expression
! # ENTER
(pack (dat$ Dat "-") " " (tim$ ... # third expression
! Tim # inspect 'Tim' variable
-> 41908
! (time Tim) # convert it
-> (11 38 28)
! # ENTER
-> "2004-10-29 11:38:28" # done, as there are only 3 expressions
Now we execute it again, but this time we want to look at what's happening inside the second expression.
: (stamp) # Call it again
(and (=T Dat) (setq Dat (date T)))
! # ENTER
(default Dat (date) Tim (time T))
! # ENTER
(pack (dat$ Dat "-") " " (tim$ ... # here we want to look closer
! (d) # debug this expression
-> T
! # ENTER
(dat$ Dat "-") # stopped at first subexpression
! (e) # evaluate it
-> "2004-10-29"
! # ENTER
(tim$ Tim T) # stopped at second subexpression
! (e) # evaluate it
-> "11:40:44"
! # ENTER
-> "2004-10-29 11:40:44" # done
The breakpoints still remain in the function body. We can see them when we pretty-print it:
: (pp 'stamp)
(de stamp (Dat Tim)
(! and (=T Dat) (setq Dat (date T)))
(! default Dat (date) Tim (time T))
(! pack
(! dat$ Dat "-")
" "
(! tim$ Tim T) ) )
-> stamp
To reset the function to its normal state, call unbug
:
: (unbug 'stamp)
Often, you will not want to single-step a whole function. Just use
edit
(see above) to insert a single breakpoint (the exclamation
mark followed by a space) as CAR of an expression, and run your program.
Execution will then stop there as described above; you can inspect the
environment and continue execution with ENTER when you are done.
Input and output in PicoLisp is functional, in the sense that there are not variables assigned to file descriptors, which need then to be passed to I/O functions for reading, writing and closing. Instead, these functions operate on implicit input and output channels, which are created and maintained as dynamic environments.
Standard input and standard output are the default channels. Try reading a single expression:
: (read)
(a b c) # Console input
-> (a b c)
To read from a file, we redirect the input with in
. Note that comments and whitespace are
automatically skipped by read
:
: (in "@doc/fun.l" (read))
-> (de fact (N) (if (=0 N) 1 (* N (fact (dec N)))))
The skip
function can also be used
directly. To get the first non-white character in the file with char
:
: (in "@doc/fun.l" (skip "#") (char))
-> "("
from
searches through the input
stream for given patterns. Typically, this is not done with Lisp source files
(there are better ways), but for a simple example let's extract all items
immediately following fact
in the file,
: (in "@doc/fun.l" (while (from "fact ") (println (read))))
(N)
(dec N)
or the word following "(de " with till
:
: (in "@doc/fun.l" (from "(de ") (till " " T)))
-> "fact"
With line
, a line of characters is
read, either into a single transient symbol
(the type used by PicoLisp for strings),
: (in "@doc/tut.html" (line T))
-> "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://..."
or into a list of symbols (characters):
: (in "@doc/tut.html" (line))
-> ("<" "!" "D" "O" "C" "T" "Y" "P" "E" " " "H" "T" "M" "L" ...
line
is typically used to read tabular data from a file.
Additional arguments can split the line into fixed-width fields, as described in
the reference manual
. If, however, the
data are of variable width, delimited by some special character, the split
function can be used to extract the
fields. A typical way to import the contents of such a file is:
(load "@lib/import.l")
(in '("bin/utf2" "importFile.txt") # Pipe: Convert to UTF-8
(until (eof) # Process whole file
(let L (split (line) "^I") # TAB-delimited data
... use 'getStr', 'getNum' etc ... # process them
Some more examples with echo
:
(in "a" # Copy the first 40 Bytes
(out "b" # from file "a" to file "b"
(echo 40) ) )
(in "@doc/tut.html" # Show the HTTP-header
(line)
(echo "<body>") )
(out "file.mac" # Convert to Macintosh
(in "file.txt" # from Unix or DOS format:
(while (char)
(prin
(case @
("^M" NIL) # ignore CR
("^J" "^M") # convert CR to LF
(T @) ) ) ) ) ) # otherwise no change
(out "c" # Merge the contents of "a"
(in "b" # and "b" into "c"
(in "a"
(while (read) # Read an item from "a",
(println @ (in -1 (read))) ) ) ) ) # print it with an item from "b"
There are two possibilities to get the PicoLisp interpreter into doing useful work: via command line arguments, or as a stand-alone script.
The command line can specify either files for execution, or arbitrary Lisp
expressions for direct evaluation (see Invocation):
if an argument starts with a hyphen, it is evaluated, otherwise it is load
ed as a file. A typical invocation might
look like:
$ pil app/file1.l -main app/file2.l +
It loads the debugging environment, an application source file, calls the main function, and then loads another application source. In a typical development and debugging session, this line is often modified using the shell's history mechanisms, e.g. by inserting debugging statements:
$ pil app/file1.l -"trace 'foo" -main -"debug 'bar" app/file2.l +
Another convenience during debugging and testing is to put things into the command line (shell history) which would otherwise have to be done each time in the application's user interface:
$ pil app/file1.l -main app/file2.l -go -'login "name" "password"' +
The final production release of an application usually includes a shell script, which initializes the environment, does some bookkeeping and cleanup, and calls the application with a proper command line. It is no problem if the command line is long and complicated.
For small utility programs, however, this is overkill. Enter full PicoLisp scripts.
#!
", the operating
system kernel will pass this file to an interpreter program whose pathname is
given in the first line (optionally followed by a single argument). This is fast
and efficient, because the overhead of a subshell is avoided.
Let's assume you installed PicoLisp in the directory "/home/foo/picolisp/", and put links to the executable and the installation directory as:
$ ln -s /home/foo/picolisp /usr/lib/picolisp
$ ln -s /usr/lib/picolisp/bin/picolisp /usr/bin/picolisp
Then a simple hello-world script might look like:
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(prinl "Hello world!")
(bye)
If you write this into a text file, and use chmod
to set it to
"executable", it can be executed like any other command. Note that (because
#
is the comment character in PicoLisp) the first line will not be
interpreted, and you can still use that file as a normal command line argument
to PicoLisp (useful during debugging).
The fact that a hyphen causes evaluation of command line arguments can be
used to simulate something like command line options. The following script
defines two functions a
and f
, and then calls
(load T)
to process the rest of the
command line (which otherwise would be ignored because of the (bye)
statement):
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(de a ()
(println '-a '-> (opt)) )
(de f ()
(println '-f '-> (opt)) )
(load T)
(bye)
(opt
retrieves the next command line
option)
Calling this script (let's say we named it "testOpts") gives:
$ ./testOpts -f abc
-f -> "abc"
$ ./testOpts -a xxx -f yyy
-a -> "xxx"
-f -> "yyy"
We have to be aware of the fact, however, that the aggregation of arguments like
$ ./testOpts -axxx -fyyy
or
$ ./testOpts -af yyy
cannot be achieved with this simple and general mechanism of command line processing.
Utilities are typically used outside the context of the PicoLisp environment. All examples above assumed that the current working directory is the PicoLisp installation directory, which is usually all right for applications developed in that environment. Command line file arguments like "app/file1.l" will be properly found.
To allow utilities to run in arbitrary places on the host file system, the
concept of home directory substitution was introduced. The interpreter
remembers internally at start-up the pathname of its first argument (usually
"lib.l"), and substitutes any leading "@
" character in subsequent
file names with that pathname. Thus, to run the above example in some other
place, simply write:
$ /home/foo/picolisp/pil @app/file1.l -main @app/file2.l +
that is, supply a full path name to the initial command (here 'p'), or put it
into your PATH
variable, and prefix each file which has to be
loaded from the PicoLisp home directory with a @
character.
"Normal" files (not prefixed by @
) will be opened or created
relative to the current working directory as usual.
Stand-alone scripts will often want to load additional modules from the PicoLisp environment, beyond the "lib.l" we provided in the first line of the hello-world script. Typically, at least a call to
(load "@lib/misc.l")
(note the home directory substitution) will be included near the beginning of the script.
As a more complete example, here is a script which extracts the date, name and size of the latest official PicoLisp release version from the download web site, and prints it to standard output:
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@lib/misc.l" "@lib/http.l")
(use (@Date @Name @Size)
(when
(match
'(@Date ~(chop " - <a href=\"") @Name "\"" ">"
@Name ~(chop "</a> (") @Size )
(client "software-lab.de" 80 "down.html"
(from "Release Archive")
(from "<li>")
(till ",") ) )
(prinl @Name)
(prinl @Date " -- " @Size) ) )
(bye)
We recommend that you have a terminal window open, and try the examples by
yourself. You may either type them in, directly to the PicoLisp interpreter, or
edit a separate source file (e.g. "@doc/fun.l"
) in a second
terminal window and load it into PicoLisp with
: (load "@doc/fun.l")
each time you have modified and saved it.
Once a function is loaded from a source file, you can call 'vim' directly on that function with
: (vi 'fact)
The function 'vi' opens the appropriate source file, and jumps to the right line where 'fact' is defined. When you modify it, you can simply call 'ld' to (re)load that source file
: (ld)
The PicoLisp object model is very simple, yet flexible and powerful. Objects as well as classes are both implemented as symbols. In fact, there is no formal difference between objects and classes; classes are more a conceptual design consideration in the head of the programmer than a physical reality.
Having said this, we declare that normally:
So the main difference between classes and objects is that the former ones
usually are internal symbols. By convention, their names start with a
'+
'. Sometimes it makes sense, however, to create named objects (as
global singletons, for example), or even anonymous classes.
Both classes and objects have a list in their value, consisting of method definitions (often empty for objects) and (super)class(es). And both classes and objects have local data in their property lists (often empty for classes). This implies, that any given object (as an instance of a class) may have private (object-local) methods defined.
It is rather difficult to contrive a simple OOP example. We constructed a
hierarchy of geometric shapes, with a base class +Shape
and two
subclasses +Rectangle
and +Circle
.
The source code is included as "@doc/shape.l
" in the PicoLisp distribution, so you
don't have to type it in. Just load
the file, or start it from the shell as:
$ pil @doc/shape.l +
Let's look at it piece by piece. Here's the base class:
(class +Shape)
# x y
(dm T (X Y)
(=: x X)
(=: y Y) )
(dm move> (DX DY)
(inc (:: x) DX)
(inc (:: y) DY) )
The first line '(class +Shape)
' defines the symbol
+Shape
as a class without superclasses. The following method
definitions will go to that class.
The comment '# x y
' in the second line is just a convention, to
indicate what instance variables (properties) that class uses. As PicoLisp is a
dynamic language, a class can be extended at runtime with any number of
properties, and there is nothing like a fixed object size or structure. This
comment is a hint of what the programmer thinks to be essential and typical for
that class. In the case of +Shape
, x
and
y
are the coordinates of the shape's origin.
Then we have two method definitions, using the keyword dm
for "define method". The first method is
special, in that its name is T
. Each time a new object is created,
and a method with that name is found in its class hierarchy, that method will be
executed. Though this looks like a "constructor" in other programming languages,
it should probably better be called "initializer". The T
method of
+Shape
takes two arguments X
and Y
, and
stores them in the object's property list.
The second method move>
changes the object's origin by adding
the offset values DX
and DY
to the object's origin.
Now to the first derived class:
(class +Rectangle +Shape)
# dx dy
(dm T (X Y DX DY)
(super X Y)
(=: dx DX)
(=: dy DY) )
(dm area> ()
(* (: dx) (: dy)) )
(dm perimeter> ()
(* 2 (+ (: dx) (: dy))) )
(dm draw> ()
(drawRect (: x) (: y) (: dx) (: dy)) )
+Rectangle
is defined as a subclass of +Shape
.
The comment '# dx dy
' indicates that +Rectangle
has a
width and a height in addition to the origin coordinates inherited from
+Shape
.
The T
method passes the origin coordinates X
and
Y
to the T
method of the superclass
(+Shape
), then stores the width and height parameters into
dx
and dy
.
Next we define the methods area>
and
perimeter>
which do some obvious calculations, and a method
draw>
which is supposed to draw the shape on the screen by
calling some hypothetical function drawRect
.
Finally, we define a +Circle
class in an analog way, postulating
the hypothetical function drawCircle
:
(class +Circle +Shape)
# r
(dm T (X Y R)
(super X Y)
(=: r R) )
(dm area> ()
(*/ (: r) (: r) 31415927 10000000) )
(dm perimeter> ()
(*/ 2 (: r) 31415927 10000000) )
(dm draw> ()
(drawCircle (: x) (: y) (: r)) )
Now we can experiment with geometrical shapes. We create a rectangle at point
(0,0) with a width of 30 and a height of 20, and keep it in the variable
R
:
: (setq R (new '(+Rectangle) 0 0 30 20)) # New rectangle
-> $134432824 # returned anonymous symbol
: (show R)
$134432824 (+Rectangle) # Show the rectangle
dy 20
dx 30
y 0
x 0
We see that the symbol $134432824
has a list of classes
'(+Rectangle)
' in its value, and the coordinates, width and height
in its property list.
Sending messages to that object
: (area> R) # Calculate area
-> 600
: (perimeter> R) # and perimeter
-> 100
will return the values for area and perimeter, respectively.
Then we move the object's origin:
: (move> R 10 5) # Move 10 right and 5 down
-> 5
: (show R)
$134432824 (+Rectangle)
y 5 # Origin changed (0,0) -> (10,5)
x 10
dy 20
dx 30
Though a method move>
wasn't defined for the
+Rectangle
class, it is inherited from the +Shape
superclass.
Similarly, we create and use a circle object:
: (setq C (new '(+Circle) 10 10 30)) # New circle
-> $134432607 # returned anonymous symbol
: (show C)
$134432607 (+Circle) # Show the circle
r 30
y 10
x 10
-> $134432607
: (area> C) # Calculate area
-> 2827
: (perimeter> C) # and perimeter
-> 188
: (move> C 10 5) # Move 10 right and 5 down
-> 15
: (show C)
$134432607 (+Circle) # Origin changed (10,10) -> (20,15)
y 15
x 20
r 30
It is also easy to send messages to objects in a list:
: (mapcar 'area> (list R C)) # Get list of areas
-> (600 2827)
: (mapc
'((Shape) (move> Shape 10 10)) # Move all 10 right and down
(list R C) )
-> 25
: (show R)
$134431493 (+Rectangle)
y 15
x 20
dy 20
dx 30
-> $134431493
: (show C)
$134431523 (+Circle)
y 25
x 30
r 30
Assume that we want to extend our shape system. From time to time, we need
shapes that behave exactly like the ones above, but are tied to a fixed
position. That is, they do not change their position even if they receive a
move>
message.
One solution would be to modify the move>
method in the
+Shape
class to a no-operation. But this would require to duplicate
the whole shape hierarchy (e.g. by defining +FixedShape
,
+FixedRectangle
and +FixedCircle
classes).
The PicoLisp Way is the use of Prefix Classes through multiple inheritance. It uses the fact that searching for method definitions is a depth-first, left-to-right search of the class tree. We define a prefix class:
: (class +Fixed)
(dm move> (DX DY)) # A do-nothing method
We can now create a fixed rectangle, and try to move it:
: (setq R (new '(+Fixed +Rectangle) 0 0 30 20)) # '+Fixed' prefix class
-> $134432881
: (move> R 10 5) # Send 'move>' message
-> NIL
: (show R)
$134432881 (+Fixed +Rectangle)
dy 20
dx 30
y 0 # Did not move!
x 0
We see, prefix classes can surgically change the inheritance tree for selected objects or classes.
Alternatively, if fixed rectangles are needed often, it might make sense to
define a new class +FixRect
:
: (class +FixRect +Fixed +Rectangle)
-> +FixRect
and then use it directly:
: (setq R (new '(+FixRect) 0 0 30 20))
-> $13455710
PicoLisp has persistent objects built-in as a first class data type. With "first class" we mean not just the ability of being passed around, or returned from functions (that's a matter of course), but that they are a primary data type with their own interpreter tag bits. They are, in fact, a special type of symbolic atoms (called "External Symbols"), that happen to be read from pool file(s) when accessed, and written back automatically when modified.
In all other aspects they are normal symbols. They have a value, a property list and a name.
The name cannot be directly controlled by the programmer, as it is assigned
when the symbol is created. It is an encoded index of the symbol's location in
its database file. In its visual representation (output by the print
functions and input by the read
functions) it is surrounded by braces.
To make use of external symbols, you need to open a database first:
: (pool "test.db")
If a file with that name did not exist, it got created now. Also created at
the same moment was {1}
, the very first symbol in the file. This
symbol is of great importance, and is handled especially by PicoLisp. Therefore
a global constant *DB
exists, which
points to that symbol {1}
, which should be used exclusively to
access the symbol {1}
, and which should never be modified by the
programmer.
: *DB # The value of '*DB'
-> {1} # is '{1}'
: (show *DB)
{1} NIL # Value of '{1}' is NIL, property list empty
Now let's put something into the value and property list of {1}
.
: (set *DB "Hello world") # Set value of '{1}' to a transient symbol (string)
-> "Hello world"
: (put *DB 'a 1) # Property 'a' to 1
-> 1
: (put *DB 'b 2) # Property 'b' to 2
-> 2
: (show *DB) # Now show the symbol '{1}'
{1} "Hello world"
b 2
a 1
Note that instead of '(set *DB "Hello world")
', we might
also have written '(setq {1} "Hello world")
', and instead of
'(put *DB 'a 1)
' we might have written '(put '{1} 'a
1)
'. This would have the same effect, but as a rule external symbols
should never be be accessed literally in application programs, because the
garbage collector might not be able to free these symbols and all symbols
connected to them (and that might well be the whole database). It is all right,
however, to access external symbols literally during interactive debugging.
Now we can create our first own external symbol. This can be done with
new
when a T
argument is
supplied:
: (new T)
-> {2} # Got a new symbol
We store it in the database root {1}
:
: (put *DB 'newSym '{2}) # Literal '{2}' (ok during debugging)
-> {2}
: (show *DB)
{1} "Hello world"
newSym {2} # '{2}' is now stored in '{1}'
b 2
a 1
Put some property value into '{2}'
: (put *DB 'newSym 'x 777) # Put 777 as 'x'-property of '{2}'
-> 777
: (show *DB 'newSym) # Show '{2}' (indirectly)
{2} NIL
x 777
-> {2}
: (show '{2}) # Show '{2}' (directly)
{2} NIL
x 777
All modifications to - and creations of - external symbols done so far are
not written to the database yet. We could call rollback
(or simply exit PicoLisp) to undo
all the changes. But as we want to keep them:
: (commit) # Commit all changes
-> T
: (bye) # Exit picolisp
$ # back to the shell
So, the next time when ..
$ pil + # .. we start PicoLisp
: (pool "test.db") # and open the database file,
-> T
: (show *DB) # our two symbols are there again
{1} "Hello world"
newSym {2}
b 2
a 1
-> {1}
: (show *DB 'newSym)
{2} NIL
x 777
-> {2}
To a database, there is more than just persistence. PicoLisp includes an entity/relation class framework (see also Database) which allows a close mapping of the application data structure to the database.
We provided a simple yet complete database and GUI demo application in
@doc/family.tgz
and @doc/family64.tgz
. Please unpack the first one if
you use a 32-bit system, and the second one on a 64-bit system. Both contain the
sources in @doc/family.l
, and an initial
database in the "family/" subdirectory.
To use it, please unpack it first in your current working directory, then start it up in the following way:
$ pil family.l -main +
:
This loads the source file, initializes the database by calling the
main
function, and prompts for user input.
The data model is small and simple. We define a class +Person
and two subclasses +Man
and +Woman
.
(class +Person +Entity)
+Person
is a subclass of the +Entity
system class. Usually all objects in
a database are of a direct or indirect subclass of +Entity
. We can then define the relations to
other data with the rel
function.
(rel nm (+Need +Sn +Idx +String)) # Name
This defines the name property (nm
) of a person. The first
argument to rel
is always a list of relation classes (subclasses of
+relation
), optionally followed
by further arguments, causing relation daemon objects be created and stored in
the class definition. These daemon objects control the entity's behavior later
at runtime.
Relation daemons are a kind of metadata, controlling the interactions between entities, and maintaining database integrity. Like other classes, relation classes can be extended and refined, and in combination with proper prefix classes a fine-grained description of the application's structure can be produced.
Besides primitive relation classes, like +Number
,
+String
or +Date
, there are
+Link
(unidirectional link),
+Joint
(bidirectional link) or +Hook
(object-local
index trees)
+Bag
)
+List
prefix class
+Blob
class for "binary large objects"
+Key
(unique
index), +Ref
(non-unique index) or +Idx
(full text
index)
+Sn
(modified soundex algorithm [knuth73]
for tolerant searches)
+Need
prefix class, for existence checks
+Dep
prefix class controlling dependencies between other
relations
In the case of the person's name (nm
) above, the relation object
is of type (+Need +Sn +Idx +String)
. Thus, the name of each person
in this demo database is a mandatory attribute (+Need
), searchable
with the soundex algorithm (+Sn
) and a full index
(+Idx
) of type +String
.
(rel pa (+Joint) kids (+Man)) # Father
(rel ma (+Joint) kids (+Woman)) # Mother
(rel mate (+Joint) mate (+Person)) # Partner
The attributes for father (pa
), Mother
(ma
) and partner (mate
) are all defined as
+Joint
s. A +Joint
is probably the most powerful
relation mechanism in PicoLisp; it establishes a bidirectional link between two
objects.
The above declarations say that the father (pa
) attribute
points to an object of type +Man
, and is joined with that object's
kids
attribute (which is a list of joints back to all his
children).
The consistency of +Joint
s is maintained automatically by the
relation daemons. These become active whenever a value is stored to a person's
pa
, ma
, mate
or kids
property.
For example, interesting things happen when a person's mate
is
changed to a new value. Then the mate
property of the old mate's
object is cleared (she has no mate after that). Now when the person pointed to
by the new value already has a mate, then that mate's mate
property
gets cleared, and the happy new two mates now get their joints both set
correctly.
The programmer doesn't have to care about all that. He just declares these
relations as +Joint
s.
The last four attributes of person objects are just static data:
(rel job (+Ref +String)) # Occupation
(rel dat (+Ref +Date)) # Date of birth
(rel fin (+Ref +Date)) # Date of death
(rel txt (+String)) # Info
They are all searchable via a non-unique index (+Ref
). Date
values in PicoLisp are just numbers, representing the day number (starting first
of March of the year zero).
A method url>
is defined:
(dm url> ()
(list "!person" '*ID This) )
It is needed later in the GUI, to cause a click on a link to switch to that object.
The classes +Man
and +Woman
are subclasses of
+Person
:
(class +Man +Person)
(rel kids (+List +Joint) pa (+Person)) # Children
(class +Woman +Person)
(rel kids (+List +Joint) ma (+Person)) # Children
They inherit everything from +Person
, except for the
kids
attribute. This attribute joins with the pa
or
ma
attribute of the child, depending on the parent's gender.
That's the whole data model for our demo database application.
It is followed by a call to dbs
("database sizes"). This call is optional. If it is not present, the whole
database will reside in a single file, with a block size of 256 bytes. If it is
given, it should specify a list of items, each having a number in its CAR, and a
list in its CDR. The CARs taken together will be passed later to pool, causing an individual database file with that
size to be created. The CDRs tell what entity classes (if an item is a symbol)
or index trees (if an item is a list with a class in its CAR and a list of
relations in its CDR) should be placed into that file.
A handful of access functions is provided, that know about database relationships and thus allows higher-level access modes to the external symbols in a database.
For one thing, the B-Trees created and maintained by the index daemons can be used directly. Though this is rarely done in a typical application, they form the base mechanisms of other access modes and should be understood first.
The function tree
returns the tree
structure for a given relation. To iterate over the whole tree, the functions
iter
and scan
can be used:
(iter (tree 'dat '+Person) '((P) (println (datStr (get P 'dat)) (get P 'nm))))
"1770-08-03" "Friedrich Wilhelm III"
"1776-03-10" "Luise Augusta of Mecklenburg-Strelitz"
"1797-03-22" "Wilhelm I"
...
They take a function as the first argument. It will be applied to all objects found in the tree (to show only a part of the tree, an optional begin- and end-value can be supplied), producing a simple kind of report.
More useful is collect
; it
returns a list of all objects that fall into a range of index values:
: (collect 'dat '+Person (date 1982 1 1) (date 1988 12 31))
-> ({2-M} {2-L} {2-E})
This returns all persons born between 1982 and 1988. Let's look at them with
show
:
: (more (collect 'dat '+Person (date 1982 1 1) (date 1988 12 31)) show)
{2-M} (+Man)
nm "William"
dat 724023
ma {2-K}
pa {2-J}
job "Heir to the throne"
{2-L} (+Man)
nm "Henry"
dat 724840
ma {2-K}
pa {2-J}
job "Prince"
{2-E} (+Woman)
nm "Beatrice"
dat 726263
ma {2-D}
job "Princess"
pa {2-B}
If you are only interested in a certain attribute, e.g. the name, you can return it directly:
: (collect 'dat '+Person (date 1982 1 1) (date 1988 12 31) 'nm)
-> ("William" "Henry" "Beatrice")
To find a single object in the database, the function db
is used:
: (db 'nm '+Person "Edward")
-> {2-;}
If the key is not unique, additional arguments may be supplied:
: (db 'nm '+Person "Edward" 'job "Prince" 'dat (date 1964 3 10))
-> {2-;}
The programmer must know which combination of keys will suffice to specify the object uniquely. The tree search is performed using the first value ("Edward"), while all other attributes are used for filtering. Later, in the Pilog section, we will show how more general (and possibly more efficient) searches can be performed.
The only types of GUI supported by the PicoLisp application server framework is either dynamically generated (but static by nature) HTML, or an interactive XHTML/CSS framework with the optional use of JavaScript.
Before we explain the GUI of our demo database application, we present a
minimal example for a plain HTML-GUI in @doc/hello.l
. Start the application server as:
$ pil @lib/http.l --server 8080 @doc/hello.l -wait
Now point your browser to the address 'http://localhost:8080
'. You should see a
very simple HTML page. You can come back here with the browser's BACK button.
You can call the page repeatedly, or concurrently with many clients if you
like. To terminate the server, you have to send it a TERM signal (e.g.
'killall pil
'), or type the Ctrl-C
key in the console
window.
In our demo database application, a single function person
is
responsible for the whole GUI. Again, please look at @doc/family.l
.
To start the database and the application server, call:
$ pil family.l -main -go +
As before, the database is opened with main
. The function
go
is also defined in @doc/family.l
:
(de go ()
(server 8080 "!person") )
It starts the HTTP server listening on TCP port 8080 (we did a similar thing
in our minimal GUI example above directly on the command line). Each connect to
that port will cause the function person
to be invoked.
Again, point your browser to the address 'http://localhost:8080
'.
You should see a new browser window with an input form created by the
function person
. We provided an initial database in "family/[1-4]".
You can navigate through it by clicking on the pencil icons besides the input
fields.
The chart with the children data can be scrolled using the down
(v
) and up (^
) buttons.
A click on the button "Select" below opens a search dialog. You can scroll through the chart as before. Again, a click on a pencil will jump to that person. You can abort the dialog with a click on the "Cancel"-button.
The search fields in the upper part of the dialog allow a conjunctive search. If you enter "Edward" in the "Name" field and click "Search", you'll see all persons having the string "Edward" in their name. If you also enter "Duke" in the "Occupation" field, the result list will reduce to only two entries.
To create a new person, press the "New Man" or "New Woman" button. A new empty form will be displayed. Please type a name into the first field, and perhaps also an occupation and birth date. Any change of contents should be followed by a press on the "Done" button, though any other button (also Scroll or Select-buttons) will also do.
To assign a father attribute, you can either type a name directly into
the field (if that person already exists in the database and you know the exact
spelling), or use the "Set"-button (->
) to the left of that
field to open the search dialog. If you type in the name directly, your input
must exactly match upper and lower case.
Alternatively, you may create a new person and assign a child in the "Children" chart.
On the console where you started PicoLisp, there should a prompt have
appeared just when the browser connected. You can debug the application
interactively while it is running. For example, the global variable
*Top
always contains the top level GUI object:
: (show *Top)
To take a look at the first field on the form:
: (show *Top 'gui 1)
A production application would be started in a slightly different way:
$ pil family.l -main -go -wait
In that case, no debug prompt will appear. In both cases, however, two
pil
processes will be running now. One is the initial server
process which will continue to run until it is killed. The other is a child
process holding the state of the GUI in the browser. It will terminate some time
after the browser is closed, or when (bye)
or a Ctrl-D
is entered at the
PicoLisp prompt.
Now back to the explanation of the GUI function person
:
(de person ()
(app)
(action
(html 0 (get (default *ID (val *DB)) 'nm) "@lib.css" NIL
(form NIL
(<h2> (<id> (: nm)))
For an in-depth explanation of that startup code, please refer to the guide to PicoLisp Application Development.
All components like fields and buttons are controlled by form
.
The function gui
creates a single GUI component and takes the type
(a list of classes) and a variable number of arguments depending on the needs of
these classes.
(gui '(+E/R +TextField) '(nm : home obj) 40 "Name")
This creates a +TextField
with the label "Name" and a length of
40 characters. The +E/R
(: Entity/Relation) prefix class connects
that field to a database object, the nm
attribute of a person in
this case, so that the person's name is displayed in that text field, and any
changes entered into that field are propagated to the database automatically.
(gui '(+ClassField) '(: home obj) '(("Male" +Man) ("Female" +Woman)))
A +ClassField
displays and changes the class of an object, in
this case the person's sex from +Man
to +Woman
and
vice versa.
As you see, there is no place where explicit accesses to the database have to
be programmed, no select
or update
. This is all
encapsulated in the GUI components, mainly in the +E/R
prefix
class. The above function person
is fully functional as we present
it and allows creation, modification and deletion of person objects in the
database.
The two buttons on the bottom right generate simple reports:
The first one shows all contemporaries of the person that is currently displayed, i.e. all persons who did not die before, or were not born after that person. This is a typical PicoLisp report, in that in addition to the report's HTML page, a temporary file may be generated, suitable for download (and import into a spread sheet), and from which a PDF can be produced for print-out.
In PicoLisp, there is not a real difference between a plain HTML-GUI and a
report. Again, the function html
is used to generate the page.
The second report is much simpler. It produces a recursive structure of the family.
In both reports, links to the person objects are created which allow easy navigation through the database.
This sections explains some cases of using Pilog in typical application programming, in combination with persistent objects and databases. Please refer to the Pilog section of the PicoLisp Reference for the basic usage of Pilog.
Again, we use our demo application @doc/family.l
that was introduced in the Database Programming section.
Normally, Pilog is used either interactively to query the database during
debugging, or in applications to generate export data and reports. In the
following examples we use the interactive query front-end functions ?
and select
. An application will use goal
and prove
directly, or use convenience functions
like pilog
or solve
.
All Pilog access to external symbols is done via the two predicates db/3
and select/3
.
db/3
corresponds to the Lisp-level
functions db
and collect
, as it derives its data from a
single relation. It can be used for simple database queries.
select/3
provides for
self-optimizing parallel access to an arbitrary number of relations. There is
also a Lisp front-end function select
, for convenient calls to the Pilog
select
predicate.
A predicate show/1
is pre-defined
for debugging purposes (a simple glue to the Lisp-level function
show
, see Browsing). Searching with db/3
for all persons having the string "Edward"
in their name:
: (? (db nm +Person "Edward" @P) (show @P))
{2-;} (+Man)
nm "Edward"
ma {2-:}
pa {2-A}
dat 717346
job "Prince"
@P={2-;}
{2-1B} (+Man)
nm "Albert Edward"
kids ({2-1C} {2-1D} {2-1E} {2-1F} {2-1G} {2-1H} {2-1I} {2-g} {2-a})
job "Prince"
mate {2-f}
fin 680370
dat 664554
@P={2-1B}
... # more results
To search for all persons with "Edward" in their name who are married to somebody with occupation "Queen":
: (? (db nm +Person "Edward" @P) (val "Queen" @P mate job) (show @P))
{2-1B} (+Man)
mate {2-f}
nm "Albert Edward"
kids ({2-1C} {2-1D} {2-1E} {2-1F} {2-1G} {2-1H} {2-1I} {2-g} {2-a})
job "Prince"
fin 680370
dat 664554
@P={2-1B}
-> NIL # only one result
If you are interested in the names of "Albert Edward"'s children:
: (? (db nm +Person "Albert Edward" @P) (lst @K @P kids) (val @Kid @K nm))
@P={2-1B} @K={2-1C} @Kid="Beatrice Mary Victoria"
@P={2-1B} @K={2-1D} @Kid="Leopold George Duncan"
@P={2-1B} @K={2-1E} @Kid="Arthur William Patrick"
@P={2-1B} @K={2-1F} @Kid="Louise Caroline Alberta"
@P={2-1B} @K={2-1G} @Kid="Helena Augusta Victoria"
@P={2-1B} @K={2-1H} @Kid="Alfred Ernest Albert"
@P={2-1B} @K={2-1I} @Kid="Alice Maud Mary"
@P={2-1B} @K={2-g} @Kid="Victoria Adelaide Mary"
@P={2-1B} @K={2-a} @Kid="Edward VII"
-> NIL
db/3
can do a direct index access
only for a single attribute (nm
of +Person
above). To
search for several criteria at the same time, select/3
has to be used:
: (?
(select (@P)
((nm +Person "Edward") (nm +Person "Augusta" pa)) # Generator clauses
(tolr "Edward" @P nm) # Filter clauses
(tolr "Augusta" @P kids nm) )
(show @P) )
{2-1B} (+Man)
kids ({2-1C} {2-1D} {2-1E} {2-1F} {2-1G} {2-1H} {2-1I} {2-g} {2-a})
mate {2-f}
nm "Albert Edward"
job "Prince"
fin 680370
dat 664554
@P={2-1B}
-> NIL
select/3
takes a list of
generator clauses which are used to retrieve objects from the database, and a
number of normal Pilog filter clauses. In the example above the generators are
(nm +Person "Edward")
to generate persons with "Edward" in
their names, and
(nm +Person "Augusta" pa)
to find persons with "Augusta"
in their names and generate persons using the pa
("father")
attribute.
All persons generated are possible candidates for our selection. The
nm
index tree of +Person
is traversed twice in
parallel, optimizing the search in such a way that successful hits get higher
priority in the search, depending on the filter clauses. The process will stop
as soon as any one of the generators is exhausted. Note that this is different
from the standard Prolog search algorithm.
The filter clauses in this example both use the pre-defined predicate
tolr/3
for tolerant string
matches (according either to the soundex algorithm (see the section Database Programming) or to substring matches), and filter
objects that
(tolr "Edward" @P nm)
, and
(tolr "Augusta" @P
kids nm)
A more typical and extensive example for the usage of select
can
be found in the qPerson
function in @doc/family.l
. It is used in the search dialog of the
demo application, and searches for a person with the name, the parents' and
partner's names, the occupation and a time range for the birth date. The
relevant index trees in the database are searched (actually only those trees
where the user entered a search key in the corresponding dialog field), and a
logical AND of the search attributes is applied to the result.
For example, press the "Select" button, enter "Elizabeth" into the "Mother" search field and "Phil" in the "Partner" search field, meaning to look for all persons whose mother's name is like "Elizabeth" and whose partner's name is like "Phil". As a result, two persons ("Elizabeth II" and "Anne") will show up.
In principle, db/3
can be seen as a
special case of select/3
. The
following two queries are equivalent:
: (? (db nm +Person "Edward" @P))
@P={2-;}
@P={2-1B}
@P={2-R}
@P={2-1K}
@P={2-a}
@P={2-T}
-> NIL
: (? (select (@P) ((nm +Person "Edward"))))
@P={2-;}
@P={2-1B}
@P={2-R}
@P={2-1K}
@P={2-a}
@P={2-T}
-> NIL
For convenience, a select
Lisp
glue function is provided as a front-end to the select
predicate.
Note that this function does not evaluate its arguments (it is intended for
interactive use), and that it supports only a subset of the predicate's
functionality. The syntax resembles SELECT in the SQL language, for example:
# SELECT * FROM Person
: (select +Person) # Step through the whole database
{2-o} (+Man)
nm "Adalbert Ferdinand Berengar Viktor of Prussia"
dat 688253
ma {2-j}
pa {2-h}
fin 711698
{2-1B} (+Man)
nm "Albert Edward"
dat 664554
job "Prince"
mate {2-f}
kids ({2-1C} {2-1D} {2-1E} {2-1F} {2-1G} {2-1H} {2-1I} {2-g} {2-a})
fin 680370
...
# SELECT * FROM Person WHERE nm LIKE "%Edward%"
: (select +Person nm "Edward") # Show all Edwards
{2-;} (+Man)
nm "Edward"
dat 717346
job "Prince"
ma {2-:}
pa {2-A}
{2-1B} (+Man)
nm "Albert Edward"
dat 664554
job "Prince"
kids ({2-1C} {2-1D} {2-1E} {2-1F} {2-1G} {2-1H} {2-1I} {2-g} {2-a})
mate {2-f}
fin 680370
...
# SELECT nm, dat FROM Person WHERE nm LIKE "%Edward%"
: (select nm dat +Person nm "Edward")
"Edward" "1964-03-10" {2-;}
"Albert Edward" "1819-08-26" {2-1B}
"George Edward" NIL {2-R}
"Edward Augustus Hanover" NIL {2-1K}
...
# SELECT dat, fin, p1.nm, p2.nm
# FROM Person p1, Person p2
# WHERE p1.nm LIKE "%Edward%"
# AND p1.job LIKE "King%"
# AND p1.mate = p2.mate -- Actually, in a SQL model we'd need
# -- another table here for the join
: (select dat fin nm (mate nm) +Person nm "Edward" job "King")
"1894-06-23" "1972-05-28" "Edward VIII" "Wallace Simpson" {2-T}
"1841-11-09" NIL "Edward VII" "Alexandra of Denmark" {2-a}
-> NIL
In addition (just to stay with the SQL terminology ;-), there is also an
update
function. It is a front-end
to the set!>
and put!>
transaction methods, and
should be used when single objects in the database have to be modified by hand.
In principle, it would also be possible to use the edit
function to modify a database object. This
is not recommended, however, because edit
does not know about
relations to other objects (like Links, Joints and index trees) and may easily
cause database corruption.
In the most general case, the value of a property in a database object is
changed with the put!>
method. Let's look at "Edward" from the
previous examples:
: (show '{2-;})
{2R} (+Man)
job "Prince"
nm "Edward"
dat 717346
ma {2-:}
pa {20A}
-> {2-;}
We might change the name to "Johnny" with put!>
:
: (put!> '{2-;} 'nm "Johnny")
-> "Johnny"
However, an easier and less error-prone prone way - especially when more than
one property has to be changed - is using update
. It presents the value (the list of
classes) and then each property on its own line, allowing the user to change it
with the command line editor.
Just hitting ENTER will leave that property unchanged. To modify it, you'll typically hit ESC to get into command mode, and move the cursor to the point of change.
For properties with nested list structures (+List +Bag
),
update
will recurse into the data structure.
: (update '{2-;})
{2-;} (+Man) # ENTER
nm "Johnny" # Modified the name to "Johnny"
ma {2-:} # ENTER
pa {2-A} # ENTER
dat 1960-03-10 # Modified the year from "1964" to "1960"
job "Prince" # ENTER
-> {2-;}
All changes are committed immediately, observing the rules of database synchronization so that any another user looking at the same object will have his GUI updated correctly.
To abort update
, hit Ctrl-X
.
If only a single property has to be changed, update
can be
called directly for that property:
: (update '{2-;} 'nm)
{2-;} nm "Edward"
...
[knuth73] Donald E. Knuth: ``The Art of Computer Programming'', Vol.3, Addison-Wesley, 1973, p. 392 picolisp-3.1.5.2.orig/doc/utf8 0000644 0000000 0000000 00000001371 12265263724 014530 0 ustar root root UTF-8 Format # Encoding for zero is different from Java # Special character 0xFF (char T) 0000 .. 007F 0xxxxxxx 6 0 0080 .. 07FF 110xxxxx 10xxxxxx A 6 5 0 0800 .. FFFF 1110xxxx 10xxxxxx 10xxxxxx F C B 6 5 0 Umlaute äöüÄÖÜß |Ä| # C3 84 <-> C4 |Ö| # C3 96 <-> D6 |Ü| # C3 9C <-> DC |ä| # C3 A4 <-> E4 |ö| # C3 B6 <-> F6 |ü| # C3 BC <-> FC |ß| # C3 9F <-> DF Paragraph # C2 A7 <-> A7 EUR (8364 "20AC") # E2 82 AC <-> A4 tr -d '\303' |tr '\204\226\234\244\266\274\237' '' (out "Nagoya" (prinl (char (hex "540D")) (char (hex "53E4")) (char (hex "5C4B"))) ) picolisp-3.1.5.2.orig/doc/vim-tsm 0000644 0000000 0000000 00000001447 12265263724 015242 0 ustar root root 26apr10abu (c) Software Lab. Alexander Burger Transient Symbol Markup for 'vim' ================================= 1. Compile 'vim' with Vince Negri's "Conceal" patch: http://vim.wikia.com/wiki/Patch_to_conceal_parts_of_lines patch -p0 < conceal-ownsyntax.diff make distclean ./configure --with-features=huge make VIMRUNTIMEDIR=~/local/vim72/runtime MAKE="make -e" cd ~/bin ln -s ~/local/vim72/src/vim ln vim vi ln vim view 2. Then put into your ".vimrc" or vim syntax file: if has("conceal") set conceallevel=2 syn region picoLispTransient concealends matchgroup=picoLispString start=/"/ skip=/\\\\\|\\"/ end=/"/ hi picoLispTransient gui=underline term=underline cterm=underline hi picoLispString ctermfg=red guifg=red endif picolisp-3.1.5.2.orig/doc/app.html 0000644 0000000 0000000 00000275340 12265263724 015376 0 ustar root root
(c) Software Lab. Alexander Burger
This document presents an introduction to writing browser-based applications in PicoLisp.
It concentrates on the XHTML/CSS GUI-Framework (as opposed to the previous Java-AWT, Java-Swing and Plain-HTML frameworks), which is easier to use, more flexible in layout design, and does not depend on plug-ins, JavaScript, cookies or CSS.
A plain HTTP/HTML GUI has various advantages: It runs on any browser, and can be fully driven by scripts ("@lib/scrape.l").
To be precise: CSS can be used to enhance the layout. And browsers with JavaScript will respond faster and smoother. But this framework works just fine in browsers which do not know anything about CSS or JavaScript. All examples were also tested using the w3m text browser.
For basic informations about the PicoLisp system please look at the PicoLisp Reference and the PicoLisp Tutorial. Knowledge of HTML, and a bit of CSS and HTTP is assumed.
The examples assume that PicoLisp was started from a global installation (see Installation).
You can use PicoLisp to generate static HTML pages. This does not make much sense in itself, because you could directly write HTML code as well, but it forms the base for interactive applications, and allows us to introduce the application server and other fundamental concepts.
To begin with a minimal application, please enter the following two lines into a generic source file named "project.l" in the PicoLisp installation directory.
########################################################################
(html 0 "Hello" "@lib.css" NIL
"Hello World!" )
########################################################################
(We will modify and use this file in all following examples and experiments. Whenever you find such a program snippet between hash ('#') lines, just copy and paste it into your "project.l" file, and press the "reload" button of your browser to view the effects)
Open a second terminal window, and start a PicoLisp application server
$ pil @lib/http.l @lib/xhtml.l @lib/form.l --server 8080 project.l +
No prompt appears. The server just sits, and waits for connections. You can
stop it later by hitting Ctrl-C
in that terminal, or by executing
'killall pil
' in some other window.
(In the following, we assume that this HTTP server is up and running)
Now open the URL 'http://localhost:8080
' with your
browser. You should see an empty page with a single line of text.
The above line loads the debugger (via the '+' switch), the HTTP server code ("@lib/http.l"), the XHTML functions ("@lib/xhtml.l") and the input form framework ("@lib/form.l", it will be needed later for interactive forms).
Then the server
function is called with a port number and a
default URL. It will listen on that port for incoming HTTP requests in an
endless loop. Whenever a GET request arrives on port 8080, the file "project.l"
will be (load)
ed, causing the
evaluation (= execution) of all its Lisp expressions.
During that execution, all data written to the current output channel is sent directly to to the browser. The code in "project.l" is responsible to produce HTML (or anything else the browser can understand).
The PicoLisp application server uses a slightly specialized syntax when communicating URLs to and from a client. The "path" part of an URL - which remains when
(load)
ed. This
is the most common case, and we use it in our example "project.l".
*Mimes
, the file is sent to the client with mime-type and
max-age values taken from that table.
An application is free to extend or modify the *Mimes
table with
the mime
function. For example
(mime "doc" "application/msword" 60)
defines a new mime type with a max-age of one minute.
Argument values in URLs, following the path and the question mark, are encoded in such a way that Lisp data types are preserved:
In that way, high-level data types can be directly passed to functions encoded in the URL, or assigned to global variables before a file is loaded.
It is, of course, a huge security hole that - directly from the URL - any
Lisp source file can be loaded, and any Lisp function can be called. For that
reason, applications must take care to declare exactly which files and functions
are to be allowed in URLs. The server checks a global variable *Allow
, and - when its value is
non-NIL
- denies access to anything that does not match its
contents.
Normally, *Allow
is not manipulated directly, but set with the
allowed
and allow
functions
(allowed ("app/")
"!start" "!stop" "@lib.css" "!psh" )
This is usually called at the beginning of an application, and allows access to the directory "app/", to the functions 'start', 'stop' and 'psh', and to the file "@lib.css".
Later in the program, *Allow
may be dynamically extended with
allow
(allow "!foo")
(allow "newdir/" T)
This adds the function 'foo', and the directory "newdir/", to the set of allowed items.
For a variety of security checks (most notably for using the psh
function, as in some later examples) it is necessary to create a file named
".pw" in the PicoLisp installation directory. This file should contain a single
line of arbitrary data, to be used as a password for identifying local
resources.
The recommeded way to create this file is to call the pw
function, defined in "@lib/http.l"
$ pil @lib/http.l -'pw 12' -bye
Please execute this command.
html
FunctionNow back to our "Hello World" example. In principle, you could write "project.l" as a sequence of print statements
########################################################################
(prinl "HTTP/1.0 200 OK^M")
(prinl "Content-Type: text/html; charset=utf-8")
(prinl "^M")
(prinl "<html>")
(prinl "Hello World!")
(prinl "</html>")
########################################################################
but using the html
function is much more convenient.
Moreover, html
is nothing more than a printing function.
You can see this easily if you connect a PicoLisp Shell (psh
) to
the server process (you must have generated a ".pw" file for
this), and enter the html
statement
$ /usr/lib/picolisp/bin/psh 8080
: (html 0 "Hello" "@lib.css" NIL "Hello World!")
HTTP/1.0 200 OK
Server: PicoLisp
Date: Fri, 29 Dec 2006 07:28:58 GMT
Cache-Control: max-age=0
Cache-Control: no-cache
Content-Type: text/html; charset=utf-8
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Hello</title>
<base href="http://localhost:8080/"/>
<link rel="stylesheet" type="text/css" href="http://localhost:8080/@lib.css"/>
</head>
<body>Hello World!</body>
</html>
-> </html>
: # (type Ctrl-D here to terminate PicoLisp)
These are the arguments to html
:
0
: A max-age value for cache-control (in seconds, zero means
"no-cache"). You might pass a higher value for pages that change seldom, or
NIL
for no cache-control at all.
"Hello"
: The page title.
"@lib.css"
: A CSS-File name. Pass NIL
if you do
not want to use any CSS-File, or a list of file names if you want to give more
than one CSS-File.
NIL
: A CSS style attribute specification (see the description
of CSS Attributes below). It will be passed to the
body
tag.
After these four arguments, an arbitrary number of expressions may follow. They form the body of the resulting page, and are evaluated according to a special rule. This rule is slightly different from the evaluation of normal Lisp expressions:
Therefore, our source file might as well be written as:
########################################################################
(html 0 "Hello" "@lib.css" NIL
(prinl "Hello World!") )
########################################################################
The most typical print statements will be some HTML-tags:
########################################################################
(html 0 "Hello" "@lib.css" NIL
(<h1> NIL "Hello World!")
(<br> "This is some text.")
(ht:Prin "And this is a number: " (+ 1 2 3)) )
########################################################################
<h1>
and <br>
are tag functions.
<h1>
takes a CSS attribute as its first argument.
Note the use of ht:Prin
instead of prin
.
ht:Prin
should be used for all direct printing in HTML pages,
because it takes care to escape special characters.
The html
function above, and many of the
HTML tag functions, accept a CSS attribute specification.
This may be either an atom, a cons pair, or a list of cons pairs. We demonstrate
the effects with the <h1>
tag function.
An atom (usually a symbol or a string) is taken as a CSS class name
: (<h1> 'foo "Title")
<h1 class="foo">Title</h1>
For a cons pair, the CAR is taken as an attribute name, and the CDR as the attribute's value
: (<h1> '(id . bar) "Title")
<h1 id="bar">Title</h1>
Consequently, a list of cons pairs gives a set of attribute-value pairs
: (<h1> '((id . "abc") (lang . "de")) "Title")
<h1 id="abc" lang="de">Title</h1>
All pre-defined XHTML tag functions can be found in "@lib/xhtml.l". We recommend to look at their sources, and to experiment a bit, by executing them at a PicoLisp prompt, or by pressing the browser's "Reload" button after editing the "project.l" file.
For a suitable PicoLisp prompt, either execute (in a separate terminal
window) the PicoLisp Shell (psh
) command (works only if the
application server is running, and you did generate a ".pw"
file)
$ /usr/lib/picolisp/bin/psh 8080
:
or start the interpreter stand-alone, with "@lib/xhtml.l" loaded
$ pil @lib/http.l @lib/xhtml.l +
:
Note that for all these tag functions the above tag body evaluation rule applies.
Most tag functions are simple and straightforward. Some of them just print their arguments
: (<br> "Hello world")
Hello world<br/>
: (<em> "Hello world")
<em>Hello world</em>
while most of them take a CSS attribute specification
as their first argument (like the <h1>
tag above)
: (<div> 'main "Hello world")
<div class="main">Hello world</div>
: (<p> NIL "Hello world")
<p>Hello world</p>
: (<p> 'info "Hello world")
<p class="info">Hello world</p>
All of these functions take an arbitrary number of arguments, and may nest to an arbitrary depth (as long as the resulting HTML is legal)
: (<div> 'main
(<h1> NIL "Head")
(<p> NIL
(<br> "Line 1")
"Line"
(<nbsp>)
(+ 1 1) ) )
<div class="main"><h1>Head</h1>
<p>Line 1<br/>
Line 2</p>
</div>
HTML-lists, implemented by the <ol>
and
<ul>
tags, let you define hierarchical structures. You might
want to paste the following code into your copy of "project.l":
########################################################################
(html 0 "Unordered List" "@lib.css" NIL
(<ul> NIL
(<li> NIL "Item 1")
(<li> NIL
"Sublist 1"
(<ul> NIL
(<li> NIL "Item 1-1")
(<li> NIL "Item 1-2") ) )
(<li> NIL "Item 2")
(<li> NIL
"Sublist 2"
(<ul> NIL
(<li> NIL "Item 2-1")
(<li> NIL "Item 2-2") ) )
(<li> NIL "Item 3") ) )
########################################################################
Here, too, you can put arbitrary code into each node of that tree, including other tag functions.
Like the hierarchical structures with the list functions, you can generate
two-dimensional tables with the <table>
and
<row>
functions.
The following example prints a table of numbers and their squares:
########################################################################
(html 0 "Table" "@lib.css" NIL
(<table> NIL NIL NIL
(for N 10 # A table with 10 rows
(<row> NIL N (prin (* N N))) ) ) ) # and 2 columns
########################################################################
The first argument to <table>
is the usual CSS attribute,
the second an optional title ("caption"), and the third an optional list
specifying the column headers. In that list, you may supply a list for a each
column, with a CSS attribute in its CAR, and a tag body in its CDR for the
contents of the column header.
The body of <table>
contains calls to the
<row>
function. This function is special in that each
expression in its body will go to a separate column of the table. If both for
the column header and the row function an CSS attribute is given, they will be
combined by a space and passed to the HTML <td>
tag. This
permits distinct CSS specifications for each column and row.
As an extension of the above table example, let's pass some attributes for
the table itself (not recommended - better define such styles in a CSS file and
then just pass the class name to <table>
), right-align both
columns, and print each row in an alternating red and blue color
########################################################################
(html 0 "Table" "@lib.css" NIL
(<table>
'((width . "200px") (style . "border: dotted 1px;")) # table style
"Square Numbers" # caption
'((align "Number") (align "Square")) # 2 headers
(for N 10 # 10 rows
(<row> (xchg '(red) '(blue)) # red or blue
N # 2 columns
(prin (* N N) ) ) ) ) )
########################################################################
If you wish to concatenate two or more cells in a table, so that a single
cell spans several columns, you can pass the symbol '-
' for the
additional cell data to <row>
. This will cause the data given
to the left of the '-
' symbols to expand to the right.
You can also directly specify table structures with the simple
<th>
, <tr>
and <td>
tag
functions.
If you just need a two-dimensional arrangement of components, the even
simpler <grid>
function might be convenient:
########################################################################
(html 0 "Grid" "@lib.css" NIL
(<grid> 3
"A" "B" "C"
123 456 789 ) )
########################################################################
It just takes a specification for the number of columns (here: 3) as its first argument, and then a single expression for each cell. Instead of a number, you can also pass a list of CSS attributes. Then the length of that list will determine the number of columns. You can change the second line in the above example to
(<grid> '(NIL NIL right)
Then the third column will be right aligned.
The two most powerful tag functions are <menu>
and
<tab>
. Used separately or in combination, they form a
navigation framework with
The following example is not very useful, because the URLs of all items link to the same "project.l" page, but it should suffice to demonstrate the functionality:
########################################################################
(html 0 "Menu+Tab" "@lib.css" NIL
(<div> '(id . menu)
(<menu>
("Item" "project.l") # Top level item
(NIL (<hr>)) # Plain HTML
(T "Submenu 1" # Submenu
("Subitem 1.1" "project.l")
(T "Submenu 1.2"
("Subitem 1.2.1" "project.l")
("Subitem 1.2.2" "project.l")
("Subitem 1.2.3" "project.l") )
("Subitem 1.3" "project.l") )
(T "Submenu 2"
("Subitem 2.1" "project.l")
("Subitem 2.2" "project.l") ) ) )
(<div> '(id . main)
(<h1> NIL "Menu+Tab")
(<tab>
("Tab1"
(<h3> NIL "This is Tab 1") )
("Tab2"
(<h3> NIL "This is Tab 2") )
("Tab3"
(<h3> NIL "This is Tab 3") ) ) ) )
########################################################################
<menu>
takes a sequence of menu items. Each menu item is a
list, with its CAR either
NIL
: The entry is not an active menu item, and the rest of the
list may consist of arbitrary code (usually HTML tags).
T
: The second element is taken as a submenu name, and a click
on that name will open or close the corresponding submenu. The rest of the list
recursively specifies the submenu items (may nest to arbitrary depth).
<tab>
takes a list of subpages. Each page is simply a tab
name, followed by arbitrary code (typically HTML tags).
Note that only a single menu and a single tab may be active at the same time.
In HTML, the only possibility for user input is via <form>
and <input>
elements, using the HTTP POST method to
communicate with the server.
"@lib/xhtml.l" defines a function called <post>
, and a
collection of input tag functions, which allow direct programming of HTML forms.
We will supply only one simple example:
########################################################################
(html 0 "Simple Form" "@lib.css" NIL
(<post> NIL "project.l"
(<field> 10 '*Text)
(<submit> "Save") ) )
########################################################################
This associates a text input field with a global variable *Text
.
The field displays the current value of *Text
, and pressing the
submit button causes a reload of "project.l" with *Text
set to any
string entered by the user.
An application program could then use that variable to do something useful, for example store its value in a database.
The problem with such a straightforward use of forms is that
<hidden>
tags.
Though we wrote a few applications in that style, we recommend the GUI framework provided by "@lib/form.l". It does not need any variables for the client/server communication, but implements a class hierarchy of GUI components for the abstraction of application logic, button actions and data linkage.
First of all, we need to establish a persistent environment on the server, to handle each individual session (for each connected client).
Technically, this is just a child process of the server we started above, which does not terminate immediately after it sent its
page to the browser. It is achieved by calling the app
function
somewhere in the application's startup code.
########################################################################
(app) # Start a session
(html 0 "Simple Session" "@lib.css" NIL
(<post> NIL "project.l"
(<field> 10 '*Text)
(<submit> "Save") ) )
########################################################################
Nothing else changed from the previous example. However, when you connect your browser and then look at the terminal window where you started the application server, you'll notice a colon, the PicoLisp prompt
$ pil @lib/http.l @lib/xhtml.l @lib/form.l --server 8080 project.l +
:
Tools like the Unix ps
utility will tell you that now two
picolisp
processes are running, the first being the parent of the
second.
If you enter some text, say "abcdef", into the text field in the browser
window, press the submit button, and inspect the Lisp *Text
variable,
: *Text
-> "abcdef"
you see that we now have a dedicated PicoLisp process, "connected" to the client.
You can terminate this process (like any interactive PicoLisp) by hitting
Ctrl-D
on an empty line. Otherwise, it will terminate by itself if
no other browser requests arrive within a default timeout period of 5 minutes.
To start a (non-debug) production version, the server is commonly started
without the '+' flag, and with -wait
$ pil @lib/http.l @lib/xhtml.l @lib/form.l --server 8080 project.l -wait
In that way, no command line prompt appears when a client connects.
Now that we have a persistent session for each client, we can set up an active GUI framework.
This is done by wrapping the call to the html
function with
action
. Inside the body of html
can be - in addition
to all other kinds of tag functions - one or more calls to form
########################################################################
(app) # Start session
(action # Action handler
(html 0 "Form" "@lib.css" NIL # HTTP/HTML protocol
(form NIL # Form
(gui 'a '(+TextField) 10) # Text Field
(gui '(+Button) "Print" # Button
'(msg (val> (: home a))) ) ) ) )
########################################################################
Note that there is no longer a global variable like *Text
to
hold the contents of the input field. Instead, we gave a local, symbolic name
'a
' to a +TextField
component
(gui 'a '(+TextField) 10) # Text Field
Other components can refer to it
'(msg (val> (: home a)))
(: home)
is always the form which contains this GUI component.
So (: home a)
evaluates to the component 'a
' in the
current form. As msg
prints its
argument to standard error, and the val>
method retrieves the
current contents of a component, we will see on the console the text typed into
the text field when we press the button.
An action
without embedded form
s - or a
form
without a surrounding action
- does not make much
sense by itself. Inside html
and form
, however, calls
to HTML functions (and any other Lisp functions, for that matter) can be freely
mixed.
In general, a typical page may have the form
(action # Action handler
(html .. # HTTP/HTML protocol
(<h1> ..) # HTML tags
(form NIL # Form
(<h3> ..)
(gui ..) # GUI component(s)
(gui ..)
.. )
(<h2> ..)
(form NIL # Another form
(<h3> ..)
(gui ..) # GUI component(s)
.. )
(<br> ..)
.. ) )
gui
FunctionThe most prominent function in a form
body is gui
.
It is the workhorse of GUI construction.
Outside of a form
body, gui
is undefined.
Otherwise, it takes an optional alias name, a list of classes, and additional
arguments as needed by the constructors of these classes. We saw this example
before
(gui 'a '(+TextField) 10) # Text Field
Here, 'a
' is an alias name for a component of type
(+TextField)
. The numeric argument 10
is passed to the
text field, specifying its width. See the chapter on GUI
Classes for more examples.
During a GET request, gui
is basically a front-end to
new
. It builds a component, stores it in the internal structures of
the current form, and initializes it by sending the init>
message to the component. Finally, it sends it the show>
message, to produce HTML code and transmit it to the browser.
During a POST request, gui
does not build any new components.
Instead, the existing components are re-used. So gui
does not have
much more to do than sending the show>
message to a component.
HTTP has only two methods to change a browser window: GET and POST. We employ these two methods in a certain defined, specialized way:
A button's action code can do almost anything: Read and modify the contents of input fields, communicate with the database, display alerts and dialogs, or even fake the POST request to a GET, with the effect of showing a completely different document (See Switching URLs).
GET builds up all GUI components on the server. These components are objects
which encapsulate state and behavior of the HTML page in the browser. Whenever a
button is pressed, the page is reloaded via a POST request. Then - before any
output is sent to the browser - the action
function takes control.
It performs error checks on all components, processes possible user input on the
HTML page, and stores the values in correct format (text, number, date, object
etc.) in each component.
The state of a form is preserved over time. When the user returns to a previous page with the browser's BACK button, that state is reactivated, and may be POSTed again.
The following silly example displays two text fields. If you enter some text into the "Source" field, you can copy it in upper or lower case to the "Destination" field by pressing one of the buttons
########################################################################
(app)
(action
(html 0 "Case Conversion" "@lib.css" NIL
(form NIL
(<grid> 2
"Source" (gui 'src '(+TextField) 30)
"Destination" (gui 'dst '(+Lock +TextField) 30) )
(gui '(+JS +Button) "Upper Case"
'(set> (: home dst)
(uppc (val> (: home src))) ) )
(gui '(+JS +Button) "Lower Case"
'(set> (: home dst)
(lowc (val> (: home src))) ) ) ) ) )
########################################################################
The +Lock
prefix class in the "Destination" field makes that
field read-only. The only way to get some text into that field is by using one
of the buttons.
Because an action code runs before html
has a chance to output
an HTTP header, it can abort the current page and present something different to
the user. This might, of course, be another HTML page, but would not be very
interesting as a normal link would suffice. Instead, it can cause the download
of dynamically generated data.
The next example shows a text area and two buttons. Any text entered into the text area is exported either as a text file via the first button, or a PDF document via the second button
########################################################################
(load "@lib/ps.l")
(app)
(action
(html 0 "Export" "@lib.css" NIL
(form NIL
(gui '(+TextField) 30 8)
(gui '(+Button) "Text"
'(let Txt (tmp "export.txt")
(out Txt (prinl (val> (: home gui 1))))
(url Txt) ) )
(gui '(+Button) "PDF"
'(psOut NIL "foo"
(a4)
(indent 40 40)
(down 60)
(hline 3)
(font (14 . "Times-Roman")
(ps (val> (: home gui 1))) )
(hline 3)
(page) ) ) ) ) )
########################################################################
(a text area is built when you supply two numeric arguments (columns and
rows) to a +TextField
class)
The action code of the first button creates a temporary file (i.e. a file
named "export.txt" in the current process's temporary space), prints the value
of the text area (this time we did not bother to give it a name, we simply refer
to it as the form's first gui list element) into that file, and then calls the
url
function with the file name.
The second button uses the PostScript library "@lib/ps.l" to create a
temporary file "foo.pdf". Here, the temporary file creation and the call to the
url
function is hidden in the internal mechanisms of
psOut
. The effect is that the browser receives a PDF document and
displays it.
Alerts and dialogs are not really what they used to be ;-)
They do not "pop up". In this framework, they are just a kind of simple-to-use, pre-fabricated form. They can be invoked by a button's action code, and appear always on the current page, immediately preceding the form which created them.
Let's look at an example which uses two alerts and a dialog. In the beginning, it displays a simple form, with a locked text field, and two buttons
########################################################################
(app)
(action
(html 0 "Alerts and Dialogs" "@lib.css" NIL
(form NIL
(gui '(+Init +Lock +TextField) "Initial Text" 20 "My Text")
(gui '(+Button) "Alert"
'(alert NIL "This is an alert " (okButton)) )
(gui '(+Button) "Dialog"
'(dialog NIL
(<br> "This is a dialog.")
(<br>
"You can change the text here "
(gui '(+Init +TextField) (val> (: top 1 gui 1)) 20) )
(<br> "and then re-submit it to the form.")
(gui '(+Button) "Re-Submit"
'(alert NIL "Are you sure? "
(yesButton
'(set> (: home top 2 gui 1)
(val> (: home top 1 gui 1)) ) )
(noButton) ) )
(cancelButton) ) ) ) ) )
########################################################################
The +Init
prefix class initializes the "My Text" field with the
string "Initial Text". As the field is locked, you cannot modify this value
directly.
The first button brings up an alert saying "This is an alert.". You can dispose it by pressing "OK".
The second button brings up a dialog with an editable text field, containing a copy of the value from the form's locked text field. You can modify this value, and send it back to the form, if you press "Re-Submit" and answer "Yes" to the "Are you sure?" alert.
Now let's forget our "project.l" test file for a moment, and move on to a more substantial and practical, stand-alone, example. Using what we have learned so far, we want to build a simple bignum calculator. ("bignum" because PicoLisp can do only bignums)
It uses a single form, a single numeric input field, and lots of buttons. It can be found in the PicoLisp distribution (e.g. under "/usr/share/picolisp/") in "misc/calc.l", together with a directly executable wrapper script "misc/calc".
To use it, change to the PicoLisp installation directory, and start it as
$ misc/calc
or call it with an absolute path, e.g.
$ /usr/share/picolisp/misc/calc
If you like to get a PicoLisp prompt for inspection, start it instead as
$ pil misc/calc.l -main -go +
Then - as before - point your browser to 'http://localhost:8080
'.
The code for the calculator logic and the GUI is rather straightforward. The
entry point is the single function calculator
. It is called
directly (as described in URL Syntax) as the server's
default URL, and implicitly in all POST requests. No further file access is
needed once the calculator is running.
Note that for a production application, we inserted an allow-statement (as recommended by the Security chapter)
(allowed NIL "!calculator" "@lib.css")
at the beginning of "misc/calc.l". This will restrict external access to that single function.
The calculator uses three global variables, *Init
,
*Accu
and *Stack
. *Init
is a boolean flag
set by the operator buttons to indicate that the next digit should initialize
the accumulator to zero. *Accu
is the accumulator. It is always
displayed in the numeric input field, accepts user input, and it holds the
results of calculations. *Stack
is a push-down stack, holding
postponed calculations (operators, priorities and intermediate results) with
lower-priority operators, while calculations with higher-priority operators are
performed.
The function digit
is called by the digit buttons, and adds
another digit to the accumulator.
The function calc
does an actual calculation step. It pops the
stack, checks for division by zero, and displays an error alert if necessary.
operand
processes an operand button, accepting a function and a
priority as arguments. It compares the priority with that in the top-of-stack
element, and delays the calculation if it is less.
finish
is used to calculate the final result.
The calculator
function has one numeric input field, with a
width of 60 characters
(gui '(+Var +NumField) '*Accu 60)
The +Var
prefix class associates this field with the global
variable *Accu
. All changes to the field will show up in that
variable, and modification of that variable's value will appear in the field.
The square root operator button has an
+Able
prefix class
(gui '(+Able +JS +Button) '(ge0 *Accu) (char 8730)
'(setq *Accu (sqrt *Accu)) )
with an argument expression which checks that the current value in the accumulator is positive, and disables the button if otherwise.
The rest of the form is just an array (grid) of buttons, encapsulating all
functionality of the calculator. The user can enter numbers into the input
field, either by using the digit buttons, or by directly typing them in, and
perform calculations with the operator buttons. Supported operations are
addition, subtraction, multiplication, division, sign inversion, square root and
power (all in bignum integer arithmetic). The 'C
' button just
clears the accumulator, while the 'A
' button also clears all
pending calculations.
All that in 53 lines of code!
Charts are virtual components, maintaining the internal representation of two-dimensional data.
Typically, these data are nested lists, database selections, or some kind of dynamically generated tabular information. Charts make it possible to view them in rows and columns (usually in HTML tables), scroll up and down, and associate them with their corresponding visible GUI components.
In fact, the logic to handle charts makes up a substantial part of the whole framework, with large impact on all internal mechanisms. Each GUI component must know whether it is part of a chart or not, to be able to handle its contents properly during updates and user interactions.
Let's assume we want to collect textual and numerical data. We might create a table
########################################################################
(app)
(action
(html 0 "Table" "@lib.css" NIL
(form NIL
(<table> NIL NIL '((NIL "Text") (NIL "Number"))
(do 4
(<row> NIL
(gui '(+TextField) 20)
(gui '(+NumField) 10) ) ) )
(<submit> "Save") ) ) )
########################################################################
with two columns "Text" and "Number", and four rows, each containing a
+TextField
and a +NumField
.
You can enter text into the first column, and numbers into the second. Pressing the "Save" button stores these values in the components on the server (or produces an error message if a string in the second column is not a legal number).
There are two problems with this solution:
: (val> (get *Top 'gui 2)) # Value in the first row, second column
-> 123
there is no direct way to get the whole data structure as a single list.
Instead, you have to traverse all GUI components and collect the data.
A chart can handle these things:
########################################################################
(app)
(action
(html 0 "Chart" "@lib.css" NIL
(form NIL
(gui '(+Chart) 2) # Inserted a +Chart
(<table> NIL NIL '((NIL "Text") (NIL "Number"))
(do 4
(<row> NIL
(gui 1 '(+TextField) 20) # Inserted '1'
(gui 2 '(+NumField) 10) ) ) ) # Inserted '2'
(<submit> "Save") ) ) )
########################################################################
Note that we inserted a +Chart
component before the GUI
components which should be managed by the chart. The argument '2' tells the
chart that it has to expect two columns.
Each component got an index number (here '1' and '2') as the first argument
to gui
, indicating the column into which this component should go
within the chart.
Now - if you entered "a", "b" and "c" into the first, and 1, 2, and 3 into
the second column - we can retrieve the chart's complete contents by sending it
the val>
message
: (val> (get *Top 'chart 1)) # Retrieve the value of the first chart
-> (("a" 1) ("b" 2) ("c" 3))
BTW, a more convenient function is chart
: (val> (chart)) # Retrieve the value of the current chart
-> (("a" 1) ("b" 2) ("c" 3))
chart
can be used instead of the above construct when we want to
access the "current" chart, i.e. the chart most recently processed in the
current form.
To enable scrolling, let's also insert two buttons. We use the pre-defined
classes +UpButton
and +DnButton
########################################################################
(app)
(action
(html 0 "Scrollable Chart" "@lib.css" NIL
(form NIL
(gui '(+Chart) 2)
(<table> NIL NIL '((NIL "Text") (NIL "Number"))
(do 4
(<row> NIL
(gui 1 '(+TextField) 20)
(gui 2 '(+NumField) 10) ) ) )
(gui '(+UpButton) 1) # Inserted two buttons
(gui '(+DnButton) 1)
(----)
(<submit> "Save") ) ) )
########################################################################
to scroll down and up a single (argument '1') line at a time.
Now it is possible to enter a few rows of data, scroll down, and continue. It is not necessary (except in the beginning, when the scroll buttons are still disabled) to press the "Save" button, because any button in the form will send changes to the server's internal structures before any action is performed.
As we said, a chart is a virtual component to edit two-dimensional data. Therefore, a chart's native data format is a list of lists: Each sublist represents a single row of data, and each element of a row corresponds to a single GUI component.
In the example above, we saw a row like
("a" 1)
being mapped to
(gui 1 '(+TextField) 20)
(gui 2 '(+NumField) 10)
Quite often, however, such a one-to-one relationship is not desired. The internal data structures may have to be presented in a different form to the user, and user input may need conversion to an internal representation.
For that, a chart accepts - in addition to the "number of columns" argument - two optional function arguments. The first function is invoked to 'put' the internal representation into the GUI components, and the second to 'get' data from the GUI into the internal representation.
A typical example is a chart displaying customers in a database. While the internal representation is a (one-dimensional) list of customer objects, 'put' expands each object to a list with, say, the customer's first and second name, telephone number, address and so on. When the user enters a customer's name, 'get' locates the matching object in the database and stores it in the internal representation. In the following, 'put' will in turn expand it to the GUI.
For now, let's stick with a simpler example: A chart that holds just a list of numbers, but expands in the GUI to show also a textual form of each number (in German).
########################################################################
(app)
(load "@lib/zahlwort.l")
(action
(html 0 "Numerals" "@lib.css" NIL
(form NIL
(gui '(+Init +Chart) (1 5 7) 2
'((N) (list N (zahlwort N)))
car )
(<table> NIL NIL '((NIL "Numeral") (NIL "German"))
(do 4
(<row> NIL
(gui 1 '(+NumField) 9)
(gui 2 '(+Lock +TextField) 90) ) ) )
(gui '(+UpButton) 1)
(gui '(+DnButton) 1)
(----)
(<submit> "Save") ) ) )
########################################################################
"@lib/zahlwort.l" defines the utility function zahlwort
, which
is required later by the 'put' function. zahlwort
accepts a number
and returns its wording in German.
Now look at the code
(gui '(+Init +Chart) (1 5 7) 2
'((N) (list N (zahlwort N)))
car )
We prefix the +Chart
class with +Init
, and pass it
a list of numbers (1 5 7)
for the initial value of the chart. Then,
following the '2' (the chart has two columns), we pass a 'put' function
'((N) (list N (zahlwort N)))
which takes a number and returns a list of that number and its wording, and a 'get' function
car )
which in turn accepts such a list and returns a number, which happens to be the list's first element.
You can see from this example that 'get' is the inverse function of 'put'. 'get' can be omitted, however, if the chart is read-only (contains no (or only locked) input fields).
The field in the second column
(gui 2 '(+Lock +TextField) 90) ) ) )
is locked, because it displays the text generated by 'put', and is not supposed to accept any user input.
When you start up this form in your browser, you'll see three pre-filled
lines with "1/eins", "5/fünf" and "7/sieben", according to the
+Init
argument (1 5 7)
. Typing a number somewhere into
the first column, and pressing ENTER or one of the buttons, will show a suitable
text in the second column.
In previous chapters we saw examples of GUI classes like
+TextField
, +NumField
or +Button
, often
in combination with prefix classes like +Lock
, +Init
or +Able
. Now we take a broader look at the whole hierarchy, and
try more examples.
The abstract class +gui
is the base of all GUI classes. A live
view of the class hierarchy can be obtained with the dep
("dependencies") function:
: (dep '+gui)
+gui
+JsField
+Button
+UpButton
+PickButton
+DstButton
+ClrButton
+ChoButton
+Choice
+GoButton
+BubbleButton
+DelRowButton
+ShowButton
+DnButton
+Img
+field
+Checkbox
+TextField
+FileField
+ClassField
+numField
+NumField
+FixField
+BlobField
+DateField
+SymField
+UpField
+MailField
+SexField
+AtomField
+PwField
+ListTextField
+LinesField
+TelField
+TimeField
+HttpField
+Radio
-> +gui
We see, for example, that +DnButton
is a subclass of
+Button
, which in turn is a subclass of +gui
.
Inspecting +DnButton
directly
: (dep '+DnButton)
+Tiny
+Rid
+JS
+Able
+gui
+Button
+DnButton
-> +DnButton
shows that +DnButton
inherits from +Tiny
,
+Rid
, +Able
and +Button
. The actual
definition of +DnButton
can be found in "@lib/form.l"
(class +DnButton +Tiny +Rid +JS +Able +Button)
...
In general, "@lib/form.l" is the ultimate reference to the framework, and should be freely consulted.
Input fields implement the visual display of application data, and allow - when enabled - input and modification of these data.
On the HTML level, they can take the form of
Except for checkboxes, which are implemented by the Checkbox class, all these HTML representations are
generated by +TextField
and its content-specific subclasses like
+NumField
, +DateField
etc. Their actual appearance (as
one of the above forms) depends on their arguments:
We saw already "normal" text fields. They are created with a single numeric argument. This example creates an editable field with a width of 10 characters:
(gui '(+TextField) 10)
If you supply a second numeric for the line count ('4' in this case), you'll get a text area:
(gui '(+TextField) 10 4)
Supplying a list of values instead of a count yields a drop-down selection (combo box):
(gui '(+TextField) '("Value 1" "Value 2" "Value 3"))
In addition to these arguments, you can pass a string. Then the field is created with a label:
(gui '(+TextField) 10 "Plain")
(gui '(+TextField) 10 4 "Text Area")
(gui '(+TextField) '("Value 1" "Value 2" "Value 3") "Selection")
Finally, without any arguments, the field will appear as a plain HTML text:
(gui '(+TextField))
This makes mainly sense in combination with prefix classes like
+Var
and +Obj
, to manage the contents of these fields,
and achieve special behavior as HTML links or scrollable chart values.
A +NumField
returns a number from its val>
method, and accepts a number for its set>
method. It issues an
error message when user input cannot be converted to a number.
Large numbers are shown with a thousands-separator, as determined by the current locale.
########################################################################
(app)
(action
(html 0 "+NumField" "@lib.css" NIL
(form NIL
(gui '(+NumField) 10)
(gui '(+JS +Button) "Print value"
'(msg (val> (: home gui 1))) )
(gui '(+JS +Button) "Set to 123"
'(set> (: home gui 1) 123) ) ) ) )
########################################################################
A +FixField
needs an additional scale factor argument, and
accepts/returns scaled fixpoint numbers.
The decimal separator is determined by the current locale.
########################################################################
(app)
(action
(html 0 "+FixField" "@lib.css" NIL
(form NIL
(gui '(+FixField) 3 10)
(gui '(+JS +Button) "Print value"
'(msg (format (val> (: home gui 1)) 3)) )
(gui '(+JS +Button) "Set to 123.456"
'(set> (: home gui 1) 123456) ) ) ) )
########################################################################
A +DateField
accepts and returns a date
value.
########################################################################
(app)
(action
(html 0 "+DateField" "@lib.css" NIL
(form NIL
(gui '(+DateField) 10)
(gui '(+JS +Button) "Print value"
'(msg (datStr (val> (: home gui 1)))) )
(gui '(+JS +Button) "Set to \"today\""
'(set> (: home gui 1) (date)) ) ) ) )
########################################################################
The format displayed to - and entered by - the user depends on the current
locale (see datStr
and expDat
). You can change it, for example to
: (locale "DE" "de")
-> NIL
If no locale is set, the format is YYYY-MM-DD. Some pre-defined locales use patterns like DD.MM.YYYY (DE), YYYY/MM/DD (JP), DD/MM/YYYY (UK), or MM/DD/YYYY (US).
An error is issued when user input does not match the current locale's date format.
Independent from the locale setting, a +DateField
tries to
expand abbreviated input from the user. A small number is taken as that day of
the current month, larger numbers expand to day and month, or to day, month and
year:
Similar is the +TimeField
. It accepts and returns a time
value.
########################################################################
(app)
(action
(html 0 "+TimeField" "@lib.css" NIL
(form NIL
(gui '(+TimeField) 8)
(gui '(+JS +Button) "Print value"
'(msg (tim$ (val> (: home gui 1)))) )
(gui '(+JS +Button) "Set to \"now\""
'(set> (: home gui 1) (time)) ) ) ) )
########################################################################
When the field width is '8', like in this example, time is displayed in the
format HH:MM:SS
. Another possible value would be '5', causing
+TimeField
to display its value as HH:MM
.
An error is issued when user input cannot be converted to a time value.
The user may omit the colons. If he inputs just a small number, it should be between '0' and '23', and will be taken as a full hour. '125' expands to "12:05", '124517' to "12:45:17", and so on.
Telephone numbers are represented internally by the country code (without a
leading plus sign or zero) followed by the local phone number (ideally separated
by spaces) and the phone extension (ideally separated by a hyphen). The exact
format of the phone number string is not enforced by the GUI, but further
processing (e.g. database searches) normally uses fold
for better reproducibility.
To display a phone number, +TelField
replaces the country code
with a single zero if it is the country code of the current locale, or prepends
it with a plus sign if it is a foreign country (see telStr
).
For user input, a plus sign or a double zero is simply dropped, while a
single leading zero is replaced with the current locale's country code (see
expTel
).
########################################################################
(app)
(locale "DE" "de")
(action
(html 0 "+TelField" "@lib.css" NIL
(form NIL
(gui '(+TelField) 20)
(gui '(+JS +Button) "Print value"
'(msg (val> (: home gui 1))) )
(gui '(+JS +Button) "Set to \"49 1234 5678-0\""
'(set> (: home gui 1) "49 1234 5678-0") ) ) ) )
########################################################################
A +Checkbox
is straightforward. User interaction is restricted
to clicking it on and off. It accepts boolean (NIL
or
non-NIL
) values, and returns T
or NIL
.
########################################################################
(app)
(action
(html 0 "+Checkbox" "@lib.css" NIL
(form NIL
(gui '(+Checkbox))
(gui '(+JS +Button) "Print value"
'(msg (val> (: home gui 1))) )
(gui '(+JS +Button) "On"
'(set> (: home gui 1) T) )
(gui '(+JS +Button) "Off"
'(set> (: home gui 1) NIL) ) ) ) )
########################################################################
A big part of this framework's power is owed to the combinatorial flexibility of prefix classes for GUI- and DB-objects. They allow to surgically override individual methods in the inheritance tree, and can be combined in various ways to achieve any desired behavior.
Technically, there is nothing special about prefix classes. They are just normal classes. They are called "prefix" because they are intended to be written before other classes in a class's or object's list of superclasses.
Usually they take their own arguments for their T
method from
the list of arguments to the gui
function.
+Init
overrides the init>
method for that
component. The init>
message is sent to a +gui
component when the page is loaded for the first time (during a GET request).
+Init
takes an expression for the initial value of that field.
(gui '(+Init +TextField) "This is the initial text" 30)
Other classes which automatically give a value to a field are
+Var
(linking the field to a variable) and +E/R
(linking the field to a database entity/relation).
+Cue
can be used, for example in "mandatory" fields, to give a
hint to the user about what he is supposed to enter. It will display the
argument value, in angular brackets, if and only if the field's value is
NIL
, and the val>
method will return
NIL
despite the fact that this value is displayed.
Cause an empty field to display "<Please enter some text here>":
(gui '(+Cue +TextField) "Please enter some text here" 30)
An important feature of an interactive GUI is the context-sensitive disabling and enabling of individual components, or of a whole form.
The +Able
prefix class takes an argument expression, and
disables the component if this expression returns NIL
. We saw an
example for its usage already in the square root
button of the calculator example. Or, for illustration purposes, imagine a
button which is supposed to be enabled only after Christmas
(gui '(+Able +Button)
'(>= (cdr (date (date))) (12 24))
"Close this year"
'(endOfYearProcessing) )
or a password field that is disabled as long as somebody is logged in
(gui '(+Able +PwField) '(not *Login) 10 "Password")
A special case is the +Lock
prefix, which permanently and
unconditionally disables a component. It takes no arguments
(gui '(+Lock +NumField) 10 "Count")
('10' and "Count" are for the +NumField
), and creates a
read-only field.
The whole form can be disabled by calling disable
with a
non-NIL
argument. This affects all components in this form. Staying
with the above example, we can make the form read-only until Christmas
(form NIL
(disable (> (12 24) (cdr (date (date))))) # Disable whole form
(gui ..)
.. )
Even in a completely disabled form, however, it is often necessary to
re-enable certain components, as they are needed for navigation, scrolling, or
other activities which don't affect the contents of the form. This is done by
prefixing these fields with +Rid
(i.e. getting "rid" of the lock).
(form NIL
(disable (> (12 24) (cdr (date (date)))))
(gui ..)
..
(gui '(+Rid +Button) ..) # Button is enabled despite the disabled form
.. )
GUI prefix classes allow a fine-grained control of how values are stored in -
and retrieved from - components. As in predefined classes like
+NumField
or +DateField
, they override the
set>
and/or val>
methods.
+Set
takes an argument function which is called whenever that
field is set to some value. To convert all user input to upper case
(gui '(+Set +TextField) uppc 30)
+Val
is the complement to +Set
. It takes a function
which is called whenever the field's value is retrieved. To return the square of
a field's value
(gui '(+Val +NumField) '((N) (* N N)) 10)
+Fmt
is just a combination of +Set
and
+Val
, and takes two functional arguments. This example will display
upper case characters, while returning lower case characters internally
(gui '(+Fmt +TextField) uppc lowc 30)
+Map
does (like +Fmt
) a two-way translation. It
uses a list of cons pairs for a linear lookup, where the CARs represent the
displayed values which are internally mapped to the values in the CDRs. If a
value is not found in this list during set>
or
val>
, it is passed through unchanged.
Normally, +Map
is used in combination with the combo box
incarnation of text fields (see Input Fields). This
example displays "One", "Two" and "Three" to the user, but returns a number 1, 2
or 3 internally
########################################################################
(app)
(action
(html 0 "+Map" "@lib.css" NIL
(form NIL
(gui '(+Map +TextField)
'(("One" . 1) ("Two" . 2) ("Three" . 3))
'("One" "Two" "Three") )
(gui '(+Button) "Print"
'(msg (val> (field -1))) ) ) ) )
########################################################################
Whenever a button is pressed in the GUI, any changes caused by
action
in the current environment (e.g. the database or application
state) need to be reflected in the corresponding GUI fields. For that, the
upd>
message is sent to all components. Each component then
takes appropriate measures (e.g. refresh from database objects, load values from
variables, or calculate a new value) to update its value.
While the upd>
method is mainly used internally, it can be
overridden in existing classes via the +Upd
prefix class. Let's
print updated values to standard error
########################################################################
(app)
(default *Number 0)
(action
(html 0 "+Upd" "@lib.css" NIL
(form NIL
(gui '(+Upd +Var +NumField)
'(prog (extra) (msg *Number))
'*Number 8 )
(gui '(+JS +Button) "Increment"
'(inc '*Number) ) ) ) )
########################################################################
To allow automatic validation of user input, the chk>
message
is sent to all components at appropriate times. The corresponding method should
return NIL
if the value is all right, or a string describing the
error otherwise.
Many of the built-in classes have a chk>
method. The
+NumField
class checks for legal numeric input, or the
+DateField
for a valid calendar date.
An on-the-fly check can be implemented with the +Chk
prefix
class. The following code only accepts numbers not bigger than 9: The
or
expression first delegates the check to the main
+NumField
class, and - if it does not give an error - returns an
error string when the current value is greater than 9.
########################################################################
(app)
(action
(html 0 "+Chk" "@lib.css" NIL
(form NIL
(gui '(+Chk +NumField)
'(or
(extra)
(and (> (val> This) 9) "Number too big") )
12 )
(gui '(+JS +Button) "Print"
'(msg (val> (field -1))) ) ) ) )
########################################################################
A more direct kind of validation is built-in via the +Limit
class. It controls the maxlength
attribute of the generated HTML
input field component. Thus, it is impossible to type to more characters than
allowed into the field.
########################################################################
(app)
(action
(html 0 "+Limit" "@lib.css" NIL
(form NIL
(gui '(+Limit +TextField) 4 8)
(gui '(+JS +Button) "Print"
'(msg (val> (field -1))) ) ) ) )
########################################################################
Although set>
and val>
are the official
methods to get a value in and out of a GUI component, they are not very often
used explicitly. Instead, components are directly linked to internal Lisp data
structures, which are usually either variables or database objects.
The +Var
prefix class takes a variable (described as the
var
data type - either a symbol or a cons pair - in the Function Reference). In the following example, we
initialize a global variable with the value "abc", and let a
+TextField
operate on it. The "Print" button can be used to display
its current value.
########################################################################
(app)
(setq *TextVariable "abc")
(action
(html 0 "+Var" "@lib.css" NIL
(form NIL
(gui '(+Var +TextField) '*TextVariable 8)
(gui '(+JS +Button) "Print"
'(msg *TextVariable) ) ) ) )
########################################################################
+E/R
takes an entity/relation specification. This is a cons
pair, with a relation in its CAR (e.g. nm
, for an object's name),
and an expression in its CDR (typically (: home obj)
, the object
stored in the obj
property of the current form).
For an isolated, simple example, we create a temporary database, and access
the nr
and nm
properties of an object stored in a
global variable *Obj
.
########################################################################
(when (app) # On start of session
(class +Tst +Entity) # Define data model
(rel nr (+Number)) # with a number
(rel nm (+String)) # and a string
(pool (tmp "db")) # Create temporary DB
(setq *Obj # and a single object
(new! '(+Tst) 'nr 1 'nm "New Object") ) )
(action
(html 0 "+E/R" "@lib.css" NIL
(form NIL
(gui '(+E/R +NumField) '(nr . *Obj) 8) # Linkage to 'nr'
(gui '(+E/R +TextField) '(nm . *Obj) 20) # Linkage to 'nm'
(gui '(+JS +Button) "Show" # Show the object
'(out 2 (show *Obj)) ) ) ) ) # on standard error
########################################################################
Buttons are, as explained in Control Flow, the only way (via POST requests) for an application to communicate with the server.
Basically, a +Button
takes
Here is a minimal button, with just a label and an expression:
(gui '(+Button) "Label" '(doSomething))
And this is a button displaying different labels, depending on the state:
(gui '(+Button) "Enabled" "Disabled" '(doSomething))
To show an image instead of plain text, the label(s) must be preceeded by the
T
symbol:
(gui '(+Button) T "img/enabled.png" "img/disabled.png" '(doSomething))
The expression will be executed during action
handling (see Action Forms), when this button was pressed.
Like other components, buttons can be extended and combined with prefix classes, and a variety of predefined classes and class combinations are available.
Buttons are essential for the handling of alerts and dialogs. Besides buttons for normal functions, like scrolling in charts or other side effects, special buttons exist which can close an alert or dialog in addition to doing their principal job.
Such buttons are usually subclasses of +Close
, and most of them
can be called easily with ready-made functions like closeButton
,
cancelButton
, yesButton
or noButton
. We
saw a few examples in Alerts and Dialogs.
When a button inherits from the +JS
class (and JavaScript is
enabled in the browser), that button will possibly show a much faster response
in its action.
The reason is that the activation of a +JS
button will - instead
of doing a normal POST - first try to send only the contents of all GUI
components via an XMLHttpRequest to the server, and receive the updated values
in response. This avoids the flicker caused by reloading and rendering of the
whole page, is much faster, and also does not jump to the beginning of the page
if it is larger than the browser window. The effect is especially noticeable
while scrolling in charts.
Only if this fails, for example because an error message was issued, or a dialog popped up, it will fall back, and the form will be POSTed in the normal way.
Thus it makes no sense to use the +JS
prefix for buttons that
cause a change of the HTML code, open a dialog, or jump to another page. In such
cases, overall performance will even be worse, because the XMLHttpRequest is
tried first (but in vain).
When JavaScript is disabled int the browser, the XMLHttpRequest will not be tried at all. The form will be fully usable, though, with identical functionality and behavior, just a bit slower and not so smooth.
The PicoLisp release includes in the "app/" directory a minimal, yet complete reference application. This application is typical, in the sense that it implements many of the techniques described in this document, and it can be easily modified and extended. In fact, we use it as templates for our own production application development.
It is a kind of simplified ERP system, containing customers/suppliers, products (items), orders, and other data. The order input form performs live updates of customer and product selections, price, inventory and totals calculations, and generates on-the-fly PDF documents. Fine-grained access permissions are controlled via users, roles and permissions. It comes localized in six languages (English, Spanish, German, Norwegian, Russian and Japanese), with some initial data and two sample reports.
For a global installation (see Installation), please create a symbolic link to the place where the program files are installed. This is necessary because the application needs read/write access to the current working directory (for the database and other runtime data).
$ ln -s /usr/share/picolisp/app
As ever, you may start up the application in debugging mode
$ pil app/main.l -main -go +
or in (non-debug) production mode
$ pil app/main.l -main -go -wait
and go to 'http://localhost:8080
' with your
browser. You can login as user "admin", with password "admin". The demo data
contain several other users, but those are more restricted in their role
permissions.
Another possibility is to try the online version of this application at app.7fach.de.
Before or after you logged in, you can select another language, and click on the "Change" button. This will effect all GUI components (though not text from the database), and also the numeric, date and telephone number formats.
The navigation menu on the left side shows two items "Home" and "logout", and three submenus "Data", "Report" and "System".
Both "Home" and "logout" bring you back to the initial login form. Use "logout" if you want to switch to another user (say, for another set of permissions), and - more important - before you close your browser, to release possible locks and process resources on the server.
The "Data" submenu gives access to application specific data entry and maintenance: Orders, product items, customers and suppliers. The "Report" submenu contains two simple inventory and sales reports. And the "System" submenu leads to role and user administration.
You can open and close each submenu individually. Keeping more than one submenu open at a time lets you switch rapidly between different parts of the application.
The currently active menu item is indicated by a highlighted list style (no matter whether you arrived at this page directly via the menu or by clicking on a link somewhere else).
Each item in the "Data" or "System" submenu opens a search dialog for that class of entities. You can specify a search pattern, press the top right "Search" button (or just ENTER), and scroll through the list of results.
While the "Role" and "User" entities present simple dialogs (searching just by name), other entities can be searched by a variety of criteria. In those cases, a "Reset" button clears the contents of the whole dialog. A new object can be created with bottom right "New" button.
In any case, the first column will contain either a "@"-link (to jump to that object) or a "@"-button (to insert a reference to that object into the current form).
By default, the search will list all database objects with an attribute value greater than or equal to the search criterion. The comparison is done arithmetically for numbers, and alphabetically (case sensitive!) for text. This means, if you type "Free" in the "City" field of the "Customer/Supplier" dialog, the value of "Freetown" will be matched. On the other hand, an entry of "free" or "town" will yield no hits.
Some search fields, however, show a different behavior depending on the application:
Using the bottom left scroll buttons, you can scroll through the result list without limit. Clicking on a link will bring up the corresponding object. Be careful here to select the right column: Some dialogs (those for "Item" and "Order") also provide links for related entities (e.g. "Supplier").
A database object is usually displayed in its own individual form, which is determined by its entity class.
The basic layout should be consistent for all classes: Below the heading (which is usually the same as the invoking menu item) is the object's identifier (name, number, etc.), and then a row with an "Edit" button on the left, and "Delete" button, a "Select" button and two navigation links on the right side.
The form is brought up initially in read-only mode. This is necessary to prevent more than one user from modifying an object at the same time (and contrary to the previous PicoLisp Java frameworks, where this was not a problem because all changes were immediately reflected in the GUIs of other users).
So if you want to modify an object, you have to gain exclusive access by clicking on the "Edit" button. The form will be enabled, and the "Edit" button changes to "Done". Should any other user already have reserved this object, you will see a message telling his name and process ID.
An exception to this are objects that were just created with "New". They will automatically be reserved for you, and the "Edit" button will show up as "Done".
The "Delete" button pops up an alert, asking for confirmation. If the object is indeed deleted, this button changes to "Restore" and allows to undelete the object. Note that objects are never completely deleted from the database as long as there are any references from other objects. When a "deleted" object is shown, its identifier appears in square brackets.
The "Select" button (re-)displays the search dialog for this class of entities. The search criteria are preserved between invocations of each dialog, so that you can conveniently browse objects in this context.
The navigation links, pointing left and right, serve a similar purpose. They let you step sequentially through all objects of this class, in the order of the identifier's index.
Other buttons, depending on the entity, are usually arranged at the bottom of the form. The bottom rightmost one should always be another "Edit" / "Done" button.
As we said in the chapter on Scrolling, any button in the form will save changes to the underlying data model. As a special case, however, the "Done" button releases the object and reverts to "Edit". Besides this, the edit mode will also cease as soon as another object is displayed, be it by clicking on an object link (the pencil icon), the top right navigation links, or a link in a search dialog.
The only way to interact with a HTTP-based application server is to click either on a HTML link, or on a submit button (see also Control Flow). It is essential to understand the different effects of such a click on data entered or modified in the current form.
For that reason the layout design should clearly differentiate between links and buttons. Image buttons are not a good idea when in other places images are used for links. The standard button components should be preferred; they are usually rendered by the browser in a non-ambiguous three-dimensional look and feel.
Note that if JavaScript is enabled in the browser, changes will be automatically committed to the server.
The enabled or disabled state of a button is an integral part of the application logic. It must be indicated to the user with appropriate styles.
The data model for this mini application consists of only six entity classes (see the E/R diagram at the beginning of "app/er.l"):
+CuSu
(Customer/Supplier),
+Item
(Product Item) and +Ord
(Order).
+Pos
object is a single position in an order.
+Role
and +User
objects are needed for
authentication and authorization.
The classes +Role
and +User
are defined in
"@lib/adm.l". A +Role
has a name, a list of permissions, and a list
of users assigned to this role. A +User
has a name, a password and
a role.
In "app/er.l", the +Role
class is extended to define an
url>
method for it. Any object whose class has such a method is
able to display itself in the GUI. In this case, the file "app/role.l" will be
loaded - with the global variable *ID
pointing to it - whenever an
HTML link to this role object is activated.
The +User
class is also extended. In addition to the login name,
a full name, telephone number and email address is declared. And, of course, the
ubiquitous url>
method.
The application logic is centered around orders. An order has a number, a
date, a customer (an instance of +CuSu
) and a list of positions
(+Pos
objects). The sum>
method calculates the
total amount of this order.
Each position has an +Item
object, a price and a quantity. The
price in the position overrides the default price from the item.
Each item has a number, a description, a supplier (also an instance of
+CuSu
), an inventory count (the number of these items that were
counted at the last inventory taking), and a price. The cnt>
method calculates the current stock of this item as the difference of the
inventory and the sold item counts.
The call to dbs
at the end of "app/er.l" configures the physical
database storage. Each of the supplied lists has a number in its CAR which
determines the block size as (64 << N) of the corresponding database file.
The CDR says that the instances of this class (if the element is a class symbol)
or the tree nodes (if the element is a list of a class symbol and a property
name) are to be placed into that file. This allows for some optimizations in the
database layout.
When you are connected to the application (see Getting Started) you might try to do some "real" work with it. Via the "Data" menu (see Navigation) you can create or modify customers, suppliers, items and orders, and produce simple overviews via the "Report" menu.
Source in "app/cusu.l"
The Customer/Supplier search dialog (choCuSu
in "app/gui.l")
supports a lot of search criteria. These become necessary when the database
contains a large number of customers, and can filter by zip, by phone number
prefixes, and so on.
In addition to the basic layout (see Editing), the form is divided into four separate tabs. Splitting a form into several tabs helps to reduce traffic, with possibly better GUI response. In this case, four tabs are perhaps overkill, but ok for demonstration purposes, and they leave room for extensions.
Be aware that when data were modified in one of the tabs, the "Done" button has to be pressed before another tab is clicked, because tabs are implemented as HTML links (see Buttons vs. Links).
New customers or suppliers will automatically be assigned the next free number. You can enter another number, but an error will result if you try to use an existing number. The "Name" field is mandatory, you need to overwrite the "<Name>" clue.
Phone and fax numbers in the "Contact" tab must be entered in the correct format, depending on the locale (see Telephone Numbers).
The "Memo" tab contains a single text area. It is no problem to use it for large pieces of text, as it gets stored in a database blob internally.
Source in "app/item.l"
Items also have a unique number, and a mandatory "Description" field.
To assign a supplier, click on the "+" button. The Customer/Supplier search dialog will appear, and you can pick the desired supplier with the "@" button in the first column. Alternatively, if you are sure to know the exact spelling of the supplier's name, you can also enter it directly into the text field.
In the search dialog you may also click on a link, for example to inspect a possible supplier, and then return to the search dialog with the browser's back button. The "Edit" mode will then be lost, however, as another object has been visited (this is described in the last part of Editing).
You can enter an inventory count, the number of items currently in stock. The following field will automatically reflect the remaining pieces after some of these items were sold (i.e. referenced in order positions). It cannot be changed manually.
The price should be entered with the decimal separator according to the current locale. It will be formatted with two places after the decimal separator.
The "Memo" is for an arbitrary info text, like in Customer/Supplier above, stored in a database blob.
Finally, a JPEG picture can be stored in a blob for this item. Choose a file with the browser's file select control, and click on the "Install" button. The picture will appear at the bottom of the page, and the "Install" button changes to "Uninstall", allowing the picture's removal.
Source in "app/ord.l"
Oders are identified by number and date.
The number must be unique. It is assigned when the order is created, and cannot be changed for compliance reasons.
The date is initialized to "today" for a newly created order, but may be changed manually. The date format depends on the locale. It is YYYY-MM-DD (ISO) by default, DD.MM.YYYY in the German and YYYY/MM/DD in the Japanese locale. As described in Time & Date, this field allows input shortcuts, e.g. just enter the day to get the full date in the current month.
To assign a customer to this order, click on the "+" button. The Customer/Supplier search dialog will appear, and you can pick the desired customer with the "@" button in the first column (or enter the name directly into the text field), just as described above for Items.
Now enter order the positions: Choose an item with the "+" button. The "Price" field will be preset with the item's default price, you may change it manually. Then enter a quantity, and click a button (typically the "+" button to select the next item, or a scroll button go down in the chart). The form will be automatically recalculated to show the total prices for this position and the whole order.
Instead of the "+" or scroll buttons, as recommended above, you could of course also press the "Done" button to commit changes. This is all right, but has the disadvantage that the button must be pressed a second time (now "Edit") if you want to continue with the entry of more positions.
The "x" button at the right of each position deletes that position without further confirmation. It has to be used with care!
The "^" button is a "bubble" button. It exchanges a row with the row above it. Therefore, it can be used to rearrange all items in a chart, by "bubbling" them to their desired positions.
The "PDF-Print" button generates and displays a PDF document for this order. The browser should be configured to display downloaded PDF documents in an appropriate viewer. The source for the postscript generating method is in "app/lib.l". It produces one or several A4 sized pages, depending on the number of positions.
Sources in "app/inventory.l and "app/sales.l"
The two reports ("Inventory" and "Sales") come up with a few search fields and a "Show" button.
If no search criteria are entered, the "Show" button will produce a listing of the relevant part of the whole database. This may take a long time and cause a heavy load on the browser if the database is large.
So in the normal case, you will limit the domain by stating a range of item numbers, a description pattern, and/or a supplier for the inventory report, or a range of order dates and/or a customer for the sales report. If a value in a range specification is omitted, the range is considered open in that direction.
At the end of each report appears a "CSV" link. It downloads a file with the
TAB-separated values generated by this report.
picolisp-3.1.5.2.orig/doc/db 0000644 0000000 0000000 00000007005 12265263724 014227 0 ustar root root Max DB-Size: 7 digits -> 2**42 (4 Tera) Blocks
Blocksize 64 -> (2**48 Bytes (256 TB))
Tree
NIL -> (val *DB)
{x} -> (val '{x})
(var . {x}) -> (get '{x} 'var)
(var . +Cls) -> (get *DB '+Cls 'var)
(var +Cls . {x}) -> (get '{x} '+Cls 'var)
B-Tree root:
(cnt . node)
B-Tree node:
(less (key more . value) (key more . value) ..)
(less ((key . value) more) ((key . value) more) ..)
Per node
BEG EXTERN <6> .. NIX
6+1+1+6+1 = 15
Per key
BEG TRANSIENT NIL
(gui '(+E/R +TextField) '(nm : home obj) 40 "Name")
(gui '(+ClassField) '(: home obj) '(("Male" +Man) ("Female" +Woman))) )
( 'chart NIL
'((btn) (NIL "Name") (NIL "Father") (NIL "Mother") (NIL "Partner") (NIL "Occupation") (NIL "born"))
(do (cho)
(
NIL (
NIL NIL
'(NIL (NIL "Children") (NIL "born") (NIL "Father") (NIL "Mother"))
(do 4
(
NIL (
NIL (ht:Prin "No birth date for " (: obj nm)))
(gui '(+QueryChart) 12
'(goal
(quote
@Obj (: home obj)
@Dat (: home obj dat)
@Beg (- (: home obj dat) 36525)
@Fin (or (: home obj fin) (+ (: home obj dat) 36525))
(db dat +Person (@Beg . @Fin) @@)
(different @@ @Obj)
(^ @ (>= (get (-> @@) 'fin) (-> @Dat)))
(^ @ (<= (get (-> @@) 'dat) (-> @Fin))) ) )
7
'((This)
(list This (: job) (: dat) (: fin) (: pa) (: ma) (: mate)) ) )
(
NIL (pack (datStr (: obj dat)) " - " (datStr (: obj fin)))
(quote
(NIL "Name") (NIL "Occupation") (NIL "born") (NIL "died")
(NIL "Father") (NIL "Mother") (NIL "Partner") )
(do 12
(
NIL "Family Tree View")
(
NIL
(recur (This)
(when (try 'url> This 1)
(
NIL (mapc recurse (: kids))) ) ) ) ) ) )
### RUN ###
(de main ()
(pool "family/" *Dbs)
(unless (val *DB)
(put>
(set *DB (request '(+Man) 'nm "Adam"))
'mate
(request '(+Woman) 'nm "Eve") )
(commit) ) )
(de go ()
(rollback)
(server 8080 "!person") )
# vi:et:ts=3:sw=3
picolisp-3.1.5.2.orig/doc/family.tgz 0000644 0000000 0000000 00000033505 12265263724 015732 0 ustar root root Q =klye |_{jwRIߋD_"E(-=c$FbI8n8BFZE?
J!:QHGrvޏYrEnFֵ-m\|;bq*T.tbw),[6+Mm5G!V8
%!ؒb&grj+dc-!+,32Nbnh~w0~iϹ:&|;je#ܴ9۪;5\aG`lZ?ئr9F\n0{Pu;Tłޜ3Iٮ4>y8|NObi.Q|%u j)۪E] CTә[VTE\;gb|k0.˕je̓M7zOOj#0ܕ#C$qbr_+)R!;[`}l,H-z7R M-cb*
HV3ܴ0jp-UTMx*,ۇ2;d|2,[kGG#F8.2hO\Sr Ӛob> ]iUbg`,MӨWeZxRC.6jAfpEcȬeZk6'
?F-nnrAqi}N"yAP,<HB:!p0! k!?(`z=Ua XԍMz5C92lm4I(TpL0mdNō .mvMƲ