Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analog of Python's range in Scheme

Tags:

python

scheme

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)
like image 518
Mirzhan Irkegulov Avatar asked Oct 16 '12 07:10

Mirzhan Irkegulov


4 Answers

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)
like image 86
ayberkt Avatar answered Oct 22 '22 05:10

ayberkt


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.

like image 30
Sven Avatar answered Oct 22 '22 07:10

Sven


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)))))))
like image 41
itsbruce Avatar answered Oct 22 '22 06:10

itsbruce


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

like image 31
nibot Avatar answered Oct 22 '22 07:10

nibot