lisp 函数式编程的map, filter, fold函数实现


(define hello 100)
(define nums (list 2 3 4 5))
(define (func1 x) (* x 2))
(func1 hello)

;map function
(define (map1 lambda1 list) 
        (if(null? list) 
          '()
         (cons (lambda1 (car list)) (map1 lambda1 (cdr list))) 
          )) 
(map1 func1 nums)

;filter function within '() in result
(define (filter1 lam list)
  (if (null? list)
     '()
     (cons
      (if (lam (car list))
         (car list)
         (quote())
         )
      (filter1 lam (cdr list)))
  ))

;filter function
(define (filter2 lam list)
  (cond
    ((null? list) '())
    ((eq? (lam (car list)) #f) (filter2 lam (cdr list)))
    (else (cons (car list) (filter2 lam (cdr list))))
      )
  )

;delete an element from list
(define rember
 (lambda (a lat)
   (cond
    ((null? lat) '())
    ((eq? (car lat) a) (rember a (cdr lat)))
    (else (cons (car lat)
                (rember a (cdr lat)))))))



(rember '() (filter1 (lambda (x)(= x 2)) nums))

(filter2 (lambda (x)(= (remainder x 3) 0)) nums)

"filter by builtin"
(filter (lambda (x)(= x 2)) nums)
"map by builtin"
(map (lambda (x)(string-append (number->string x) "1000")) nums)


(define list2 (list "hello" "world"))

;fold function
(define (fold1 lam init lat)
  (cond ((null? lat) init)
        (else (fold1 lam (lam init (car lat)) (cdr lat)))
  ))


(fold1 (lambda (x y) (string-append x "-" y)) "iam" list2)