Skip to content

Instantly share code, notes, and snippets.

@sidharthkuruvila
Created September 2, 2012 02:37
Show Gist options
  • Select an option

  • Save sidharthkuruvila/3594193 to your computer and use it in GitHub Desktop.

Select an option

Save sidharthkuruvila/3594193 to your computer and use it in GitHub Desktop.
An imperative implementation of map in scheme
#lang r5rs
;Scheme doesn't come with a while loop so we create our own.
(define-syntax while
(syntax-rules (while-loop)
((while cond stmt1 stmt2 ...)
(letrec ((while-loop
(lambda ()
(if cond
(begin stmt1 stmt2 ... (while-loop))
'()))))
(while-loop)))))
;Test if to values are not equal
(define (neqv? a b) (not (eqv? a b)))
;Construct a new list by applying a function on each element
;of the original list.
(define
(map f l)
(let* ((nl (cons '() l))
(p nl))
(while (neqv? l '())
(set-cdr! p (cons (f (car l)) (cdr l)))
(set! p (cdr p))
(set! l (cdr l)))
(cdr nl)))
;Display the squares of the numbers 1 to 10
(display (map
(lambda (x) (* x x))
(list 1 2 3 4 5 6 7 8 9 10)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment