> why do I need a var seq (hidden pointer to a variable on the stack) in order
> to change its items?
You don't, `var openArray` does what you're asking for.
the reason is, because other parts of the object aren't stored on the heap
(length and depending on the runtime also capacity iirc). Another reason is
that seqs behave exactly like regular non heap objects in that they have copy
instead of reference semantics.
So the internal pointer of a seq i
For `seq`, two levels of mutability (pointer and item) are mixed in one (either
both mutable, or both immutable). For `ptr` and `ref`, a level of mutability is
not implemented, as the object pointed to is always considered mutable.
For me the behavior of `ptr` is more correct than that of `seq`. I could never
understand that, if the items of a `seq` are stored on the heap, why do I need
a `var seq` (hidden pointer to a variable on the stack) in order to change its
items?
Pointers are inconsistent with `seq` just like `int` (many values) is
"inconsistent" with `bool` (only two values). An inconsistency usually goes
beyond "I connected two different things in my head and they are different,
ergo inconsistent". There is also `var openArray` (mutable, not appendable
If viewing pointers as values, it's easy to understand this behavior, and I
believe it's correct. However most people don't understand it that way. Nim
only distinguishs between `ptr T` (immutable pointer) and `var ptr T` (mutable
pointer), but not `var ptr T` (mutable pointer to an object) and
Inside a "strict" func the mutations via pointers are forbidden.
If a `ref`/`ptr` is declared with `let`, then the pointer/reference is itself
immutable (meaning it cannot point to somewhere else), however the variable it
points to is still mutable, as the variable pointed to is not a part of the
`let` variable.
let p: ptr int = nil
var a: i
Thanks, that sounds reasonable.
Mutability is allowed for `let` values if they are behind `ref`/`ptr`. In neo,
Vector/Matrix are both `ref object`s, and their `[]=` does not require that
they are `var Vector`/`var Matrix` (which they could, in which case this code
would not compile).
As I understand the let keyword introduces an immutable variable, so you can't
change it after initialization.
So for example
let x = @[1,2,3]
x[0] = 5
Run
wouldn't work.
Yesterday I discovered the library neo, which can be used to create matrices
and vectors. B
11 matches
Mail list logo