在Red中,如何在块中搜索与模式匹配的字符串?

时间:2019-01-20 02:45:19

标签: red

给出:

player-wins: [
    "rock breaks scissors"
    "paper covers rock"
    "scissors cut paper"
    ]

我想要一个函数,该函数接受两个字符串,每个字符串代表岩石,纸张或剪刀,然后返回匹配的元素,而忽略动词。

示例:

does-player-win "paper" "rock"应该通过搜索该图块来返回“岩石覆盖物”。

更新我试图更改结构以使其易于使用findselect,但显然我的结构是非法的:

player-wins: [
    ["rock" "scissors"] "breaks"
    ["paper" "rock"] "covers"
    ["scissors" "paper"] "cut"
]

1 个答案:

答案 0 :(得分:0)

我差点忘了最简单的解决方案

player-wins: [
    "rock"  "breaks" "scissors"
    "paper" "covers"" rock" 
    "scissors" "cuts"  "paper"
]

game: func [player1 player2]  [
    foreach [subject predicate object] player-wins [
        all [
            player1 = subject
            player2 = object
            return reduce [player1 predicate player2]
        ]
    ]
]

>> print game "rock" "scissors"
rock breaks scissors
>> print game "scissors" "paper"
scissors cut paper

但您的第二个结构也适合

player-wins: [
    ["rock" "scissors"] "breaks"
    ["paper" "rock"] "covers"
    ["scissors" "paper"] "cut"
]

win: function [player1 player2] [
    game: reduce [player1 player2]
    winning: player-wins/(game)
    print [player1 winning player2]
]


>> win "paper" "rock" 
paper covers rock

或简称

win: func [player1 player2] [
    print [player1 select/only player-wins reduce [player1 player2] player2]
]

与版本无关的优化版本可能像这样

player-wins: [
    "rock" "breaks" 
    "scissors" "cuts" 
    "paper" "covers" 
    "rock" "is covered by" 
    "paper" "is cut by" 
    "scissors" "will be broken by" "rock" 
]

game: func [player1 player2] [
    parse player-wins [
        collect [some [keep [player1 skip player2] | 2 skip]    ]   
    ]
 ]

 >> print game "scissors" "rock"
 scissors will be broken by rock
 >> print game "rock" "scissors"
 rock breaks scissors