Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Some Scheming
Index -> Programming, General Programming -> Functional Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Wed Jan 24, 2007 1:15 am   Post subject: Some Scheming

code:
(define (id x) x)

(define (compose func-list)
  (define (compose2 acc func-list)
    (if (null? func-list)
        acc
        (let ((first (car func-list))
              (rest (cdr func-list)))
          (compose2 (lambda (x) (first (acc x))) rest))))
  (compose2 id func-list))

((compose (list (lambda (x) (+ x 1))
                (lambda (x) (* x 3))
                (lambda (x) (- x 1)))) 5)

(define (compose3 func-list)
  (if (null? func-list)
      id
      (let ((first (car func-list))
            (rest (cdr func-list)))
        (lambda (x)
          ((compose3 rest) (first x))))))

((compose3 (list (lambda (x) (+ x 1))
                 (lambda (x) (* x 3))
                 (lambda (x) (- x 1)))) 5)

(define (r f i xs)
  (if (null? xs)
      i
      (r f (f i (car xs)) (cdr xs))))

(define (compose4 func-list)
  (r (lambda (a b)
       (lambda (x) (b (a x))))
     id
     func-list))

((compose4 (list (lambda (x) (+ x 1))
                 (lambda (x) (* x 3))
                 (lambda (x) (- x 1)))) 5)
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Fri Jan 26, 2007 2:13 am   Post subject: RE:Some Scheming

code:
(define (compose func-list)
  (letrec ((reduce (lambda (f i xs)
                     (if (null? xs) i (reduce f (f i (car xs)) (cdr xs)))))
           (id (lambda (x) x))
           (compose-two (lambda (a b)
                          (lambda (x) (b (a x))))))
    (reduce compose-two id func-list)))

((compose (list (lambda (x) (+ x 1))
                (lambda (x) (* x 3))
                (lambda (x) (- x 1)))) 5)
wtd




PostPosted: Fri Jan 26, 2007 12:11 pm   Post subject: Re: Some Scheming

code:
(define (compose func-list)
  (local ((define (reduce f i xs)
            (if (null? xs) i (reduce f (f i (car xs)) (cdr xs))))
          (define (id x) x)
          (define (compose-two a b)
            (lambda (x) (b (a x)))))
    (reduce compose-two id func-list)))

((compose (list (lambda (x) (+ x 1))
                (lambda (x) (* x 3))
                (lambda (x) (- x 1)))) 5)
Display posts from previous:   
   Index -> Programming, General Programming -> Functional Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: