Reputation:
I'm pretty new in Scheme and I'm having some problems with one exercise.
Here it goes: Write the genlist function taking two integer as parameter and returning a list containing the set of integers contained between the two provided
For example: (genlist 5 12)
=> (5 6 7 8 9 10 11 12)
I already did in Python but I dont know how to implement in Scheme.
Upvotes: 1
Views: 381
Reputation: 1028
You can do this using recursion.
The base case for (genlist x y)
is when x == y
, in that case produce (list x)
The recursive stop would be from (genlist x y)
to (genlist (+ x 1) y)
Upvotes: 0
Reputation: 48745
A list like (5 6 7)
is made like (cons 5 (cons 6 (cons 7 '())))
so the simplest solution would be that:
(genlist 8 7) ; ==> ()
(genlist 7 7) ; ==> (cons 7 (genlist 8 7))
Now this isn't the best way to do it, just the simplest. The best way would be to create the list from the end to beginning using a helper:
(genlist-helper 6 7 '()) ; ==>
(genlist-helper 6 6 (cons 7 '())) ; ==>
(genlist-helper 6 5 (cons 6 (cons 7 '())) ; ==>
(cons 6 (cons 7 '())
Now the genlist
just calls the helper by providing the empty list as the initial accumulator. It is also possible to do this with a local procedure where you don't need to add the first parameter since you have it frmo the lexical closure and you can even make it much simpler by using named let
.
I have no idea how you did it in Python. I have no recall that python has cons cells. Algol knowledge usually isn't helping when learning your first lisp language. It's like you make the assumption that since Italian and Spanish was so similar Slovenian must be as well.
Upvotes: 1