Schema: change the value of an item in a list

I hate using SO as a way to find simple functions, but I really can't find such a function anywhere:

Given a list (1 2 3 4 5), I need an equivalent (PHP, Perl's, Python's)

$a = array(1, 2, 3, 4, 5); $a[3] = 100; 

The result is (1 2 3 100 5)

Thanks!

+7
source share
4 answers

You can write list-set! Guile, for example:

 (define a (list 1 2 3 4)) ; a is '(1 2 3 4) (define (list-set! list k val) (if (zero? k) (set-car! list val) (list-set! (cdr list) (- k 1) val))) (list-set! a 2 100) ; a is '(1 2 100 4) 

(Tried this on DrRacket.)

+7
source

Guile has a built-in list-set! function list-set! which does exactly what you want using indexes with a zero index. For your example, you will have:

 (define a '(1 2 3 4 5)) (list-set! a 3 100) 

I do not think that this is a standard scheme, and I do not know if it is really effective. For a fixed-length array, use the vector:

 (define a2 #(1 2 3 4 5)) (vector-set! a2 3 100) 

I am sure this is part of the standard language.

+3
source

Using standard functions without SRFI:

 (set-car! (list-tail lst k) val) 
+3
source

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.)

+3
source

All Articles