Search code examples
functionrecursionschemelispcomposition

Combining two functions in Scheme


I have the filter-function and the reverse-function done out in my own code

(define reverse_
  (lambda (xs)
    (if (null? xs)
        xs
        (append (reverse_ (cdr xs))
                (list (car xs))))))

and

(define filter_
  (lambda (p? xs)
    (if (null? xs)
        xs
        (append (if (p? (car xs))
                    (list (car xs))
                    (list))
                (filter_ p? (cdr xs))))))

I want to combine the two functions into the (reverse-filter) function i.e you could type (reverse-filter symbol? '(1 2 3 a b c)) and it would return -> c b a.

It works now by simply typing (reverse_ (filter_ symbol? '(1 2 3 a b c))) -> c b a but I just want to combine the two.

Any help on doing this in the general case and in this specific one would be much appreciated


Solution

  • For the general case, we can use the curry and compose procedures (which hopefully are available in your interpreter), they allow us to manipulate other procedures:

    ((compose (curry filter_ symbol?) reverse_)
     '(1 2 3 a b c))
    => '(c b a)
    

    For illustrative purposes, here's a naive implementation of both procedures, to understand what they're doing under the hood:

    (define (curry f x)
      (lambda (y) (f x y)))
    
    (define (compose f g)
      (lambda (x) (f (g x))))