PasteRack.org
Paste # 93617
2015-02-27 05:14:41

Fork as a new paste.

Paste viewed 65 times.


Embed:

  1. #lang racket
  2.  
  3. (define (count-list seq)
  4.   (if (null? seq)
  5.       0
  6.       (+ 1 (count-list (cdr seq)))))
  7.  
  8. (define (first-n n seq)
  9.   (if (> n (count-list seq))
  10.       seq
  11.       (if (= n 0)
  12.           '()
  13.           (cons (car seq) (first-n (- n 1) (cdr seq))))))
  14.  
  15. (define (first n seq)
  16. (cond ((or (null? seq) (= n 0)) '())
  17. ((> n (Count-list seq)) seq)
  18. (else (cons (car seq) (first (- n 1) (cdr seq))))))
  19.  
  20. (first-n 5 '(1 2 3 4))
  21. (first-n 2 '(1 2 3 4))
  22. (first-n 0 '(1 2 3 4))
  23.  
  24. (first 5 '(1 2 3 4))
  25. (first 2 '(1 2 3 4))
  26. (first 0 '(1 2 3 4))

=>

'(1 2 3 4)

'(1 2)

'()

Count-list: undefined;

 cannot reference an identifier before its definition

  in module: 'm

Count-list: undefined;

 cannot reference an identifier before its definition

  in module: 'm

'()