如何在Forth中输入数字 [英] How to enter numbers in Forth
问题描述
在Basic中是否有诸如Basic中的input
或C中的scanf("%d")
之类的东西?
Is there something like input
in Basic or scanf("%d")
in C in Forth?
可能是这样的:
200 buffer: buf
: input ( -- n ) buf 200 accept
some-magic-filter
buf swap evaluate ;
上述代码中的问题是如何定义仅传递数字而不传递任何单词,定义等的过滤器?
The problem in the above code, is how to define a filter that will pass only numbers, but not any words, definitions, etc?
推荐答案
The standard specifies only a low level >NUMBER
word to interpret integer numbers.
OTOH using EVALUATE
to convert strings into numbers is a quick and dirty way. Either use it without checks (in the case of trusted input) or do not use it at all. Trying to filter the string before EVALUATE
is a bad idea: it has cost of >NUMBER
word itself and low reusing factor.
NB :>NUMBER
和EVALUATE
均未检测到数字溢出.
NB: neither >NUMBER
nor EVALUATE
detects numeric overflow.
在任何情况下,您输入单单元整数的单词都可以定义如下:
In any case, your word to input a single-cell integer can be defined something like:
: accept-number ( -- n )
PAD DUP 80 ACCEPT ( addr u ) StoN ( n )
;
对于受信任的输入,您可以像这样定义StoN
In the case of trusted input you can define StoN
like
: StoN ( addr u -- x )
STATE @ ABORT" This naive StoN should not be used in compilation state"
DEPTH 2- >R
EVALUATE
DEPTH 1- R> <> IF -24 THROW THEN
\ check depth to accept the single-cell numbers only
;
否则(在输入不受信任的情况下),您有两种选择:依靠特定Forth系统的特定单词或使用某些(也许是您自己的)库.
Otherwise (in the case of untrusted input) you have two choices: to rely on the specific words of a particular Forth system or to use some (perhaps your own) library.
我使用以下词典来定义StoN
:
I use the following lexicon to define StoN
:
\ ---
\ The words from Substring Matching library
\ (where length is counted in address units)
: MATCH-HEAD ( a u a-key u-key -- a-right u-right true | a u false )
2 PICK OVER U< IF 2DROP FALSE EXIT THEN
DUP >R
3 PICK R@ COMPARE IF RDROP FALSE EXIT THEN
SWAP R@ + SWAP R> - TRUE
;
\ ---
\ The words from Literals interpreting library
\ (where prefix 'I-' is shortcut for Interpret)
: I-DLIT ( a u -- x x true | a u false )
2DUP S" -" MATCH-HEAD >R
DUP 0= IF NIP RDROP EXIT THEN
0 0 2SWAP >NUMBER NIP IF RDROP 2DROP FALSE EXIT THEN
R> IF DNEGATE THEN 2SWAP 2DROP TRUE
;
: I-LIT ( a u -- x true | a u false )
I-DLIT IF D>S TRUE EXIT THEN FALSE
;
之后,可以将StoN
定义为:
: StoN ( a u -- x ) I-LIT IF EXIT THEN -24 THROW ;
提到的库可以在GitHub上找到:
The mentioned libraries can be found at GitHub:
- Substring matching functions library
- Resolvers example (for various lexemes)
这篇关于如何在Forth中输入数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!