Harmjan Lever
Harmjan Lever

Reputation: 3

How to use add elements to a matrix?

I want to add multiple items from one list to another list, that is organized in one big list, like a matrix.

let targetlists (list firstlist seccondlist thirdlist)

So in my double while loop, I added this code;

set (item x targetlists) lput (item y sourcelist) (item x targetlists)

Sadly it gives me the following error:

This isn't something you can use "set" on.

I found out that it has to do with how I select the target list, as the following code does work, but doesn't do what I want:

set firstlist lput (item y sourcelist) firstlist

Upvotes: 0

Views: 84

Answers (1)

Bryan Head
Bryan Head

Reputation: 12580

JenB is right that, in general, you use replace-item. However, replacing your while loops with map will be much more effective.

I'm not entirely sure what you're trying to do, but it looks like you're trying to put the elements of sourcelist onto the end of the lists in targetlists. Even if that's not what you're doing, this should point you in the right direction:

set targetlists (map [ [ source-item target-row ] ->
  lput source-item target-row
] sourcelist targetlists)

This will iterate through the items of sourcelist and targetlists together, calling lput on the pairs.

Also, there's a handy shortcut where, if a reporter already does what you want, you can pass it directly to map. So you can condense this to:

set targetlists (map lput sourcelist targetlists)

Now, given that you mentioned nested whiles and you're indexing into the two lists with two different indices, you might be trying to put the entire contents of sourcelist onto the ends of each of the targetlists. If that's the case, you can just do

set targetlists map [ l -> (sentence l sourcelist) ] targetlists

If I'm totally off, and you're trying to do something completely different, just let me know in the comments and I'll update my answer.

Upvotes: 1

Related Questions