Skip to content

Instantly share code, notes, and snippets.

@amoilanen
Created October 8, 2018 20:30
Show Gist options
  • Save amoilanen/b12694eeb5e6e4a2e69d94c8460cdf78 to your computer and use it in GitHub Desktop.
Save amoilanen/b12694eeb5e6e4a2e69d94c8460cdf78 to your computer and use it in GitHub Desktop.
map and fold implementation for lists in Scheme
; Maps function over list
; f - function of one argument, returns transformed argument
; l - list
(define (map f l)
(if (> (length l) 0)
(cons
(f (car l))
(map f (cdr l))
)
()
)
)
; Folds list with a given function
; f - function that accepts two arguments and produces result of the same type
; l - list
; a - initial value to use for folding
(define (foldLeft f l a)
(if (> (length l) 0)
(foldLeft f (cdr l) (f (car l) a))
a
)
)
; Examples
(map (lambda (x) (* x x)) (list 1 2 3))
(foldLeft (lambda (x y) (+ x y)) (list 1 2 3 4 5) 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment