I may be a little late, but I have a different answer.
Part of the functional program paradigm seems to be trying to avoid modifying the data whenever possible. For efficiency reasons, you can go with other answers here. But otherwise, consider a non-mutating function, such as:
(define (list-with lst idx val) (if (null? lst) lst (cons (if (zero? idx) val (car lst)) (list-with (cdr lst) (- idx 1) val))))
What passes the following tests:
(describe "a function that returns a list with a 'changed' value" (it "can modify the edges of lists without having 1-off errors" (expect (list-with '(1 2 3 4 5) 0 99) (be equal? '(99 2 3 4 5))) (expect (list-with '(1 2 3 4 5) 4 99) (be equal? '(1 2 3 4 99)))) (it "has something to do with creating new lists" (expect (list-with '(1 2 3 4 5) 2 99) (be equal? '(1 2 99 4 5)))) (it "doesnt just modify the contents of the original list" (let ((a '(1 2 3 4 5))) (list-with a 2 99) (expect a (be equal? '(1 2 3 4 5))))))
(The code is written in the Chicken Scheme and tests with the missbehave library, but this seems like a pretty portable circuit.)
Steven degutis
source share