Added Vectors and Matrics operations, slicing, docs.
This commit is contained in:
1 parent
a72991d1b7
commit
83d8c8b71f
31 files changed
+1972
-41
No files matched your search
@@ -4,6 +4,13 @@ It's an interface if the [Collection] that provides indexing access, like `array
|
||||
Array therefore implements [Iterable] too. Well known implementations of `Array` are
|
||||
[List] and [ImmutableList].
|
||||
|
||||
The language-level bracket syntax supports one or more selectors:
|
||||
|
||||
- `value[i]`
|
||||
- `value[i, j]`
|
||||
|
||||
Concrete array-like types decide what selectors they accept. Built-in list-like arrays use one selector at a time; custom types such as matrices may interpret multiple selectors.
|
||||
|
||||
Array adds the following methods:
|
||||
|
||||
## Binary search
|
||||
|
||||
@@ -30,6 +30,13 @@ There is a shortcut for the last:
|
||||
|
||||
__Important__ negative indexes works wherever indexes are used, e.g. in insertion and removal methods too.
|
||||
|
||||
The language also allows multi-selector indexing syntax such as `value[i, j]`, but `List` itself uses a single selector only:
|
||||
|
||||
- `list[index]` for one element
|
||||
- `list[range]` for a slice copy
|
||||
|
||||
Multi-selector indexing is intended for custom indexers such as `Matrix`.
|
||||
|
||||
## Concatenation
|
||||
|
||||
You can concatenate lists or iterable objects:
|
||||
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
# Matrix (`lyng.matrix`)
|
||||
|
||||
`lyng.matrix` adds dense immutable `Matrix` and `Vector` types for linear algebra.
|
||||
|
||||
Import it when you need matrix or vector arithmetic:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
```
|
||||
|
||||
## Construction
|
||||
|
||||
Create vectors from a flat list and matrices from nested row lists:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val v: Vector = vector([1, 2, 3])
|
||||
val m: Matrix = matrix([[1, 2, 3], [4, 5, 6]])
|
||||
|
||||
assertEquals([1.0, 2.0, 3.0], v.toList())
|
||||
assertEquals([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], m.toList())
|
||||
```
|
||||
|
||||
Factory methods are also available:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val z: Vector = Vector.zeros(3)
|
||||
val i: Matrix = Matrix.identity(3)
|
||||
val m: Matrix = Matrix.zeros(2, 4)
|
||||
```
|
||||
|
||||
All elements are standard double-precision numeric values internally.
|
||||
|
||||
## Shapes
|
||||
|
||||
Matrices may have any rectangular geometry:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val a: Matrix = matrix([[1, 2, 3], [4, 5, 6]])
|
||||
|
||||
assertEquals(2, a.rows)
|
||||
assertEquals(3, a.cols)
|
||||
assertEquals([2, 3], a.shape)
|
||||
assertEquals(false, a.isSquare)
|
||||
```
|
||||
|
||||
Vectors expose:
|
||||
|
||||
- `size`
|
||||
- `length` as an alias of `size`
|
||||
|
||||
## Matrix Operations
|
||||
|
||||
Supported matrix operations:
|
||||
|
||||
- `+` and `-` for element-wise matrix arithmetic
|
||||
- `*` for matrix-matrix product
|
||||
- `*` and `/` by a scalar
|
||||
- `transpose()`
|
||||
- `trace()`
|
||||
- `rank()`
|
||||
- `determinant()`
|
||||
- `inverse()`
|
||||
- `solve(rhs)` for `Vector` or `Matrix` right-hand sides
|
||||
|
||||
Example:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val a: Matrix = matrix([[1, 2, 3], [4, 5, 6]])
|
||||
val b: Matrix = matrix([[7, 8], [9, 10], [11, 12]])
|
||||
val product: Matrix = a * b
|
||||
assertEquals([[58.0, 64.0], [139.0, 154.0]], product.toList())
|
||||
assertEquals([[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]], a.transpose().toList())
|
||||
```
|
||||
|
||||
Inverse and solve:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val a: Matrix = matrix([[4, 7], [2, 6]])
|
||||
val rhs: Vector = vector([1, 0])
|
||||
|
||||
val inv: Matrix = a.inverse()
|
||||
val x: Vector = a.solve(rhs)
|
||||
|
||||
assert(abs(a.determinant() - 10.0) < 1e-9)
|
||||
assert(abs(inv.get(0, 0) - 0.6) < 1e-9)
|
||||
assert(abs(x.get(0) - 0.6) < 1e-9)
|
||||
```
|
||||
|
||||
## Vector Operations
|
||||
|
||||
Supported vector operations:
|
||||
|
||||
- `+` and `-`
|
||||
- scalar `*` and `/`
|
||||
- `dot(other)`
|
||||
- `norm()`
|
||||
- `normalize()`
|
||||
- `cross(other)` for 3D vectors
|
||||
- `outer(other)` producing a matrix
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val a: Vector = vector([1, 2, 3])
|
||||
val b: Vector = vector([2, 0, 0])
|
||||
|
||||
assertEquals(2.0, a.dot(b))
|
||||
assertEquals([0.2672612419124244, 0.5345224838248488, 0.8017837257372732], a.normalize().toList())
|
||||
```
|
||||
|
||||
## Indexing and Slicing
|
||||
|
||||
`Matrix` supports both method-style indexing and bracket syntax.
|
||||
|
||||
Scalar access:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val m: Matrix = matrix([[1, 2, 3], [4, 5, 6]])
|
||||
|
||||
assertEquals(6.0, m.get(1, 2))
|
||||
assertEquals(6.0, m[1, 2])
|
||||
```
|
||||
|
||||
Bracket indexing accepts two selectors: `[row, col]`.
|
||||
Each selector may be either:
|
||||
|
||||
- an `Int`
|
||||
- a `Range`
|
||||
|
||||
Examples:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val m: Matrix = matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
|
||||
|
||||
assertEquals(7.0, m[1, 2])
|
||||
val columnSlice: Matrix = m[0..2, 2]
|
||||
val topLeft: Matrix = m[0..1, 0..1]
|
||||
val tail: Matrix = m[1.., 1..]
|
||||
assertEquals([[3.0], [7.0], [11.0]], columnSlice.toList())
|
||||
assertEquals([[1.0, 2.0], [5.0, 6.0]], topLeft.toList())
|
||||
assertEquals([[6.0, 7.0, 8.0], [10.0, 11.0, 12.0]], tail.toList())
|
||||
```
|
||||
|
||||
Shape rules:
|
||||
|
||||
- `m[Int, Int]` returns a `Real`
|
||||
- `m[Range, Int]` returns an `Nx1` `Matrix`
|
||||
- `m[Int, Range]` returns a `1xM` `Matrix`
|
||||
- `m[Range, Range]` returns a submatrix
|
||||
|
||||
Open-ended ranges are supported:
|
||||
|
||||
- `m[..1, ..1]`
|
||||
- `m[1.., 1..]`
|
||||
- `m[.., 2]`
|
||||
|
||||
Stepped ranges are not supported in matrix slicing.
|
||||
|
||||
Slices currently return new matrices, not views.
|
||||
|
||||
## Rows and Columns
|
||||
|
||||
If you want plain lists instead of a sliced matrix:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val a: Matrix = matrix([[1, 2, 3], [4, 5, 6]])
|
||||
|
||||
assertEquals([4.0, 5.0, 6.0], a.row(1))
|
||||
assertEquals([2.0, 5.0], a.column(1))
|
||||
```
|
||||
|
||||
## Backend Notes
|
||||
|
||||
The matrix module uses a platform-specific backend where available and falls back to pure Kotlin where needed.
|
||||
|
||||
The public Lyng API stays the same across platforms.
|
||||
+18
-2
@@ -1183,8 +1183,24 @@ collection's sugar won't work with it:
|
||||
assertEquals("buzz", x[0])
|
||||
>>> void
|
||||
|
||||
If you want dynamic to function like an array, create a [feature
|
||||
request](https://gitea.sergeych.net/SergeychWorks/lyng/issues).
|
||||
Multiple selectors are packed into one list index object:
|
||||
|
||||
val x = dynamic {
|
||||
get {
|
||||
if( it == [1, 2] ) "hit"
|
||||
else null
|
||||
}
|
||||
}
|
||||
assertEquals("hit", x[1, 2])
|
||||
>>> void
|
||||
|
||||
So:
|
||||
|
||||
- `x[i]` passes `i`
|
||||
- `x[i, j]` passes `[i, j]`
|
||||
- `x[i, j, k]` passes `[i, j, k]`
|
||||
|
||||
This is the same rule used by Kotlin-backed `getAt` / `putAt` indexers in embedding.
|
||||
|
||||
# Theory
|
||||
|
||||
|
||||
@@ -82,11 +82,16 @@ Primary sources used: `lynglib/src/commonMain/kotlin/net/sergeych/lyng/{Parser,T
|
||||
- Type/containment: `is`, `!is`, `in`, `!in`, `as`, `as?`.
|
||||
- Null-safe family:
|
||||
- member access: `?.`
|
||||
- safe index: `?[i]`
|
||||
- safe index: `?[i]`, `?[i, j]`
|
||||
- safe invoke: `?(...)`
|
||||
- safe block invoke: `?{ ... }`
|
||||
- elvis: `?:` and `??`.
|
||||
- Increment/decrement: prefix and postfix `++`, `--`.
|
||||
- Indexing syntax:
|
||||
- single selector: `a[i]`
|
||||
- multiple selectors: `a[i, j, k]`
|
||||
- language-level indexing with multiple selectors is passed to `getAt`/`putAt` as one list-like index object, not as multiple method arguments.
|
||||
- example: `m[0..2, 2]`.
|
||||
|
||||
## 5. Declarations
|
||||
- Variables:
|
||||
|
||||
@@ -58,6 +58,8 @@ Sources: `lynglib/src/commonMain/kotlin/net/sergeych/lyng/Script.kt`, `lynglib/s
|
||||
- `Observable`, `Subscription`, `ObservableList`, `ListChange` and change subtypes, `ChangeRejectionException`.
|
||||
- `import lyng.complex`
|
||||
- `Complex`, `complex(re, im)`, `cis(angle)`, and numeric embedding extensions such as `2.i` / `3.re`.
|
||||
- `import lyng.matrix`
|
||||
- `Matrix`, `Vector`, `matrix(rows)`, `vector(values)`, dense linear algebra, inversion, solving, and matrix slicing with `m[row, col]`.
|
||||
- `import lyng.buffer`
|
||||
- `Buffer`, `MutableBuffer`.
|
||||
- `import lyng.serialization`
|
||||
|
||||
@@ -183,6 +183,72 @@ Scope-backed Kotlin lambdas receive a `ScopeFacade` (not a full `Scope`). For mi
|
||||
|
||||
If you truly need the full `Scope` (e.g., for low-level interop), use `requireScope()` explicitly.
|
||||
|
||||
### 4.5) Indexers from Kotlin: `getAt` and `putAt`
|
||||
|
||||
Lyng bracket syntax is dispatched through `getAt` and `putAt`.
|
||||
|
||||
That means:
|
||||
|
||||
- `x[i]` calls `getAt(index)`
|
||||
- `x[i] = value` calls `putAt(index, value)` or `setAt(index, value)`
|
||||
- field-like `x["name"]` also uses the same index path unless you expose a real field/property
|
||||
|
||||
For Kotlin-backed classes, bind indexers as ordinary methods named `getAt` and `putAt`:
|
||||
|
||||
```kotlin
|
||||
moduleScope.eval("""
|
||||
extern class Grid {
|
||||
override fun getAt(index: List<Int>): Int
|
||||
override fun putAt(index: List<Int>, value: Int): void
|
||||
}
|
||||
""".trimIndent())
|
||||
|
||||
moduleScope.bind("Grid") {
|
||||
init { _ -> data = IntArray(4) }
|
||||
|
||||
addFun("getAt") {
|
||||
val index = args.requiredArg<ObjList>(0)
|
||||
val row = (index.list[0] as ObjInt).value.toInt()
|
||||
val col = (index.list[1] as ObjInt).value.toInt()
|
||||
val data = (thisObj as ObjInstance).data as IntArray
|
||||
ObjInt.of(data[row * 2 + col].toLong())
|
||||
}
|
||||
|
||||
addFun("putAt") {
|
||||
val index = args.requiredArg<ObjList>(0)
|
||||
val value = args.requiredArg<ObjInt>(1).value.toInt()
|
||||
val row = (index.list[0] as ObjInt).value.toInt()
|
||||
val col = (index.list[1] as ObjInt).value.toInt()
|
||||
val data = (thisObj as ObjInstance).data as IntArray
|
||||
data[row * 2 + col] = value
|
||||
ObjVoid
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage from Lyng:
|
||||
|
||||
```lyng
|
||||
val g = Grid()
|
||||
g[0, 1] = 42
|
||||
assertEquals(42, g[0, 1])
|
||||
```
|
||||
|
||||
Important rule: multiple selectors inside brackets are packed into one index object.
|
||||
So:
|
||||
|
||||
- `x[i]` passes `i`
|
||||
- `x[i, j]` passes a `List` containing `[i, j]`
|
||||
- `x[i, j, k]` passes `[i, j, k]`
|
||||
|
||||
This applies equally to:
|
||||
|
||||
- Kotlin-backed classes
|
||||
- Lyng classes overriding `getAt`
|
||||
- `dynamic { get { ... } set { ... } }`
|
||||
|
||||
If you want multi-axis slicing semantics, decode that list yourself in `getAt`.
|
||||
|
||||
### 5) Add Kotlin‑backed fields
|
||||
|
||||
If you need a simple field (with a value) instead of a computed property, use `createField`. This adds a field to the class that will be present in all its instances.
|
||||
|
||||
@@ -110,6 +110,56 @@ For example:
|
||||
assert( 5.clamp(0..10) == 5 )
|
||||
>>> void
|
||||
|
||||
## Linear algebra: `lyng.matrix`
|
||||
|
||||
For vectors and dense matrices, import `lyng.matrix`:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
```
|
||||
|
||||
It provides:
|
||||
|
||||
- `Vector`
|
||||
- `Matrix`
|
||||
- `vector(values)`
|
||||
- `matrix(rows)`
|
||||
|
||||
Core operations include:
|
||||
|
||||
- matrix addition and subtraction
|
||||
- matrix-matrix multiplication
|
||||
- matrix-vector multiplication
|
||||
- transpose
|
||||
- determinant
|
||||
- inverse
|
||||
- linear solve
|
||||
- vector dot, norm, normalize, cross, outer product
|
||||
|
||||
Example:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val a: Matrix = matrix([[1, 2, 3], [4, 5, 6]])
|
||||
val b: Matrix = matrix([[7, 8], [9, 10], [11, 12]])
|
||||
val product: Matrix = a * b
|
||||
assertEquals([[58.0, 64.0], [139.0, 154.0]], product.toList())
|
||||
```
|
||||
|
||||
Matrices also support two-axis bracket indexing and slicing:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val m: Matrix = matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
||||
assertEquals(6.0, m[1, 2])
|
||||
val sub: Matrix = m[0..1, 1..2]
|
||||
assertEquals([[2.0, 3.0], [5.0, 6.0]], sub.toList())
|
||||
```
|
||||
|
||||
See [Matrix](Matrix.md) for the full API.
|
||||
|
||||
## Random values
|
||||
|
||||
Lyng stdlib provides a global random singleton and deterministic seeded generators:
|
||||
|
||||
@@ -375,6 +375,18 @@ It is rather simple, like everywhere else:
|
||||
|
||||
See [math](math.md) for more on it. Notice using Greek as identifier, all languages are allowed.
|
||||
|
||||
For linear algebra, import `lyng.matrix`:
|
||||
|
||||
import lyng.matrix
|
||||
|
||||
val a: Matrix = matrix([[1, 2], [3, 4]])
|
||||
val i: Matrix = Matrix.identity(2)
|
||||
val sum: Matrix = a + i
|
||||
assertEquals([[2.0, 2.0], [3.0, 5.0]], sum.toList())
|
||||
>>> void
|
||||
|
||||
See [Matrix](Matrix.md) for vectors, matrix multiplication, inversion, and slicing such as `m[0..2, 1]`.
|
||||
|
||||
Logical operation could be used the same
|
||||
|
||||
var x = 10
|
||||
@@ -811,6 +823,14 @@ Lists can contain any type of objects, lists too:
|
||||
|
||||
Notice usage of indexing. You can use negative indexes to offset from the end of the list; see more in [Lists](List.md).
|
||||
|
||||
In general, bracket indexing may contain more than one selector:
|
||||
|
||||
value[i]
|
||||
value[i, j]
|
||||
|
||||
For built-in lists, strings, maps, and buffers, the selector is usually a single value such as an `Int`, `Range`, or `Regex`.
|
||||
For types with custom indexers, multiple selectors are packed into one list-like index object and passed to `getAt` / `putAt`.
|
||||
|
||||
When you want to "flatten" it to single array, you can use splat syntax:
|
||||
|
||||
[1, ...[2,3], 4]
|
||||
@@ -1699,6 +1719,14 @@ Open-ended ranges could be used to get start and end too:
|
||||
assertEquals( "pult", "catapult"[ 4.. ])
|
||||
>>> void
|
||||
|
||||
The same bracket syntax is also used by imported numeric modules such as `lyng.matrix`, where indexing can be multi-axis:
|
||||
|
||||
import lyng.matrix
|
||||
|
||||
val m: Matrix = matrix([[1, 2, 3], [4, 5, 6]])
|
||||
assertEquals(6.0, m[1, 2])
|
||||
>>> void
|
||||
|
||||
### String operations
|
||||
|
||||
Concatenation is a `+`: `"hello " + name` works as expected. No confusion. There is also
|
||||
|
||||
@@ -5,6 +5,53 @@ For a programmer-focused migration summary, see `docs/whats_new_1_5.md`.
|
||||
|
||||
## Language Features
|
||||
|
||||
### Matrix and Vector Module (`lyng.matrix`)
|
||||
Lyng now ships a dense linear algebra module with immutable double-precision `Matrix` and `Vector` types.
|
||||
|
||||
It provides:
|
||||
|
||||
- `matrix([[...]])` and `vector([...])`
|
||||
- matrix multiplication
|
||||
- matrix inversion
|
||||
- determinant, trace, rank
|
||||
- solving `A * x = b`
|
||||
- vector operations such as `dot`, `normalize`, `cross`, and `outer`
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val a: Matrix = matrix([[4, 7], [2, 6]])
|
||||
val inv: Matrix = a.inverse()
|
||||
assert(abs(inv.get(0, 0) - 0.6) < 1e-9)
|
||||
```
|
||||
|
||||
Matrices also support Lyng-style slicing:
|
||||
|
||||
```lyng
|
||||
import lyng.matrix
|
||||
|
||||
val m: Matrix = matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
||||
assertEquals(6.0, m[1, 2])
|
||||
val column: Matrix = m[0..2, 2]
|
||||
val tail: Matrix = m[1.., 1..]
|
||||
assertEquals([[3.0], [6.0], [9.0]], column.toList())
|
||||
assertEquals([[5.0, 6.0], [8.0, 9.0]], tail.toList())
|
||||
```
|
||||
|
||||
See [Matrix](Matrix.md).
|
||||
|
||||
### Multiple Selectors in Bracket Indexing
|
||||
Bracket indexing now accepts more than one selector:
|
||||
|
||||
```lyng
|
||||
value[i]
|
||||
value[i, j]
|
||||
value[i, j, k]
|
||||
```
|
||||
|
||||
For custom indexers, multiple selectors are packed into one list-like index object and dispatched through `getAt` / `putAt`.
|
||||
This is the rule used by `lyng.matrix` and by embedding APIs for Kotlin-backed indexers.
|
||||
|
||||
### Decimal Arithmetic Module (`lyng.decimal`)
|
||||
Lyng now ships a first-class decimal module built as a regular extension library rather than a deep core special case.
|
||||
|
||||
|
||||
Reference in new issue
Block a user