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

Username:   Password: 
 RegisterRegister   
 Scheme TYS
Index -> Programming, General Programming -> Functional Programming
Goto page Previous  1, 2
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Cervantes




PostPosted: Sun Feb 04, 2007 1:27 pm   Post subject: Re: Scheme TYS

Here's mine, not translated to R5RS.

scheme:

(define (p-canonize sparse-poly)
  (local ((define (aux prev-element ssp)
            (cond
              [(empty? ssp) (cons prev-element empty)]
              [(= (cadr prev-element) (cadar ssp))
               (aux (list (+ (car prev-element) (caar ssp)) (cadr prev-element)) (cdr ssp))]
              [else (cons prev-element (aux (car ssp) (cdr ssp)))])))
    (filter (lambda (x) (not (= 0 (fst x))))
            (aux '(0 0) (sort sparse-poly (lambda (a b) (< (cadr a) (cadr b))))))))
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Mon Feb 05, 2007 11:36 pm   Post subject: RE:Scheme TYS

New one. Probably rather simple, but let's see what kind of responses we get. Smile

Write a tail-recursive function split which splits a list into a pair of lists, based on whether or not the members satisfy a predicate.

code:
(split (lambda (x) (< x 2))
       '(0 1 2 3 4 5))


Should result in:

code:
((0 1) (2 3 4 5))
Cervantes




PostPosted: Tue Feb 06, 2007 3:08 pm   Post subject: RE:Scheme TYS

Seems like pretty easy accumulative recursion:
scheme:

(define (split pred lst)
  (letrec ((aux
            (lambda (pred lst pass fail)
              (cond
                ((empty? lst) (list pass fail))
                ((pred (car lst)) (aux pred (cdr lst) (cons (car lst) pass) fail))
                (else (aux pred (cdr lst) pass (cons (car lst) fail)))))))
    (aux pred lst empty empty)))

(split (lambda (x) (< x 4)) '(1 2 3 8 4 3 6 9))

This function is useful in implementing a quicksort.
wtd




PostPosted: Tue Feb 06, 2007 5:06 pm   Post subject: RE:Scheme TYS

My own solution implemented this in terms of a left -> right reduction. Smile

An O'Caml version:

code:
let split f = List.fold_left (fun (a, a') b -> if f b then (a @ [b], a') else (a, a' @ [b])) ([], [])
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 2 of 2  [ 19 Posts ]
Goto page Previous  1, 2
Jump to:   


Style:  
Search: