Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Q: I have a complex expression inside a loop...

JavaFAQ Home » Java IAQ by Peter Norvig Go to all tips in Java IAQ by Peter Norvig


Bookmark and Share

Q: I have a complex expression inside a loop. For efficiency, I'd like the computation to be done only once. But for readability, I want it to stay inside the loop where it is used. What can I do?

Answer: Let's assume an example where match is a regular expression pattern match routine, and compile compiles a string into a finite state machine that can be used by match:

for(;Wink {
  ...
  String str = ...
  match(str, compile("a*b*c*"));
  ...
}

Since Java has no macros, and little control over time of execution, your choices are limited here. One possibility, although not very pretty, is to use an inner interface with a variable initializer:

for(;Wink {
  ...
  String str = ...
  interface P1 {FSA f = compile("a*b*c*);}
  match(str, P1.f);
  ...
}

The value for P1.f gets initialized on the first use of P1, and is not changed, since variables in interfaces are implicitly static final. If you don't like that, you can switch to a language that gives you better control. In Common Lisp, the character sequence #. means to evaluate the following expression at read (compile) time, not run time. So you could write:

(loop
  ...
  (match str #.(compile "a*b*c*"))
  ...)


This tip is reprinted on JavaFAQ.nu by by courtesy of Peter Norvig I am thankful for his important contributions to my site - 21 Infrequently Answered Java Questions. Alexandre Patchine


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy