0
votes

I just had a few questions on list and function operations.

1) If I have a function f[] and a list list, I want to apply f[] sequentially to every element of the list, much like Scan does, but rather than Map, Apply, or even Nest does. How to do this?

2) If I have a list list and an index list ind, how can I assign values to the corresponding elements given another list of values? Map[list[[#]] &, ind] = value_list will give Set::write: Tag Map in ... is Protected error.

3) How to apply a function f[] n times and form a result list, instead of composing the function n times as the function Nest does? Is it Map[f[],Range[n]]?

EDIT

In response to the comment, here are a few simple examples all involving how to set elements with specified indices to zero in a list. There examples are supposed for illustrating purposes. Of course, there must be better options to do these tasks. I just tired these out before coming to the working one like setZeroWithIndex[list_, ind_] := Module[{}, list[[ind]] = ConstantArray[0, Length[ind]]; Return[list]];

1) setZeroWithIndex[list_, ind_] := Scan[ReplacePart[list, # -> 0] &, ind];. This does not work. Replacing Scan with Map, Apply etc. does not work either.

2)setZeroWithIndex[list_, ind_] := Map[list[[#]] &, ind] = ConstantArray[0, Length[ind]]; mylist = Range[20]; setZeroWithIndex[mylist, {2, 4, 6}]. Got the error I posted.

3) setZeroWithRandomIndex[list_] := ReplacePart[list, RandomInteger[{1,Length[list]}] -> 0]. Now I just want to apply setZeroWithRandomIndex n times instead of functionally composing it many times. NestList does not seem to work here.

1
I think an example of each case may be useful, at least for those like me whose English communication skills are nil. - Dr. belisarius
@belisarius: please see my edit. thank you. - Qiang Li
I think you are tying to assign values to values, instead of symbols - Dr. belisarius

1 Answers

4
votes

Scan, or Do will do exactly that. Try Scan[f, list] or Do[f@el, {el, list}].

Regarding 2), you should use Part. For instance list[[{ind}]] = a will change elements as needed. If a is a vector of the same length as ind, then appropriate threading will occur.

3) You should look at NestList.