KC3 structs are a key value associative data structure with default values and arbitrary property order.
They are compatible with C structs of the same type.
ikc3> a = %KC3.Op{sym: :dot,
precedence: 10,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
%KC3.Op{sym: :dot,
arity: 2,
special: false,
precedence: 10,
associativity: 1,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
You can define one struct type per module with defstruct
for
example in vec2d.kc3
:
defmodule Vec2D do
defstruct [x: 0.0,
y: 0.0]
end
Destructuring works with structs to extract values :
ikc3> %KC3.Op{sym: sym} = ^ a
%KC3.Op{sym: :dot,
arity: 2,
special: false,
precedence: 10,
associativity: 1,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
ikc3> sym
:dot
You can use the dot syntax to access struct values from a Sym
key :
ikc3> a = %KC3.Op{sym: :dot,
precedence: 10,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
%KC3.Op{sym: :dot,
arity: 2,
special: false,
precedence: 10,
associativity: 1,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
ikc3> a.sym
:dot
ikc3> a.arity
2
ikc3> a.callable
fn (a, b) { a.x * b.y + a.y * b.y }
The bracket syntax allows you to query structs the same as maps :
ikc3> a[:sym]
:dot
ikc3> a[:arity]
2
ikc3> a[:callable]
fn (a, b) { a.x * b.y + a.y * b.y }
You can also use the KC3.access
function for the same result :
ikc3> a = %KC3.Op{sym: :dot,
precedence: 10,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
%KC3.Op{sym: :dot,
arity: 2,
special: false,
precedence: 10,
associativity: 1,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
ikc3> access(a, :sym)
:dot
ikc3> access(a, :arity)
2
ikc3> access(a, :callable)
fn (a, b) { a.x * b.y + a.y * b.y }
To update an existing struct property you can use Struct.put, a new struct with modified properties will be returned. E.g. :
ikc3> a = %KC3.Op{sym: :dot,
precedence: 10,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
%KC3.Op{sym: :dot,
arity: 2,
special: false,
precedence: 10,
associativity: 1,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
b = Struct.put(a, :sym, :·)
%KC3.Op{sym: :·,
arity: 2,
special: false,
precedence: 10,
associativity: 1,
callable: fn (a, b) { a.x * b.y + a.y * b.y }}
Top : KC3 documentation
Previous : 1.2 Integer
Next : 1.4 Ratio