Skip to content

Instantly share code, notes, and snippets.

@NlightNFotis
Created June 28, 2016 20:12
Show Gist options
  • Save NlightNFotis/b662a0368b5eea68ebfde1e4e4fb9787 to your computer and use it in GitHub Desktop.
Save NlightNFotis/b662a0368b5eea68ebfde1e4e4fb9787 to your computer and use it in GitHub Desktop.
A small naive implementation of map, filter and reduce in racket, implemented by myself.
#lang racket
;; This file departs from the book* a little bit, because, reading the book
;; made some older things I had read in the Simply Scheme book "click in".
;; In particular, I finally understood how I could go around and implement
;; map-filter-reduce on my own, so, this is my stab at it.
;;
;; *where book == The Little Schemer
;; Map works as follows: It takes a function argument and a list of atoms, and
;; returns a new list that is the result of applying the function argument to
;; each of the lists atoms.
(define (map fn lat)
(cond
([null? lat] '())
(else
(cons (fn (car lat)) (map fn (cdr lat))))))
;; Filter works as follows: It takes a function argument that acts as a predicate
;; and a list of atoms, and constructs a new list that only returns the values in
;; the original list that pass the predicate test.
(define (filter fn lat)
(cond
([null? lat] '())
(else
(if (fn (car lat))
(cons (car lat) (filter fn (cdr lat)))
(filter fn (cdr lat))))))
;; Reduce works as follows: It takes a function argument and a list of atoms
;; and recursively applies the function to the lists atoms until they have been
;; reduced to single value dictated by the evaluation of the function argument.
(define (reduce fn lat)
(cond
([null? (cdr lat)] (car lat))
(else
(fn (car lat) (reduce fn (cdr lat))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment