Scheme examples


Examples of functions in Scheme language from SICP book.


Scheme: factorial function


Reverse a list passed as argument (iterative way):
(define (reverse-list lst)
  (define (reverse-list-iter list1 result)
	(if (null? list1)
		result
		(let ((tail (cdr list1))
			  (first (car list1)))
		  (reverse-list-iter tail (cons first result)))))
  (reverse-list-iter lst (list)))



Reverse a list passed as argument (using append procedure):
(define (reverse-list list1)
  (if (null? list1)
	  '()
	  (append (reverse-list (cdr list1)) (list (car list1)))))



Create a list with all the elements in the list with same even-odd parity as the first element:
(define (same-parity lst)
  (define (same-parity-inner rmd list1)
	(if (null? list1)
		(list)
		(let ((felement (car list1))
			  (tail (cdr list1)))
		  (if (= rmd (remainder felement 2))
			  (cons felement (same-parity-inner rmd tail))
			  (same-parity-inner rmd tail)))))
  
  (if (null? lst)
	  (list)
	  (let ((first (car lst)))
		(cons first (same-parity-inner (remainder first 2) (cdr lst))))))