title: Scheme: Implementing n-argument compose using fold
body: <p>I'm trying to find the "best" implementation of a multi-argument "compose" in Scheme (I know it's a builtin in some implementations, but assume for the moment I am using one that doesn't have this).</p>
  
  <p>For a 2-argument compose function I have this:</p>
  
  <pre><code>(define compose
    (lambda (f g)
      (lambda x
        (f (apply g x)))))
  </code></pre>
  
  <p>This has the advantage that if the right-most function needs additional arguments, these can still be passed through the combined function. This has the pleasing property that composing the identity function on top of something does not change the function.</p>
  
  <p>For example:</p>
  
  <pre><code>(define identity
    (lambda (x) x))
  
  (define list1
    (compose identity list))
  
  (define list2
    (compose identity list1))
  
  (list2 1 2 3)
  &gt; (1 2 3)
  </code></pre>
  
  <p>Now to do an "n-argument" compose I could do this:</p>
  
  <pre><code>(define compose-n
    (lambda args
      (foldr compose identity args)))
  
  ((compose-n car cdr cdr) '(1 2 3))
  &gt; 3
  </code></pre>
  
  <p>But this no longer preserves that nice "identity" property:</p>
  
  <pre><code>((compose-n identity list) 1 2 3)
  &gt; procedure identity: expects 1 argument, given 3: 1 2 3
  </code></pre>
  
  <p>The problem is that "initial" function used for the foldr command. It has built:</p>
  
  <pre><code>(compose identity (compose list identity))
  </code></pre>
  
  <p>So... I'm not sure the best way around this. "foldl" would seem to be the natural better alternative, because I want to it start with "identity" on the <em>left</em> not the <em>right</em>...</p>
  
  <p>But a naive implementation:</p>
  
  <pre><code>(define compose-n
    (lambda args
      (foldl compose identity args)))
  </code></pre>
  
  <p>which works (have to reverse the order of function applications):</p>
  
  <pre><code>((compose-n cdr cdr car) '(1 2 3))
  &gt; 3
  </code></pre>
  
  <p>doesn't solve the problem because now I end up having to put the identity function on the left!</p>
  
  <pre><code>((compose-n cdr cdr car) '(1 2 3))
  &gt; procedure identity: expects 1 argument, given 3: 1 2 3
  </code></pre>
  
  <p>It's like, I need to use "foldr" but need some different "initial" value than the identity function... or a better identity function? Obviously I'm confused here!</p>
  
  <p>I'd like to implement it <em>without</em> having to write an explicit tail-recursive "loop"... it seems there should be an elegant way to do this, I'm just stuck.</p>