is there a list building method that can reference...
# getting-started
h
is there a list building method that can reference previously constructed elements of the list while building it that i'm not seeing? Or does the collection not exist until after all its elements are determined, so that's not really possible in as a List constructor
l
If you start with a collection or some sort of iterable, maybe you can use
.fold
. It uses an accumulator that is passed in the lambda
h
yeah, i was thinking fold, but wouldn't that be crazy expensive?
oh, well i could fold into a mutable list
k
Or you know, sometimes a for loop is fine as well.
h
yeah, i just figured i could make it all pretty
i think if i did it as a sequence then i could pull elements from early parts of the list while i built it
this feels clever but obnoxious...
Copy code
val (u: List<Vector>, e: List<Vector>) = cols.foldIndexed(ArrayList<Vector>(width) to ArrayList<Vector>(width)) { k, (u, e), a ->
            u[k] = when(k) {
                0 -> a
                1 -> a - a * e[0] * e[0]
                else -> a - e.map { a * it * it }.sum()
            }
            e[k] = u[k] / u[k].magnitude
            u to e
        }
it's a translation of this:
i think i can simplify it all actually
k
I think a for loop with a sum in it is way clearer.
h
yep
you're right
k
Copy code
val U = mutableListOf<Vector>()
for (a in A)
    U += (a - U.sumBy { it * a * a }).unit
h
i'll make it even better actually. i'll give you the result
when i'm done
k
Now I'm curious simple smile
h
Copy code
val e = arrayListOf<Vector>()
        cols.forEachIndexed { k, a ->
            e[k] = when (k) {
                0 -> a
                1 -> a - a * e[0] * e[0]
                else -> a - e.map { a * it * it }.sum()
            }
        }
k
You don't need special cases for 0 and 1 though, right?
h
i don't know why it pastes all skewed like that
k
Because you didn't select the indent of the first line.
h
but yeah, you're right that i don't have to, although it might speed it up a tad, and also it helps for clarity
ah, you're absolutely correct
anyways, u only exists to define e
in the algorithm, so i cut out the middleman
k
It's the other way around no?
h
that's what it seems to be reading top to bottom
but this is qr decomposition, and neither q nor r are defined by u
only e
k
Ah I thought you just wanted to do Gram–Schmidt.
h
this is the gram-schmidt qr decomp algorithm
i just posted the excerpt concerning the block of code i wrote for context
k
I see.