コンビネーション

今日の一行 (お題) flips
(↑ぐお!はてな記法だとリンクに[]が使えない!) をみて、なんか出来そうだなーと思ったけど、無理だった。はじめ、組み合わせを数え上げればいいのだと思って、

(use srfi-1)

(define (reverse-append s1 s2)
  (if (null? s1)
      s2
      (reverse-append (cdr s1) (cons (car s1) s2))))

(define (combination-insert x s)
  (let loop ((c ()) (p ()) (s s))
    (if (null? s)
        (cons (reverse-append p (list x)) c)
        (loop (cons (reverse-append p (cons x s)) c) (cons (car s) p) (cdr s)))))

(define (combination s)
  (if (null? s)
      (list s)
      (append-map (lambda (x) (combination-insert (car s) x)) (combination (cdr s)))))

こういうのを書いたのですが、関数を生成するんだから、

((flips 2) f) ; => ((lambda (x y) (f x y)) (lambda (x y) (f y x)))

となる flips が要るわけで、えーと……引数リストの組み合わせを数え上げて、'(lambda (x y) (apply f (list x y))) みたいな奴を作って eval すればいいのかな?

どうみてももっと単純でまっとうなやり方があるだろうという感じ。