How to create a list of consecutive numbers in Scheme?
In Python to create a list of integers from 1 to 10 would be range(1,11)
. Is there an equivalent for Scheme?
mzscheme --version
gives Welcome to Racket v5.2.1.
Edit: Per https://stackoverflow.com/a/7144310/596361 to implement range functionality, this code is needed:
#lang racket
(require srfi/1)
(iota 5 1)
There is a built-in range function in Racket that behaves like that of Python.
> (range 10)
'(0 1 2 3 4 5 6 7 8 9)
Look for iota (as defined in SRFI-1).
Example: (iota 10 1) gives 10 consecutive integers starting from 1 (instead of the default of 0).
iota doesn't take the same arguments as range but it duplicates all the functionality - ascending ranges, descending ranges, starting from 0 if only one bound is given, ability to specify the interval.
Here's a version which does an ascending range if the first number is lower or a descending range if it is higher:
(define range
(lambda (n m)
(cond
((= n m) (list n))
(else (cons n (range ((if (< n m) + -) n 1) m))))))
And here's an improved version which can take 1 or 2 arguments; if only one is given, it does a range from 0 to the given number:
(define range
(lambda (n . m)
(let
((n (if (null? m) 0 n)) (m (if (null? m) n (car m))))
(cond
((= n m) (list n))
(else (cons n (range ((if (< n m) + -) n 1) m)))))))
If there's nothing built-in, it's trivial to write your own:
(define (range first last)
(if (>= first last)
'()
(cons first (range (+ first 1) last))))
Online scheme evaluator: http://eval.ironscheme.net/?id=71
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With