Red 语言将串联的字符串元素转换为浮点数

Convert string elements in series to floats in Red language

我想一次性将许多可用作字符串的十进制数转换为浮点数。我正在尝试将这些字符串组合成一个系列然后将它们转换为浮点数的代码。这一切正常,但如果出现错误则失败:

a: "1.5" 
b: ""
c: "3.7"
invars: [a b c]

print a
print type? a

set invars foreach x invars [append [] to-float reduce x]  ; code to convert string series to float series; 

print a
print type? a

错误是:

*** Script Error: cannot MAKE/TO float! from: ""
*** Where: to
*** Stack: to-float 

为了更正错误,我尝试了以下代码:

temp: []
foreach x invars [
    y: copy ""
    either error? [set [y] to-float reduce x]
        [append temp reduce x]         ; put original value if not convertable
        [append temp reduce y]  ]
print temp 
set invars temp
print a 
print type? a

但这也行不通。问题出在哪里,如何解决?

forall invars [invars/1:  load get invars/1]
>> invars
== [1.5 [] 3.7]

如果你想去掉空块

>> replace/all invars block! 0
== [1.5 0 3.7]

如果你真的想在 (:less:) 步骤中完成所有操作

forall invars [invars/1: either empty? invars/1: get invars/1 [0.0] [load invars/1]]

之后您可以再次设置您的变量。

但是如果你只想设置你的变量,你必须这样做

foreach x invars [set :x load get x]

与浮动

 foreach x invars [either empty? get x [set :x 0] [set :x to-float get x]]

最后是带有 to-float

的全错误安全版本
foreach x invars [attempt [set :x to-float get x]]
== 3.7
>> a
== 1.5
>> b
== ""
>> c
== 3.7