Palindrom
Palindrom

Reputation: 443

Using cons, list, append in Scheme

I need to write a code that take a element and add to list that give as input, and return an new list instead of old list.. after than i will do recurssion and i need new list... below code is working fine.. however i try to reduce all set! that because confuse me and sometime i take error that i cannot solve..

How can i do this operation without set! ? I try just cons, list and append but none of them do this job.

(set! list (cons element list))

Thank you..

Upvotes: 2

Views: 3158

Answers (1)

Will Ness
Will Ness

Reputation: 71070

Just (cons element list) is enough.

Your code is altering the contents of list variable. We don't normally do that, in functional style, and the only way to do this is to use set! as you did.

But to just return the new list, which has a new element on top of it, the call (cons element list) is enough:

...
(let ((newlist (cons element oldlist)))
  .....
  ..... use newlist and oldlist as needed

Upvotes: 4

Related Questions