找到元素后如何增加块元素?

时间:2019-01-20 01:59:36

标签: red

给出player-choices: ["rock" 0 "paper" 0 "scissors" 0]

如何通过搜索"paper"在此块中"paper"之后增加值?

4 个答案:

答案 0 :(得分:3)

>> player-choices/("paper"): player-choices/("paper") + 1
== 1

答案 1 :(得分:1)

您还可以保留引用值在块中的位置,以便以后更改它们:

player-choices: ["rock" 0 "paper" 0 "scissors" 0]
rock-pos: find/tail player-choices "rock"
paper-pos: find/tail player-choices "paper"
scissors-pos: find/tail player-choices "scissors"

change paper-pos 1 + paper-pos/1
player-choices
; == ["rock" 0 "paper" 1 "scissors" 0]

答案 2 :(得分:1)

还要考虑,您可能不需要在数据块中使用字符串。

player-choices: [rock 0 paper 0 scissors 0]
player-choices/paper: player-choices/paper + 1

您还可以编写一个通用的incr函数,如下所示:

incr: function [
    "Increments a value or series index"
    value [scalar! series! any-word! any-path!] "If value is a word, it will refer to the incremented value"
    /by "Change by this amount"
        amount [scalar!]
][
    amount: any [amount 1]

    if integer? value [return add value amount]         ;-- This speeds up our most common case by 4.5x
                                                        ;   though we are still 5x slower than just adding 
                                                        ;   1 to an int directly and doing nothing else.

    ; All this just to be smart about incrementing percents.
    ; The question is whether we want to do this, so the default 'incr
    ; call seems arguably nicer. But if we don't do this it is at 
    ; least easy to explain.
    if all [
        integer? amount
        1 = absolute amount
        any [percent? value  percent? attempt [get value]]
    ][amount: to percent! (1% * sign? amount)]          ;-- % * int == float, so we cast.

    case [
        scalar? value [add value amount]
        any [
            any-word? value
            any-path? value                             ;!! Check any-path before series.
        ][
            op: either series? get value [:skip][:add]
            set value op get value amount
            :value                                      ;-- Return the word for chaining calls.
        ]
        series? value [skip value amount]               ;!! Check series after any-path.
    ]
]

然后做

incr 'player-choices/paper

答案 3 :(得分:0)

  

给玩家选择:[“摇滚” 0“纸” 0“剪刀” 0]   如何通过搜索“纸张”在此块中“纸张”之后增加值?

poke player-choices index? next find player-choices "paper" 1 + select player-choices "paper"

细分:

>> ? poke
USAGE:
     POKE series index value

DESCRIPTION: 
     Replaces the series value at a given index, and returns the new value. 
  1. 系列赛选手选择。
  2. 索引是“纸”后值在玩家选择中的位置
  3. 该值等于纸张添加到1后的当前值

查找将返回找到值的序列或无。

>> find player-choices "paper"
== ["paper" 0 "scissors" 0]    

但是,您需要下一个值的索引:

>> index? next find player-choices "paper"
== 4

Select将在找到序列之前的值时返回该序列的下一个值。否则它将不返回任何内容。

>> select pc "paper"
== 0

但是我们想将其增加一,因此

>> 1 + select pc "paper"
== 1