Skip to content

Sample programs

Vishal Patil edited this page Dec 31, 2024 · 7 revisions

Note

Please refer to the test cases in eval.rs

Area of a Circle

(define pi 3.14)
(define (area-of-circle r) 
          (* pi (* r r)))
(area-of-circle 10)

Max of 3

(define my-max3 
   (lambda  (x y z)
     (if (& (> x y) (> x z))
       x
       (if (> y z) 
            y
            z))))

(my-max3 1 8 3)  

Sum of first N integers

(begin
  (define sum-n 
      (lambda (n a) 
         (if (= n 0) a 
            (sum-n (- n 1) (+ n a)))))
(sum-n 50000 0)
)

Adder

(define add-n 
   (lambda (n) 
      (lambda (a) (+ n a))))

(define add-5 (add-n 5))

(add-5 10)

Fibonacci numbers using tail recursion

(define fib
  (lambda (n a b) 
     (if (= n 0) a 
        (if (= n 1) b 
           (fib (- n 1) b (+ a b))))))
                  
(fib 10 0 1)

Factorial using tail recursion

(define fact 
  (lambda (n a) 
    (if (= n 1) a 
      (fact (- n 1) (* n a)))))
                        
(fact 10 1)

Function Application

(begin
  (define (double value) 
                (* 2 value))
  (define (apply-twice fn value) 
                (fn (fn value)))
        
   (apply-twice double 5)
)

Map

 (begin
            (define (map f l)
                (if (null? l) 
                    (list) 
                    (cons (f (car l)) (map f (cdr l)))))
            (map (lambda (x) (* x x)) (list 1 2 3 4 5))
        )

Filter

  (begin
            (define (filter f l)
                (if (null? l) 
                    (list) 
                    (if (f (car l)) 
                        (cons (car l) (filter f (cdr l))) 
                        (filter f (cdr l)))))
            (filter (lambda (x) (> x 2)) (list 1 2 3 4 5))
        )

Reduce

(begin
            (define (reduce f l)
                (if (null? l) 
                    (list) 
                    (if (null? (cdr l)) 
                        (car l) 
                        (f (car l) (reduce f (cdr l))))))
            (reduce (lambda (x y) (+ x y)) (list 1 2 3 4 5))
        )