Skip to content

Instantly share code, notes, and snippets.

@ddeaguiar
Created April 6, 2014 19:55
Show Gist options
  • Save ddeaguiar/10010756 to your computer and use it in GitHub Desktop.
Save ddeaguiar/10010756 to your computer and use it in GitHub Desktop.
Racket examples - various implementations of list-length
#lang racket
(require racket/trace)
;; Recursive implementation of list length
(define (list-length l)
(if (empty? l)
0
(+ 1 (list-length (cdr l)))))
(trace list-length)
(display (list-length '(1 2 3 4 5))) ;; should be 5
;; Iterative implementation of list length
(define (list-length-iter l acc)
(if (null? l)
acc
(list-length-iter (cdr l) (+ 1 acc))))
(define (list-length-2 l)
(list-length-iter l 0))
(trace list-length-iter)
(display (list-length-2 '(1 2 3 4 5))) ;; should be 5
;; Recursive implementation of list length using pattern matching
(require racket/match)
(define (list-length-3 l)
(match l
['() 0]
[(list-rest _ b) (+ 1 (list-length-3 b))]))
(trace list-length-3)
(list-length-3 '(foo bar baz)) ;; should be 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment