Racket 基本的数学运算

Racket 基本的数学运算

纯函数式编程语言不能用循环,一切这种结构都要改作递归实现

1.平方根(牛顿切线法)

#lang racket
(define (sqrt x)
  (define (good-enough? a b) (< (abs (- (* a a) b)) 0.00001))
  (define (improve a b) (average a (/ b a)))
  (define (average a b) ( / (+ a b) 2))

  (define (_sqrt guess x)
    (if (good-enough? guess x)
        guess
        (_sqrt (improve guess x) x)
     ))
  (_sqrt 1.0 x)
)

2. 判断质数

#lang racket
(define (isPrime x)
  (define (_isPrime idx x)
    (define (<= a b) (or (< a b) (= a b)))
    (define (inRange? j i) (<= (* j j) i))
    (if (inRange? idx x)
        (if (= (remainder x idx) 0)
            #f
            (_isPrime (+ idx 1) x)
            )
        #t
        )
     )
  (if (< x 2)
      #f
  (_isPrime 2 x))
)

3. 求平方根(二分法)

#lang racket
(define (sqrt x)
  (define (good-enough? lwbd upbd)
    (let ((epsilon 0.00001))
      (< (abs (- upbd lwbd)) epsilon)
      )
    )
  (define (f x) (* x x))
  (define (_sqrt lwbd upbd x)
    (let ((m (/ (+ lwbd upbd) 2)))
      (if (good-enough? upbd lwbd)
        m
      (if (> (* (- (f lwbd) x)  (- (f m) x) ) 0)
          (_sqrt m upbd x)
          (_sqrt lwbd m x)
      )
     )
    )
   )
  (_sqrt 0.0 x x)
)

4.分数的四则运算

#lang racket
(define (make-rat a b)
  (let ((_a (abs a))
        (_b (abs b))
        )   
    (let ((_g (gcd _a _b)))
      (if (< (* a b) 0)
      (cons (- (/ _a _g)) (/ _b _g))
      (cons  (/ _a _g) (/ _b _g))))
    )
  )

(define (numer f) (car f))
(define (denom f) (cdr f))

(define (output-rat s)
  
  (display (numer s))
  (display "/")
  (display (denom s))
)

(define (gcd x y)
  (if (= (remainder x y) 0)
      y
      (gcd y (remainder x y))))

(define (add-rat a b)
  (let ((_n (+ (* (numer a) (denom b)) (* (numer b) (denom a))))
        (_d (* (denom a) (denom b)) ))
    (make-rat _n _d))
  )

(define (sub-rat a b)
  (define (neg x) (make-rat (- (numer x)) (denom x)))
  (add-rat a (neg b))
)

(define (mul-rat a b)
  (let ((_n (* (numer a) (numer b)))
        (_d (* (denom a) (denom b)))
        )
    (make-rat _n _d)
    )
  )
(define (div-rat a b)
  (define (reci x)
    (make-rat (denom x) (numer x)))
  (mul-rat a (reci b))
  )


(output-rat (add-rat (make-rat 3 5) (make-rat 1 2)))
(newline)
(output-rat (sub-rat (make-rat 4 5) (make-rat 1 7)))
(newline)
(output-rat (mul-rat (make-rat 2 5) (make-rat 1 2)))
(newline)
(output-rat (div-rat (make-rat 1 7) (make-rat 1 3)))
(newline)
  
  
           

5.对list的map和变长参数的imap


(define (map f h)
  (if (null? h)
      null
      (cons (f (car h)) (map f (cdr h)))
))

(define (imap f . h)
  (map f h)
)

发表评论

电子邮件地址不会被公开。 必填项已用*标注