1
votes

I'm a beginner learner of dr.racket. I'm asked to write a function that does the following: Write a function "readnum" that consumes nothing,and each time it is called, it will produce the Nth number of a defined list.

Example:

(define a (list 0 2 -5 0))

readnum --> 0 (first time readnum is called)

readnum --> 2 (second time readnum is called)

readnum --> -5 (third time readnum is called)

You dont have to worry about the case where the list does have numbers or no numbers left to be read.

Dr.racket is a functional language and it is very inconvinient to mutate variables and use them as counters, and in this problem I am not allowed to define other global functions and variables (local is allowed though). Here is my attempt but it does not seems to work:

(define counter -1)
(define lstofnum (list 5 10 15 20 32 3 2))
(define (read-num)
((begin(set! counter (+ 1 counter)))
(list-ref lstofnum counter)))

Not only I defined global variable which is not allowed, the output is not quite right either.

Any help would be appreciated, thanks!

1
Welcome to StackOverflow. This was a great first post, you explained your problem clearly and precisely, and gave an example of what you have tried and why you think it wasn't working. +1 - BlackVegetable

1 Answers

2
votes

The trick here is to declare a local variable before actually defining the function, in this way the state will be inside a closure and we can update it as we see fit.

We can implement a solution using list-ref and saving the current index, but it's not recommended. It'd be better to store the list and cdr over it until its end is reached, this is what I mean:

(define lstofnum (list 0 2 -5 0))

(define readnum
  (let ((lst lstofnum))              ; list defined outside will be hardcoded
    (lambda ()                       ; define no-args function
      (if (null? lst)                ; not required by problem, but still...
          #f                         ; return #f when the list is finished
          (let ((current (car lst))) ; save the current element
            (set! lst (cdr lst))     ; update list
            current)))))             ; return current element

It works as expected:

(readnum)
=>  0
(readnum)
=>  2
(readnum)
=> -5
(readnum)
=> 0
(readnum)
=> #f