Skip to content

Instantly share code, notes, and snippets.

@bradclawsie
Created May 8, 2013 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradclawsie/5538289 to your computer and use it in GitHub Desktop.
Save bradclawsie/5538289 to your computer and use it in GitHub Desktop.
;; blog.jazzychad.net/2012/08/01/array-iteration-problem.html
(use srfi-1)
(: f ((list-of number) number number -> (list-of number)))
(define f
(lambda (arr n i)
(cond [(< n 0)
;; if we are going right-to-left, reverse the list and use the abs count
(reverse (f (reverse arr) (abs n) i))]
[else
;; else walk the list with a counter j, incrementing any i values
(letrec ([n_ne_0? (not (eq? n 0))]
[g
(lambda (arr_ j)
(cond
[(or (null? arr_) (and n_ne_0? (eq? j n)))
;; return rest of list if null, or n != 0 and j == n
;; (in which case we want to cease adding, and
;; j == n is our termination test
arr_]
[else
;; if the first elt is i, increment it and the counter
(let* ([ca (car arr_)]
[p (cond [(eq? ca i) 1] [else 0])])
(cons (+ ca p) (g (cdr arr_) (+ j p))))]))])
(g arr 0))])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment