Skip to content

Instantly share code, notes, and snippets.

@anandology
Created September 4, 2012 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anandology/3621046 to your computer and use it in GitHub Desktop.
Save anandology/3621046 to your computer and use it in GitHub Desktop.
Implementation of map function in Racket
#lang racket
; Tail-recursive implementation of map
(define (map f xs)
(define (map-iter xs result)
(if (null? xs)
(reverse result)
(map-iter (cdr xs) (cons (f (car xs)) result))))
(map-iter xs '()))
(define (reverse xs)
(define (reverse-iter xs result)
(if (null? xs)
result
(reverse-iter (cdr xs) (cons (car xs) result))))
(reverse-iter xs '()))
; Here both map and reverse function are looking very similar.
; There is scope for generalization
;
; Here is another attempt using accumulate
(define (accumulate f start xs)
(if (null? xs)
start
(accumulate f (f (car xs) start) (cdr xs))))
(define (reverse1 xs)
(accumulate cons '() xs))
(define (map1 f xs)
(reverse1
(accumulate (lambda (x result) (cons (f x) result)) '() xs)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment