Created
September 4, 2012 13:14
-
-
Save anandology/3621046 to your computer and use it in GitHub Desktop.
Implementation of map function in Racket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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