简体   繁体   English

Ruby注入怪异行为

[英]Ruby Inject Weird Behavior

I'm trying to produce the full permutation of a given array. 我正在尝试产生给定数组的完整排列。 For example, if the input is fact(2, ['A', 'B']) , the output should be [["A", "A"], ["B", "A"], ["A", "B"], ["B", "B"]] . 例如,如果输入为fact(2, ['A', 'B']) ,则输出应为[["A", "A"], ["B", "A"], ["A", "B"], ["B", "B"]]

def fact(n, arr)
    return [[]] if n == 0
    nxt = fact(n - 1, arr).freeze
    arr.inject([]){ |result, elem| nxt.each { |x| result.push(x + [elem]); result } }
end

However when I'm trying to do this using a 'more functional programming' way, something weird happened. 但是,当我尝试使用“更多功能的编程”方式执行此操作时,发生了一些奇怪的事情。 The interpreter complains Untitled 4.rb:4:in 'push': can't modify frozen Array (RuntimeError) . 解释器抱怨Untitled 4.rb:4:in 'push': can't modify frozen Array (RuntimeError) I'm actually trying to modify the injected array named result , how could it change nxt ? 我实际上是在尝试修改名为result的注入数组,它将如何更改nxt

It's built in, and it is lazy: 它是内置的,很懒:

perms = ['A', 'B'].repeated_permutation(2)
#use the resulting enumerator like this:
perms.each{|perm| p perm}

Turn out to be a typo. 原来是一个错字。

def fact(n, arr)
    return [[]] if n == 0
    nxt = fact(n - 1, arr).freeze
    arr.inject([]){ |a, elem| nxt.each { |x| a.push(x + [elem]) }; a }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM