Driagis
Driagis

Reputation: 1

User input to a list

I'm trying to take in user input and add it to a list but I have not been able to get it working. I'm still new to scheme and have been browsing around to try to figure it out but I haven't had any luck.

(display "Continue to enter numbers until satisfied then enter e to end")
(newline)
(define (intlist number)
  (define number(read-line))
  (cond (number? number)
        (cons lst (number))
        (else
         (display lst)
         done')))

this is what I have so far. Any help or direction to where I can learn a bit more is appreciated.

Upvotes: 0

Views: 553

Answers (1)

Martin Půda
Martin Půda

Reputation: 7576

Your solution is almost correct, but it doesn't work, because:

  • Variable lst doesn't exist and with this expression (number), you are calling some undefined function number.

  • done' is badly written 'done.

  • Function cons expects element as first argument and other element or list as second argument. See these examples:

> (cons 1 2)
'(1 . 2)
> (cons 1 '())
'(1)
> (cons 1 (cons 2 (cons 3 '())))
'(1 2 3)

Last example is important here- your function will be recursive and it will return a cons cell in each step. If I will follow your solution, this can be enough:

(define (list-from-user)
  (let ((number (read)))
    (if (number? number)
        (cons number (list-from-user))
        '())))

(Note that I used read instead of read-line, because read-line returns string, and let instead of define.)

If you really want to wait for e, you must decide, what happens if user enters something that isn't number and isn't e- maybe just ignore it?

(define (list-from-user)
  (let ((user-input (read)))
    (cond ((number? user-input) (cons user-input (list-from-user)))
          ((eq? user-input 'e) '())
          (else (list-from-user)))))

Then just add some wrapping function with output:

(define (my-fn)
  (begin (display "Continue to enter numbers until satisfied then enter e to end")
         (newline)
         (list-from-user)))

and call it

> (my-fn)

Note that my function returns list with numbers, instead of some useless 'done, so I can use that function in other functions.

(define (sum-of-list)
  (let ((lst (my-fn)))
    (format "Sum of given list is ~a." (apply + lst))))

> (sum-of-list)

Upvotes: 1

Related Questions