Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

R5RS brain fart

Name: Anonymous 2012-08-17 12:56


(define (removerepeated l)
        (cond (case (null? l)
                    (list))
              (case (inlist (cdr l) (car l))
                    (removerepeated (cdr l)))
              (else (cons (car l) (removerepeated (cdr l))))))


l is a list. The procedure is supposed to turn a list l into a set. Yes I know a primitive set exists in Scheme. This is just a data structures exercise I'm doing.

Anyway I run this:


(display (removerepeated (list 1 2 3 4 1 2 3 4 4 3 2 1)))


And get this


()


Questions:

1. Can anyone hint out what is wrong with my snippet of piss poor code?

2. I use (list) to denote an empty list. I this good technique or is there an ulterior way that is more conventional?

3. How does one debug Scheme code? I don't usually use debuggers, just printf and equivalent.

Name: Anonymous 2012-08-17 13:23

By the way. I forget this important tidbit:



(define (inlist l a)
  (if (null? l)
      #f
      (or (= a (car l))
          (inlist (cdr l) a))))


It basically  returns #t if atom a is in list l.

Name: Professional DrRacket Ninja 2012-08-17 13:28

not the most efficient way of doing it:


(define input '(1 2 3 4 1 2 3 4 4 3 2 1))

(define (remove-repeated input)
  (display input)
  (newline)
  (if (null? input) '()
      (cons (car input)
            (remove-repeated (filter
                              (lambda (x)
                                (not (eq? (car input) x)))
                              input)))))

(remove-repeated input)

Name: Anonymous 2012-08-17 15:31

1. You've got the right idea, but your cond syntax is messed up.

(define (remove-repeated l)
  (cond ((null? l) '())
        ((inlist (cdr l) (car l))
         (remove-repeated (cdr l)))
        (else (cons (car l) (remove-repeated (cdr l))))))


2. '() - the empty list () is illegal in Scheme, so you quote it to keep it from being evaluated.

3. A well-structured program helps - break it up into lots of small, pure (whenever possible) functions and debug each separately. If you're having trouble with a single function, just choose an input and step through the function, looking at which branches it takes, the values of intermediate variables, etc. I just do this by hand, not with a debugger, which shouldn't be hard for smaller functions.

Name: Anonymous 2012-08-17 15:54

>>4's got it right
I personally tend to write
(cond ((null? l) l))

Name: Anonymous 2012-08-17 16:56

>>2
You can use memq, memv and member? to find elements in a list, they are part of R5RS.

Don't change these.
Name: Email:
Entire Thread Thread List