Skip to content

Instantly share code, notes, and snippets.

@zallarak
Created January 9, 2012 01:51
Show Gist options
  • Save zallarak/1580536 to your computer and use it in GitHub Desktop.
Save zallarak/1580536 to your computer and use it in GitHub Desktop.
Mapping a linked list in Scheme (Lisp)
; Mapping a singly linked list in Scheme.
; map-1 - the name of our mapping function
; proc - the tranformation
; items - the list
(define (map-1 proc items)
(if (null? items)
()
(cons (proc (car items))
(map-1 proc (cdr items))
)))
; Psuedo-logic below
; Luckily Scheme is clear to read!
; The expression is (map-1 proc items)
; If items is empty, return empty
; else, cons the following pair:
; A: (process (car items))
; (car items) is the first item in the list
; (proc (car items)) is the process being applied to the first item in the list
; B: (map-1 proc (cdr items))
; This is telling the function to run map-1 on (cdr-items)
; (cdr-items) represents the rest of the list. Running map-1 on (cdr items):
; this invokes running proc on (car (cdr items)), the second element
; What is proc? It can be any process that can be applied to a datum
; in our case, we work with integers, so a valid proc might be
(define (abs-1 x)
(if (< x 0) (- x) x))
; So as an example..
(define sample-list (list -1 -2 -3 -4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment