Question

So I am new to using Scheme/Guile and have an assignment where I must take 2 inputs; a simple variable and a list.

I then add the variable to each number in the list and print it out. I have got it to load but when I enter this:

(add 1 (1 2 3))

I get this error:

Backtrace:
  39: 0* [add 1 ...
  39: 1*  [1 2 3]

standard inout:39:8: In expression (1 2 3):
standard input:39:8:wrong type to appy: 1
ABORT: (misc-error)

Here is the code that I currently have.

(define a (list a))
(define (add y a)
    (define x 0)
    (while (< x (length a))
        (display (+ y (car a)))
        (newline)
        (set! a (cdr a))
        (set! x (+ x 1))
    )
)

My question is:
How do I get the list to work in the parameter? I have looked around online but havent found much to fix this problem. Many thanks ahead of time for any help you can give me.

Was it helpful?

Solution

You're getting an error because (1 2 3) tells it to call the function 1 with two arguments, 2 and 3. To create a list containing 1, 2 and 3, use (list 1 2 3).

OTHER TIPS

Do you really intend to write a procedure in such an imperative way? It looks not very Scheme-like. Evaluating your procedures in GNU Guile yields many error messages about unbound variables etc. set! is eval for beginners of Scheme ;) :) (SICP treats assignment extensively in chapter 3). You can do it much easier in functional style without the side-effects of set! and display.

If you are already aware about mapping and high-order functions, you could do something like this:

(define (add x)
  (lambda (y) (+ x y)))

(map (add 1) (list 1 2 3))
===> (2 3 4)

If not, write a recursive procedure yourself:

(define (add-to-list x list)
  (if (null? list)
      '()
      (cons (+ x (car list))
            (add-to-list x (cdr list)))))

(add-to-list 1 '(1 2 3))
===> (2 3 4)

In order to learn thinking recursively, consult books like SICP, HTDP or "The litte Schemer".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top