Below is my code which takes a car element of a list(carVal) and an list(initialized to empty) as parameters. I want to append the element to the list but the same is not working.
(define populateValues
(lambda (carVal currVal)
(append currVal(list carVal ))
(display currVal)))
The display shows empty list all the time () . Can anyone help me understand why?
Well, there is
append!as a primitive, which solves most of your problems, as noted already, Scheme tends to frown on mutation, it is possible, but typically avoided, so all procedures that mutate have a!(called a bang) at their end.Also,
set!does not mutate data, it changes an environment, it makes a variable point to another thing, the original data is left unchanged.Mutating data in Scheme is quite cumbersome, but, to give you my own implementation of append! to see how it is done:
Note the use of
set-cdr!, which is a true mutator, it only works on pairs, it mutates data in memory, unlike `set!’. If a pair is passed to a function and mutated with set-cdr! or set-car!, it is mutated every-where in the program.This obeys the SRFI append! spec which says that it should be variadic and that it should return an undefined value, for instance.
Which displays:
As visible, append! can take an infinite number of arguments and it mutates them all but the last.
Scheme might not be the ideal language for you though. The use of append! as said before is nonstandard, instead, append is preferred, which does not mutate and is called for its return value. Which I implement as such:
Which shows a more familiar Scheme style in the absence of mutation, heavy use of recursion
and no use of sequencing.
Edit: If you just want to add some elements to a list and not per se join two though:
Which does what you expect