scheme - Recursive range in Lisp adds a period? -
(define .. (lambda (start stop) (cond ((> (add1 start) stop) (quote ())) ((eq? (add1 start) stop) (sub1 stop)) (else (cons start (.. (add1 start) stop))))))
i have defined simple range function. intent for
(.. 1 5) --> (1 2 3 4)
instead, bizarre period being added tuple , have no idea why:
(.. 1 5) --> (1 2 3 . 4)
i don't understand why happening. appreciated
a list in scheme either empty list ()
(also known nil
in lisps), or cons cell car
(also known first
) element of list , cdr
(also known rest
) either rest of list (i.e., list), or atom terminates list. conventional terminator empty list ()
; lists terminated ()
said "proper lists". lists terminated other atom called "improper lists". list (1 2 3 4 5)
contains elements 1, 2, 3, 4, , 5, , terminated ()
. construct
(cons 1 (cons 2 (cons 3 (cons 4 (cons 5 ())))))
now, when system prints cons cell, general case print
(car . cdr)
for instance, result of (cons 1 2)
printed
(1 . 2)
since lists built of cons cells, can use notation lists too:
'(1 2 3 4 5) == '(1 . (2 . (3 . (4 . (5 . ())))))
that's rather clunky, though, lisps (all know of) have special case printing cons cells: if cdr
list (either cons cell, or ()
), don't print .
, , don't print surrounding parenthesis of cdr
(which otherwise have, since it's list). so, if you're seeing result
(1 2 3 . 4)
it means you've got improper list terminated atom 4
. has structure
(1 . (2 . (3 . 4)))
now question is: in code did list construction go awry? ..
supposed return proper list, let's @ cases: first case returns proper list (the empty list):
((> (add1 start) stop) (quote ()))
the second case looks can return that's not list (assuming (sub1 stop) == (- stop 1)
):
((eq? (add1 start) stop) (sub1 stop))
now, if ..
functioning correctly, third case returning proper list (since (cons x y)
proper list if y
is):
(else (cons start (.. (add1 start) stop)))
make second case return list , should set.
Comments
Post a Comment