Created
January 25, 2018 12:48
-
-
Save dnaeon/6ceafa60e92d9d180d8145d0b7fe430f to your computer and use it in GitHub Desktop.
Scheme - range function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; validate-step validates whether a given step is a valid one. | |
(define validate-step | |
(lambda (step) | |
(let ((s | |
(cond | |
((and (list? step) (not (null? step))) (car step)) | |
((and (list? step) (null? step)) 1) | |
((string? step) (string->number step)) | |
((integer? step) step)))) | |
(if (integer? s) | |
(if (= s 0) (error "step cannot be zero") s) | |
(error 'validate-step "invalid step given" s))))) | |
;;; range creates a sequence of integer values from min to max with the given step. | |
;;; | |
;;; Note: the code below does not validate range input, e.g. (range 1 10 -1) is invalid | |
(define range | |
(lambda (min max . step) | |
(let ((step (validate-step step))) | |
(if (< min max) | |
(cons min (range (+ min step) max step)) | |
'())))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment