Newspiritcompany at Infogami

Newspiritcompany - Infoware Development

sisc example scheme

Example Scheme Code

;;
;; Berlin Brown
;;
;; Some various simple math and statistic routines with scheme
;; Test cases found at the bottom of this page
;;
;; 5/12/2006
;;
;; Uses: sisc - 1.13.6
;;
;; sisc math-test.scm
;;

;;
;; Sum the values of these integers from a to b
(define (sum-integers a b)
  (if (> a b)
      0
      (+ a (sum-integers (+ a 1) b))))

;;
;; Calculate x ^ 3
;; Find X to the power of 3
(define (cube x)
  (* x x x))

;;
;; Find x ^ 2
;; X to the power of two
(define (sqr x)
  (* x x))

(define (sum-cubes a b)
  (if (> a b)
      0
      (+ (cube a) (sum-cubes (+ a 1) b))))

;;
;; Example usage of lambda, just add 100 to the value of 'y'
(define (using-lambda y)
  ((lambda (x) 
     (+ x 100)) y))

;;
;; Accumulate the operation against the following sequence
(define (accum op seq)
  (if (null? seq)
      0
      (op (car seq)
      (accum op (cdr seq)))))

;;
;; Find the mean of the following sequence
(define (find-mean seq)
  (/ (accum + seq) 
     (* 1.0 (length seq))))

;;
;; Used with calculating the standard deviation
;; the squared deviation: SUM (x - u) ^ 2
(define (squared-dev x seq)
  (if (null? seq)
      0
      (+ (sqr (- (car seq) x))
     (squared-dev x (cdr seq)))))

;;
;; Find the standard deviation
;; o2 = SUM (x - u) ^ 2 / n
(define (standard-dev seq)
  (sqrt (/ (squared-dev (find-mean seq) seq)
       (length seq))))

;;
;; Find the factorial of 'n'
(define (fact n)
  (if (= n 1)
      1
      (* n (fact (- n 1)))))

;;
;; binomial-formula
;;
;; C(n, x)p^x * q^(n-x) = n! / ( x! * (n - x)! ) * p^x * q ^(n-x)
;;
(define (binomial-formula prob x n)
  (* (* (expt prob x)
    (expt (- 1 prob) (- n x)))
     (/ (fact n) 
    (* (fact x)
       (fact (- n x))))))

;;
;; Test Cases - Entry Point into the application
(define (scheme-main)
  ;; Test Cases
  (display (sum-integers 4 10))
  (newline)
  (display (sum-cubes 1 10))
  (newline)
  (display (/ (accum + (list 2000 2300)) 2.0))
  (newline)
  (display "Find the Mean: ")
  (display (find-mean (list 3 3 3 3 3 3 4 34 34 3 4)))
  (newline)
  (display "Using Lambda: ")
  (display (using-lambda 32))
  (newline)
  (display "Squared Deviation: ")
  (display (squared-dev (find-mean (list 2 8)) 
            (list 2 8)))
  (newline)
  (display "Standard Deviation: ")
  (display (standard-dev (list 2 9 11 22)))
  (newline)
  ;; Imagine that 40% of employees are smokers
  ;; What is the chance that there are exactly 2 smokers in a sample of 3
  (display "Binomial Forumula: ")
  (display (binomial-formula 0.4 2 3))
  (newline)
  )

(scheme-main)

;;
;; Example Output:
;;
;; (load "scm/math-test.scm")
;; 49
;; 3025
;; 2150.0
;; Find the Mean: 8.818181818181818
;; Using Lambda: 132
;; Squared Deviation: 18.0
;; Standard Deviation: 7.176350047203662
;; Binomial Forumula: 0.28800000000000003
;;

;; End of File