scheme - I would like to understand each line how this code removes duplicates in a list , so this is the list (a b a a a c c) gives (a b) -


here code , working fine on scheme lisp

(define (rdup ls)   (let loop ((ls ls) (current #f))     (cond ((null? ls)               ())           ((null? (cdr ls))         (if (eq? (car ls) current) () ls))           ((eq? (car ls) (cadr ls)) (loop (cdr ls) (car ls)))           ((eq? (car ls) current)   (loop (cdr ls) current))           (else                     (cons (car ls) (loop (cdr ls) (car ls)))) ))) 

and here tried

(rdup '(a b a c c)) 

and got (a b)

i want know how each line of code works

i've added line numbers , fixed indentation make easier explain:

01 (define (rdup ls) 02 (let loop ((ls ls) 03 (current #f))   04  (cond 05   ((null? ls) '()) 06   ((null? (cdr ls))  07        (if (eq? (car ls) current) '() ls)) 08   ((eq? (car ls) (cadr ls))  09        (loop (cdr ls) (car ls))) 10   ((eq? (car ls) current)  11        (loop (cdr ls) current)) 12   (else (cons (car ls)  13        (loop (cdr ls) (car ls))))))) 

line 02: using special form of let syntax create named procedure can call within let. defining (confusingly) variable inside loop ls exact same name variable outside of loop, giving internal variable initial value of external one. defining second parameter, current giving initial value of #f.

line 04 starts cond.

line 05 (i corrected work quoting empty list) returns empty list if ls null. stops procedure , unwinds stack.

line 06 checks if cdr null, indicating operating on last element of list. if true, go line 07 , either return empty list if car of ls equal current, or return ls. ends procedure , unwinds stack.

lines 08-09 duplicates in row , if calls loop procedure using cdr new list , car current.

lines 10-11 check if car equal current , if calls loop procedure cdr (again iterating down list) , current.

if none of conditions met, lines 12-13 create new list cons-ing car of ls result of calling let-created loop procedure on cdr of ls , car of ls.

if procedure worked intended, should have returned '(a b c).

here's 1 works think program intended work:

(define rdup   (lambda (l)    (reverse (let loop ((lst l)                (c '()))       (cond         ((null? lst) c)         (else          (if (member (car lst) c)              (loop (cdr lst) c)              (loop (cdr lst) (cons (car lst) c))))))))) 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -