Branch :
# 1.7 Struct
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.
```elixir
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` :
```elixir
defmodule Vec2D do
defstruct [x: 0.0,
y: 0.0]
end
```
Destructuring works with structs to extract values :
```elixir
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 :
```elixir
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 }
```
You can also use the `KC3.access` function for the same result :
```elixir
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. :
```elixir
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](/doc/)
Previous : [1.2 Integer](1.2_Integer)
Next : [1.4 Ratio](1.4_Ratio)