読者です 読者をやめる 読者になる 読者になる

はわわーっ

はわわわわっ

scheme のリストとか

scheme

scheme の勉強中。書いたコードを残しておく。

(define (double-list ls)
  (if (null? ls) ()
    (cons (* 2 (car ls)) (double-list (cdr ls)))))

(print (double-list '(1 2 3 4 5)))
;(2 4 6 8 10)
(print (double-list '()))
;()

(define (multiply-list m ls)
  (if (null? ls) ()
    (cons (* m (car ls)) (multiply-list m (cdr ls)))))

(print (multiply-list 3 '(1 2 3 4)))
;(3 6 9 12)

(define (take-int n ls)
  (if (or (= n 0) (null? ls)) ()
    (cons (car ls) (take-int (- n 1) (cdr ls)))))

(print (take-int 4 '(1 2 3 4 5 6 7 8 9)))
;(1 2 3 4)
(print (take-int 5 '(1 2 3)))
;(1 2 3)

(define (drop-int n ls)
  (cond
    ((null? ls) ())
    ((= n 0) ls)
    (else (drop-int (- n 1) (cdr ls)))))

(print (drop-int 4 '(1 2 3 4 5 6 7 8 9)))
;(5 6 7 8 9)
(print (drop-int 5 '(1 2 3)))
;()

(define (sum-int ls)
  (let loop ((sum 0) (ls ls))
    (if (null? ls) sum
      (loop (+ sum (car ls)) (cdr ls)))))

(print (sum-int '(1 2 3 4 5 6)))
;21

(define (scan-int ls)
  (let loop ((sum 0) (ls ls))
    (if (null? ls) ()
      (let ((s (+ sum (car ls))))
        (cons s (loop s (cdr ls)))))))

(print (scan-int '(1 2 3 4 5)))
;(1 3 6 10 15)

(define (diffs ls)
  (if (or (null? ls) (null? (cdr ls))) ()
    (cons (- (cadr ls) (car ls)) (diffs (cdr ls)))))

(print (diffs '(3 5 6 8)))
;(2 1 2)
(print (diffs '(3)))
;()
(print (diffs '()))
;()

; same as 'map'
(define (apply-to-integers f ls)
  (if (null? ls) ()
    (cons (f (car ls)) (apply-to-integers f (cdr ls)))))

(print (apply-to-integers (lambda (x) (* 2 x)) '(1 2 3 4 5)))
;(2 4 6 8 10)
(print (apply-to-integers (lambda (x) (* x x)) '(1 2 3 4 5)))
;(1 4 9 16 25)

(define (heads ls) (map car ls))

(print (heads '((1 2 3) (4 3 2) (3 4 5))))
;(1 4 3)