代码之家  ›  专栏  ›  技术社区  ›  Terrence Brannon

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

red
  •  0
  • Terrence Brannon  · 技术社区  · 6 年前

    鉴于:

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

    我想要一个函数,它接受两个字符串,每个字符串代表石头、布或剪刀中的任何一个,然后返回匹配的元素,忽略动词。

    例子:

    does-player-win "paper" "rock" 应该通过搜索块返回“纸盖着石头”。

    更新 我试着改变结构,使它更容易使用 find select 但显然我的结构是非法的:

    player-wins: [
        ["rock" "scissors"] "breaks"
        ["paper" "rock"] "covers"
        ["scissors" "paper"] "cut"
    ]
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   sqlab    5 年前

    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