Welcome to W3Courses
 Like Us on Facebook

Scheme

Flatten a List using Scheme Source Code

The following code flattens a list

CODE
(define (flatten x)
      (cond ((null? x) '())
((atom? x) (list x))
       (else (append (flatten (car x)) (flatten (cdr x))))))


RESULT
> (flatten '(a ((c d) f) d))
(a c d f d)
> (flatten '(a (((d f g)) e) h))
(a d f g e h)

Share

Infix to Postfix Function using Scheme Source Code

Infix to Postfix code

CODE
(define (append x y)
     (cond((null? x) y)
(else (cons (car x) (append (cdr x) y) ))))

Share

Insertion Sort Function using Scheme Source Code

Insertion Sort function code

CODE
(define insertion-sort
  (lambda (lst)
    (if (null? lst)
        '()
        (insert (car lst)
                (insertion-sort (cdr lst))))))

Share

Return the Last Element from the List using Scheme Source Code

The following code returns the last element from the list

 CODE
 (define z 0)
 (define (last-element x)
           (cond ((null? x) z)
                     (else (set! z (car x)) (last-element (cdr x)))))


 RESULT
> (last-element '(a b c d))
d
> (last-element '(d e f g h i j k))
k

Share

Calculate Length of a List using Scheme Source Code

The following code calculates length of a list

 CODE
(define (length ls)
      (if (null? ls)
             0
             (+ (length (cdr ls)) 1))))

Share

Logical Connectives (logical and, or, not, xor, imp) using Scheme Source Code

The following code makes use of logical connectives (logical and, or, not, xor, imp)

CODE
;and (logical connective)
(define (and x y)
      (cond ((eqv? x #t) y)
            (else #f)))

Share

Map Function using Scheme Source Code

Map function code

(define (map f L)
       (cond ((null? L) ‘())
               (else (cons (f (car L)) (map f (cdr L))))))

Share

Check if an Element is a Member of a List using Scheme Source Code

The following code checks if an element is a member of a list

CODE
(define (member? x y)
      (cond ((null? y) #f)
((eqv? x (car y)) #t)
             (else (member? x (cdr y)))))


RESULT
> (member_list 'd '(a x c v b))
#f
> (member? 'f  '(a s d f g h))
#t


 

Share

Power Function using Scheme Source Code

Power function code. Computes like 2^5 = 32

CODE
(define power
(lambda( x y)
(cond((eqv? y 0) 1)
((> y 0) (* (power x (- y 1)) x)))))

Share

Powerset Function using Scheme Source Code

Powerset function code

CODE
(define (powerset a)
   (if (null? a) (list '())
         (let ((p (powerset (cdr a))))
               (append (map (lambda (x) (cons (car a) x)) p) p))))

Share