Saturday, February 14, 2009

The Zen of Jess 2009: Part II

by Jason Morris

In Part I, we said that for many new Jess users, declarative programming will be a completely alien paradigm that warrants a careful and thoughtful study before attempting to write serious code. The following steps are a practical checklist that will greatly facilitate your Jess study.

1. Get the latest Jess code.
Go to http://www.jessrules.com/jess/ and install the latest binary version of Jess (jess.jar) or the whole JessDE if you're using Eclipse. Updating old versions will help you avoid fixed bugs incompatibility issues. Jess runs very well on the latest Ganymede (3.4.x) releases of Eclipse.

If you pose a question on the Jess list server and you’re running an old version, the very first thing you will be asked to do is update your code. Don’t expect that code that you wrote on an ancient version of Jess will run with the latest version, although we will certainly help you try to migrate if we can.

NOTE: I wouldn’t use anything else but the JessDE for my Jess development. Editors like JessWin were developed by a third-party and are not supported by the Jess team.



2. Study the online documentation.
You'll want to keep a link to http://www.jessrules.com/jess/docs/71/table_of_contents.html as your current background reference on Jess. The Jess manual still provides the single best overview of how Jess functionality is structured. Dr. Friedman-Hill is dedicated to keeping this document up-to-date and full of relevant examples. This is a manual, not a textbook, so there is no fluff or extraneous filler.

The current table of contents has 22 chapters:
  • Chapters 1 through 11 are essential reading.
  • Chapters 12 through 15 are advanced topics that you can visit once you have mastered the basics.
  • Chapters 16 through 18 are essential reference links that you will need at all times. Chapters 19 through 22 are various appendices.

One unfortunate thing about the online HTML docs is that they are not searchable. So, I would also keep a link to the PDF version, too http://www.jessrules.com/jess/docs/Jess71p2.pdf

The HTML docs really need a better index. Perhaps I can whip up a Microsoft Compiled Help File (*.chm) for the Jess docs? How about a Java help version, too?



3. Create reference shortcuts on your desktop.
I recommend making desktop shortcuts to the following pages:

http://www.jessrules.com/jess/docs/70/function_index.html
http://www.jessrules.com/jess/docs/71/constructs.html#
http://www.jessrules.com/jess/docs/71/api.html#

4. Purchase a copy of Jess In Action (JIA).
JIA http://www.manning.com/friedman-hill by Jess's author, Dr. E. Friedman-Hill, will be your main tutorial and primer on how to program in Jess. Its ISBIN code is 1930110898. Mine is "dog-eared" and annotated already from use – I honestly don’t know what is holding it together anymore. Eat, sleep, and breathe chapters 1 through 7 – know them like a Marine knows his rifle. Try everything at the Jess command line using the Jess language first.

I recommend not trying to program the Jess API directly until you do this step.

Why? Because you will learn the value of what should be done using the Jess language versus using the Jess API this way.

You can see my full Amazon review at
http://www.amazon.com/exec/obidos/tg/detail/-/1930110898/

5. Work the JIA tutorials.
Now, once you have a grasp of the Jess language, try the tutorials in JIA (chapters 8 and beyond), and type the code samples into Jess so that you can see how they work. Experimental learning is the key with Jess – take advantage of the fact the Jess language is interpreted to get that immediate feedback. It's very gratifying to write a little code snippet that gives you insight into a larger example.

Some variations on the what if? theme that worked for me:
  • Writing many, small deffunctions that print something or calculate something.
    This is a great way to practice using Jess's variables and list-based syntax. Practice taking apart and creating lists and multifields. Remember that lists don't just hold primitives, they can hold object references as well.
  • Changing the behavior of a JIA snippet.
    If an example writes output to the console, change it to write to a file. If a defquery looks for all (foo (color ?c)) facts, make it look for all (foo (color blue)) facts, or any non-blue foo facts (foo (color ~blue)).
  • Experiment with LHS patterns.
    Get a little fact-base built with some simple rules and modify the rule LHS patterns a bit after each run. Try all the different pattern constraints (this takes time, but pays huge dividends later). Avoid the performance traps of bad pattern ordering on your LHS of rules.
6. Participate on the Jess Mailing List and Jess Wiki
Bar none, the atmosphere at the Jess list server is one of the friendliest and most supportive on the internet. New Jess users do not have to fear the condescending replies and otherwise inappropriate remarks that mar so many other IT forums and email lists.


Jess List Server Etiquette

1. Read the documentation.
Make sure that you have read the Jess documentation most relevant to your question before you post your question. By doing this, you help eliminate the most likely problems and increase the likelihood of finding a solution on your own which is always very satisfying.

2. Be specific.
When you ask a question about the behavior of some code, give the actual code snippet that is causing the problem, not just a word description of it.

3. Explain your purpose.
Tell us what you are trying to do or what result you want to have. Very often, we can suggest a better or more correct way than what you have already coded.

You can join the mailing list at:
http://www.jessrules.com/jess/mailing_list.shtml
or participate on the Jess Wiki at:
http://www.jessrules.com/jesswiki/view


As for posting on the list server, don't be afraid to ask questions, but do try to exhaust the obvious causes of errors before posting -- you learn more that way. I strongly encourage you to try to replace all questions of the form How do I...?, How can I…? with a simple experimental code snippet.

Here's an example: Instead of asking "How do I make Jess switch from one module to the next?", I'd first read a bit about using (focus), then I'd write a little test like

;; test_focus.clp
(clear)
;; Using a fact as a trigger is perfectly acceptable
(deftemplate MAIN::switch-to (slot module-name))
;; Make a rule that looks for this pattern
(defrule MAIN::switch-module
(MAIN::switch-to (module-name ?name))
=>
;; Show me what's happening
(watch all)
;; Hypothesize here... what do you think will happen?
(focus ?name))
;; Need a place to switch to!
(defmodule FOO)
;; A friendly confirmation that we made it OK
(defrule FOO::executing-in-foo
=>
(printout t "Switched to module FOO!" crlf))
(reset)
(assert (switch-to (module-name FOO)))
(run)

... and Jess will print out

<== Focus MAIN
==> Focus FOO
FIRE 2 FOO::executing-in-foo f-0
Switched to module FOO!
<== Focus FOO ==> Focus MAIN
<== Focus MAIN 2
Jess>

Experimenting like this is very serendipitous. One thing that you might notice is that focus returned to the MAIN module automatically when no further rules in the FOO module were activated. You can imagine that doing many, many little such exercises will really boost your Jess understanding. Eventually, when you move beyond trivial examples to real applications, you'll have a whole toolbox of techniques with which to construct your Jess code.

So, when I'm faced with a tough bug, I ask myself, "Ok...what's Ernest going tell me?", and I dig deeper and usually find the answer on my own. Infinitely more satisfying and more educational! If you do discover a useful approach or novel technique, by all means, share it on the Jess Wiki!



7. Keep a programmer's journal.
As you experiment and construct your own Jess knowledge, you will accumulate your own tips, tricks, and best-practices. Veteran programmers do this religiously. I continue to have many little epiphanies as I create course content, program my own applications, and study new materials, and you'll want to record your thoughts and discoveries, too. Again, if you can share your learning experiences on the Jess Wiki, that would be great!

8. Review some LISP and some CLIPS.
Learning LISP is to learning CLIPS and Jess what learning Latin is to learning English -- it will give you a better sense of where certain concepts originated and help you with the list-based syntax.

CLIPS is the inspiration for Jess, and Jess owes a good deal of its syntax to CLIPS. Therefore, much (but not all) of what you see in CLIPS is similar to Jess.

Expert Systems: Principles and Programming 4th Ed, by Giarratano & Riley, is a good companion volume to JIA for reviewing CLIPS syntax, and it will reinforce your study of Jess. For Common LISP, there is the very good and FREE online reference http://www.gigamonkeys.com/book/

All of these techniques are helpful, but in order to really put them into practice, you have to first study what tools like Jess are meant to do.

We’ll tackle this in Part III. - JM

Sunday, February 08, 2009

The Zen of Jess 2009: Part I
by Jason Morris

Jess and the Art of (Safe) Rule-Based Computing

I’ve noted that new Jess users are highly susceptible to the viral coding malady, scribo precoxium (SP), roughly translated from Latin as “to write prematurely”. Most poor souls who contract scribo precoxium come from relatively weak Java backgrounds. Their bookshelves are devoid of the names Giarratano, Riley, Russell, Norvig, and Jackson, though the sharing of books with the phrases “head-first” or “in a nutshell” seems to be higher among the population of scribo precoxium sufferers. The typical progression finds casual coders hanging out in unmoderated forums leading to libri indifferens, or an indifference to reading reference material. Longer exposure gives way to outright Documentational Disaffective Disorder. In no time, victims are attempting complicated Jess applications without first doing any homework, and once they start writing a little code, the urge to continue cannot be controlled. Soon, they are left exasperated, due dates looming, with piles of uncompilable source. First responders on the scene often report victims face down in puddle of Mountain Dew, comatose from trying to ease their pain by mainlining a snowball of Jess and Drools.

Professionals are less susceptible than academics to SP, though even the most seasoned veteran of many product cycles has been known to contract it. As trained help providers, we on the Jess list server are keen to spot the warning signs. Typical symptoms of SP include severe external pleading such as, “Help me please!” and “I can’t get this to run!”. Often, there is an additional appeal for assistance by a certain date such as, “I need to make this work by tomorrow!!” or something similar.



What can be done?

Fortunately, there is a time-tested treatment for combating scribo precoxium: RTFD. When given intra-occularly, RTFD has been proven in the vast majority of cases to eliminate the symptoms of SP overnight. Small doses of RTFD, taken daily, can prevent the reoccurrence of scribo precoxium. Left untreated, SP can metastize into full-blown molestus neophytus which can impair your hearing, judgment, and ability to take sound programming advice of any kind. In the most serious cases, patients are have been known to develop an owen-oma, an ulcerated rip midway between their eyes and halfway up their forehead.

So, don’t hesitate to write Dr. Friedman-Hill if you need your RTFD prescription refilled.

A New Beginning

All kidding aside, in the five years since I first wrote The Zen of Jess, Jess has acquired a significant body of questions and answers on the Jess email list. Most of these answers come from Dr. Friedman-Hill himself, and though I originally opined that he must be frustrated in having to answer questions that he has taken great pains to answer elsewhere, one would never know it for the effort that he makes ensuring that every question, however “noobious”, is answered. It has occurred to me that despite all the warnings, admonitions, and evidence to the contrary, there are those for whom the cart must come before the horse. So, in keeping with our great Madame Speaker’s penchant for prevention of communicable diseases such as scribo precoxium, I shall advocate a policy of Prophylactic Programming.

Lest you contract SP, keep in mind that using Jess is not so simple as including another JAR in your application. Jess is in many ways a meta-tool, that is a tool for building tools – in my case rule-based expert systems. For many new Jess users, declarative programming will be a completely alien paradigm that warrants a careful and thoughtful study before attempting to write serious code.

We'll delve into what that entails in Part II. - JM