这是迭代一组值的规范方法吗?

时间:2018-06-06 12:39:57

标签: iterator rust

我有一个具有可枚举值集的类型:

def get_current_score(self, i, j, char, leng):
    # leng = 0 <- don't
    self.viz[i][j] = True  # you set it twice, let's keep that one

    def test_cell(a, b):  # keep it DRY
        return self.out_of_span(a, b) == False \
               and self.viz[a][b] == False \
               and self.matrix[a][b] == char

    cells = [(i - 1, j), (i - 1, j + 1), (i - 1, j - 1), (i, j - 1),
             (i, j + 1), (i + 1, j), (i + 1, j - 1), (i + 1, j + 1)]
    for a, b in cells:
        if test_cell(a, b): 
            # you don't need to set that cell to true since that's the 
            # first thing you do in the function
            # self.viz[a][b] = True
            return leng + self.get_current_score(a, b, char, leng)

    return 1 + leng

def add(self, index):
    [...]
    # scor
    print('\n --------------\n')
    for i in range(self.maxh, self.nr):
        for j in range(self.span[0], self.span[1]+1):
                if(self.player1 == False and self.matrix[i][j] == 'X'):
                    # no need to send self.viz here. same for score2
                    # if you need to set self.score1 to 0 do it here. not in the recursion
                    self.score1 = max(self.score1, self.get_current_score(i, j, 'X', self.score1))
                    self.viz[i][j] = True
                    #self.score1 -= 1
                else:
                    if(self.player1 == True and self.matrix[i][j] == 'O'):
                        self.score2 = max(self.score2, self.get_current_score(i, j, 'O', self.score1))
                        self.viz[i][j] = True
    self.reset_viz()
    self.print_matrix()

我可以在一组值上定义一个迭代器:

struct MyType(u32);

这真的是规范的做法吗?如果我们有几个自然顺序(比如在lex / colex顺序中迭代排列或组合)会怎样?

1 个答案:

答案 0 :(得分:8)

  

如果我们有几个自然顺序(比如在lex / colex顺序中迭代排列或组合)会怎样?

为不同的迭代顺序实现不同的迭代器类型。您可以使用MyTypeIterMyTypePermutationIter等多种迭代器类型代替MyTypeCombinationIter

标准库在很多地方采用这种方法。以字符串切片类型str为例。您可以自然地迭代字符串的字节,UTF-8字符或线条(仅举几个例子)。为此,str公开了不同的方法: