【问题标题】:Initialization in Rebol/Red languageRebol/Red 语言初始化
【发布时间】:2017-10-01 04:37:19
【问题描述】:

http://business-programming.com/business_programming.html#section-2.6 上给出的示例中:

REBOL []
items: copy []               ; WHY NOT JUST "items: []"
prices: copy []              ; WHY NOT JUST "prices: []"
append items "Screwdriver"
append prices "1.99"
append items "Hammer"
append prices "4.99"
append items "Wrench"
append prices "5.99"

为什么应该做 items: copy [] 而不是 items: [] ?也应该对所有变量初始化都这样做,还是有一些选择性类型需要这样做?

编辑:我发现以下代码可以正常工作:

REBOL []
items: []   
prices: []  
append items "Screwdriver"
append prices "1.99"
append items "Hammer"
append prices "4.99"
append items "Wrench"
append prices "5.99"

probe items
probe prices

items: []   
prices: []  
append items "Screwdriver"
append prices "1.99"
append items "Hammer"
append prices "4.99"
append items "Wrench"
append prices "5.99"

probe items
probe prices

输出没问题:

["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]

但不关注:

REBOL []

myfn: func [][
    items: []   
    prices: []  
    append items "Screwdriver"
    append prices "1.99"
    append items "Hammer"
    append prices "4.99"
    append items "Wrench"
    append prices "5.99" ]

do myfn
probe items
probe prices

do myfn
probe items
probe prices

输出在此处重复:

["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]
["Screwdriver" "Hammer" "Wrench" "Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99" "1.99" "4.99" "5.99"]

只有在函数中初始化时才会出现问题?

显然,函数中的所有变量默认情况下都被视为全局变量,并且在启动时只创建一次。似乎该语言正在将我的功能转换为:

items: []   
prices: []  
myfn: func [][
    append items "Screwdriver"
    append prices "1.99"
    append items "Hammer"
    append prices "4.99"
    append items "Wrench"
    append prices "5.99" ]

现在多次调用 myfn 的响应是可以理解的。 在循环中创建的全局函数也只创建一次。

【问题讨论】:

  • 如果您通读"Why do functions have memory in Rebol?" 的答案可能会有所帮助,但正如该答案所述,Ren-C 中的新语义不允许您在没有副本的情况下进行追加,因为[]是源中的一个数组,它将被锁定。
  • 阅读链接就很清楚了。有人可以用“可变”和“不可变”来解释这一点吗?或者这在这里不相关吗?
  • 请参阅我上面的编辑问题。
  • 这不是因为在一个函数中,而是因为多次运行同一行代码。您也可以通过循环获得累积行为,例如循环 2 [data: [] append data 'something]。虽然有些人会阅读并认为循环的每次迭代都会通过赋值 data: [] 获得一个新的空块,但只有一个 that 特定块的实例。所以第二次通过循环它将是 R3-Alpha 和 Red 中的 data: [something]。正如我之前所说,我自己的观点(在 Ren-C 中实现)是应该锁定源代码系列以防止修改以避免错误。
  • 解释得很好。

标签: variables initialization rebol red


【解决方案1】:

此脚本中不需要copy [],因为当它再次运行时,之前对系列itemsprices 的所有引用都将重新创建。

但如果items: [] 有可能在同一个脚本中多次运行,那么您需要复制以确保每次都创建一个新系列,而不仅仅是引用现有系列。

【讨论】:

  • 因此,items: [] 不应该是 items 可能被修改的函数的一部分,否则它将影响对该函数的下一次调用。我说的对吗?
猜你喜欢
  • 2016-08-19
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2010-12-14
  • 2022-11-10
  • 1970-01-01
相关资源
最近更新 更多