(続)Gaucheで「カブらない数字を4桁だすの」をやる
util.combinationsを教えてもらったので富豪で再チャレンジ。
http://practical-scheme.net/gauche/man/gauche-refj_158.html#SEC430
何故かわからないが順列という名であるのにnPrでr=nのときしか用意されていない。
>> (permutations '(1 2 3)) => ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)) >> (permutations '(1 2 3) 2) *** ERROR: wrong number of arguments for #<closure permutations> (required 1, got 2) Stack Trace: _______________________________________
しょうがないので組合せと組み合わせることにした
>> (map (lambda (x) (permutations x)) (combinations (iota 4) 2)) => (((0 1) (1 0)) ((0 2) (2 0)) ((0 3) (3 0)) ((1 2) (2 1)) ((1 3) (3 1)) ((2 3) (3 2)))
ここまで言った段階でschemeにはflatten(リストの平坦化)がないとおもってがっくりした。(rubyに毒されすぎだ)
よくよく考えると繰り返し構造ならreduceというかfoldで対応できることに気がついて書き直したのが以下。
>> (use srfi-27) => #<undef> >> (use util.combinations) => #<undef> >> (let ((a (fold (lambda (x y) (append (permutations x) y)) () (combinations (iota 9) 4)))) (list-ref a (random-integer (length a)))) => (5 3 1 2)
順列がきちんと実装されているならかなりの富豪で着陸できるのでいいのかも。
>> (let ((a (permutations (iota 9) 4))) (list-ref a (random-integer (length a))))
と、なってほしいものだ。