【问题标题】:How to pass functions as parameters in REBOL如何在 REBOL 中将函数作为参数传递
【发布时间】:2014-06-11 23:36:32
【问题描述】:

我尝试在 REBOL 编程语言中将函数作为参数传递,但我还没有弄清楚正确的语法:

doSomething: func [a b] [
    a b
    a b
]

doSomething print "hello" {This should pass print as the first argument and "hello" as the second argument.}

这会产生错误,因为 print 函数被调用而不是被传递:

hello
*** ERROR
** Script error: doSomething does not allow unset! for its a argument
** Where: try do either either either -apply-
** Near: try load/all join %/users/try-REBOL/data/ system/script/args...

是否可以将print 函数作为参数传递而不是调用print 函数?

【问题讨论】:

    标签: rebol


    【解决方案1】:

    我找到了解决方案:我只需要在作为参数传递的函数名称前添加:

    这里,:print 函数作为参数传递,而不是以“hello”作为参数调用:

    doSomething: func [a b] [
        a b
        a b
    ]
    
    doSomething :print "hello" {This should pass print as the first argument and "hello" as the second argument.}
    

    【讨论】:

      【解决方案2】:

      您已经发现,根据系统的性质,当解释器遇到一个 WORD 时!已绑定到函数的符号类型,默认会调用该函数。看到 GET-WORD 的默认解释器!另一方面,符号类型禁止调用,只返回单词绑定的值。

      求值器逻辑实际上是相当简单的,当它看到某种符号类型时它会如何反应。另一种抑制调用的方法是单引号,它会给你一个 LIT-WORD!符号...但是这些被评估为相应的单词!当它看到它们时:

      >> some-word: 'print
      >> type? some-word
      == word!
      

      其实就是一个GET-WORD的行为!当求值者看到时就相当于用一个WORD的GET函数了!

      doSomething: func [a b] [
          a b
          a b
      ]
      
      doSomething get 'print "hello" {Message}
      

      解释器看到 LIT-WORD! 'print 并将其评估为 WORD!对于print,然后将其传递给GET,它会为您提供一个功能!返回。

      解释器逻辑的简单性是您得到以下内容的原因:

      >> a: b: c: 10 print [a b c]
      10 10 10
      

      由于它处理 SET-WORD 的性质!符号后跟完整的表达式。这也会产生以下代码,打印出 20:

      if 10 < a: 20 [
         print a
      ]
      

      其他语言通过专门的构造(如多重初始化等)实现此类功能,但 Rebol 的逻辑更简单。

      只是想详细说明一下以帮助解释您正在查看的内容。我对另一个问题的回答可能会提供对边缘案例、历史和未来的更多见解:"When I use error? and try, err need a value"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-29
        • 1970-01-01
        • 2020-02-10
        • 2013-06-03
        • 2015-01-20
        • 2016-10-27
        相关资源
        最近更新 更多