Как увеличить элемент блока после найденного элемента? - PullRequest
0 голосов
/ 20 января 2019

Дано player-choices: ["rock" 0 "paper" 0 "scissors" 0]

Как я могу увеличить значение после "paper" в этом блоке, выполнив поиск "paper"?

Ответы [ 3 ]

0 голосов
/ 20 января 2019

Вы также можете сохранить ссылку на позиции значений в блоке, чтобы изменить их позже:

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]
0 голосов
/ 23 января 2019

Также учтите, что вам может не понадобиться использовать строки в вашем блоке данных.

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
0 голосов
/ 20 января 2019
>> player-choices/("paper"): player-choices/("paper") + 1
== 1
...