Translating function for finding all partitions of a set from Python to Ruby

前端 未结 2 1379
死守一世寂寞
死守一世寂寞 2020-12-11 18:09

I have the following python function to recursively find all partitions of a set:

def partitions(set_):
    if not set_:
        yield []
        return
             


        
2条回答
  •  臣服心动
    2020-12-11 19:01

    You'll have to think of Ruby's yield like a call to a user-defined operation.

    def twice
        yield
        yield
    end
    
    twice { puts "Hello" } 
    

    So whenever your code yields a value, a processing function for this element will be called.

    partitions([1, 2, 3, 4].to_set) { |result| 
        # process result
    }
    

    This code doesn't generate a list at all.

提交回复
热议问题