为什么每个在单词定义中的行为不同

  • 本文关键字:定义 单词 each factor-lang
  • 更新时间 :
  • 英文 :


要为数组中的each做一个引号:

(scratchpad) { "3.1415" "4" } [ string>number ] each
3.1415 
4

要在单词中执行此操作:

(scratchpad) : conveach ( x -- y z ) [ string>number ] each ;
(scratchpad) { "3.1415" "4" } conveach .

但这会引发一个错误:

The word conveach cannot be executed because it failed to compile
The input quotation to “each” doesn't match its expected effect
Input             Expected         Got
[ string>number ] ( ... x -- ... ) ( x -- x )

我做错了什么?

Factor 要求所有单词都具有已知的堆栈效果。编译器想知道单词从堆栈中吃了多少项,以及它放回了多少项。在侦听器中,您键入的代码没有该限制。

{ "3.1415" "4" } [ string>number ] each

不从堆栈中取出任何项目,但将两个项目放在那里。堆栈效应将表示为 ( -- x y )

[ string>number ] each 

另一方面,此代码接受一个项目,但将 0 到多个项目放回堆栈中。该数字取决于每个序列的长度。

! ( x -- x y z w )
{ "3" "4" "5" "6" } [ string>number ] each
! ( x -- )
{ } [ string>number ] each 
! ( x -- x )
{ "2" } [ string>number ] each 

您可能希望改用map单词,这会将您的序列从包含字符串的序列转换为包含数字的序列。喜欢这个:

: convseq ( strings -- numbers ) [ string>number ] map ;
IN: scratchpad { "3" "4" } convseq .
{ 3 4 }

最新更新