skip to main content

kiesler.at

Boundary Checks with gforth
updated by rck, 2004-05-21

Forth is a fascinating language. I've been hunting a bug in definition of mere 5 words for quite some weeks now. Now that I know, why things are the way the are, it seems quite trivial. I'm documenting the definition of check-range ( u lower-bound upper-bound -- ), while I still know about it.

Checking Bounds in Forth

Forth is a little different, compared with the usual suspects that are JAVA, C, Shellscripts and even PHP. It's stack-oriented!

The code for simple bounds-checking:

: check-range ( u lower upper -- )
  within ;

That's it!

It would be called like 1 0 2 check-range and return -1, if in bounds, 0 otherwise.

Exceptions in Forth

Exceptions in Forth are a purist's dream. if you call 'throw' with 0 on top of stack, nothing happens. if you call it with a number, an exception is thrown.

my exception would be -24: invalid numeric argument, if out of bounds.

in code: -24 throw

Checking Bounds in Forth with Exceptions

So, now we need to combine those two ideas of bounds checking and exceptions. it's kind of very easy!

the magic behind it happens via the and-instruction. but let's have a look at the definition first:

: check-range ( u lower upper -- )
  within 0= -24 and throw ;

We know about the within, we know the throw part. But what about the rest?

0= 'inverts' a logical value on the stack. if the value is 0, it's replaced by -1. if it isn't, it's replaced by 0.

Now, remember the and-instruction. -1 has all bits set, thus something and -1 is something. 0 has no bit set, thus something and 0 is 0.

Put together: if(in bounds) throw(0) else throw (-24);

Preface
Checking Bounds in Forth
The big BUT



RSSComments - Make a comment
The comments are owned by the poster. We are not responsible for its content.
RSSAll Articles
2008, 2007, 2006, 2005, 2004

What's Related

Link Manager

Forth

Article Manager

Forth

FAQ

Forth

Latest Updates

AdministrativeTexts
updated by freddiemac1993, 2013-06-14
wiki

Re: adventures
created by brittdavis10, 2012-02-23 (1 rply, 3 views)
thread

Re: how to run phpwebsite...
created by alexander, 2011-08-25 (2 rpls, 3607 views)
thread

Re: Forum tags
created by HaroldFaragher, 2011-08-22 (3 rpls, 8488 views)
thread


Zu den KO2100 Foren