Added to_json and from_json to Matrix and Vector
This commit is contained in:
parent
20bd6423d9
commit
442bf3cde3
|
@ -1,3 +1,4 @@
|
|||
require "json"
|
||||
require "./vector"
|
||||
|
||||
module Apatite::LinearAlgebra
|
||||
|
@ -18,6 +19,21 @@ module Apatite::LinearAlgebra
|
|||
@column_count = column_count || rows[0].size
|
||||
end
|
||||
|
||||
# Creates a new `Vector` instance from a `JSON::PullParser`
|
||||
def self.new(pull : JSON::PullParser)
|
||||
arr = [] of Vector
|
||||
new(pull) do |element|
|
||||
arr << element
|
||||
end
|
||||
rows(arr)
|
||||
end
|
||||
|
||||
def self.new(pull : JSON::PullParser, &block)
|
||||
pull.read_array do
|
||||
yield Vector.new(pull)
|
||||
end
|
||||
end
|
||||
|
||||
# Creates a matrix where each argument is a row.
|
||||
def self.[](*rows)
|
||||
rows(rows)
|
||||
|
@ -528,6 +544,12 @@ module Apatite::LinearAlgebra
|
|||
end
|
||||
end
|
||||
|
||||
def to_json(json : JSON::Builder)
|
||||
json.array do
|
||||
each &.to_json(json)
|
||||
end
|
||||
end
|
||||
|
||||
@[AlwaysInline]
|
||||
def unsafe_fetch(index : Int)
|
||||
@buffer[index]
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
require "json"
|
||||
|
||||
module Apatite::LinearAlgebra
|
||||
# Represents a mathematical vector, and also constitutes a row or column
|
||||
# of a `Matrix`
|
||||
|
@ -75,6 +77,21 @@ module Apatite::LinearAlgebra
|
|||
end
|
||||
end
|
||||
|
||||
# Creates a new `Vector` instance from a `JSON::PullParser`
|
||||
def self.new(pull : JSON::PullParser)
|
||||
vec = new
|
||||
new(pull) do |element|
|
||||
vec << element
|
||||
end
|
||||
vec
|
||||
end
|
||||
|
||||
def self.new(pull : JSON::PullParser, &block)
|
||||
pull.read_array do
|
||||
yield Float64.new(pull)
|
||||
end
|
||||
end
|
||||
|
||||
# Creates a new `Vector` of the given *size* and invokes the given block once
|
||||
# for each index of `self`, assigning the block's value in that index.
|
||||
#
|
||||
|
@ -742,6 +759,20 @@ module Apatite::LinearAlgebra
|
|||
io << "}"
|
||||
end
|
||||
|
||||
def to_json(json : JSON::Builder)
|
||||
json.array do
|
||||
each &.to_json(json)
|
||||
end
|
||||
end
|
||||
|
||||
def from_json(string_or_io)
|
||||
parser = JSON::PullParser.new(string_or_io)
|
||||
new(parser) do |element|
|
||||
yield element
|
||||
end
|
||||
nil
|
||||
end
|
||||
|
||||
def pretty_print(pp) : Nil
|
||||
pp.list("Vector{", self, "}")
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue