From 9607b9b035620b045764cedb8f1f1626737d24b1 Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 9 Jul 2019 19:33:59 -0700 Subject: [PATCH] Fix matrix to_json and from_json --- src/apatite/linear_algebra/matrix.cr | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/apatite/linear_algebra/matrix.cr b/src/apatite/linear_algebra/matrix.cr index 4e22d35..66616ee 100644 --- a/src/apatite/linear_algebra/matrix.cr +++ b/src/apatite/linear_algebra/matrix.cr @@ -102,6 +102,22 @@ module Apatite::LinearAlgebra diagonal(values, nil) end + # Creates a new `Matrix` instance from a `JSON::PullParser`. + # Defaults to a Float64 matrix. + def self.new(pull : JSON::PullParser) + arr = [] of Array(Float64) + new(pull) do |element| + arr << element + end + rows(arr) + end + + def self.new(pull : JSON::PullParser, &block) + pull.read_array do + yield Array(Float64).new(pull) + end + end + # Creates an +n+ by +n+ diagonal matrix where each diagonal element is # `value`. # @@ -116,8 +132,10 @@ module Apatite::LinearAlgebra # Creates an `n` by `n` identity matrix. # + # NOTE: An explicit type is required since it cannot be inferred. + # # ``` - # Matrix.identity(2) + # Matrix(Int32).identity(2) # # => [ 1, 0, # # 0, 1 ] # ``` @@ -1389,7 +1407,7 @@ module Apatite::LinearAlgebra # Convert the matrix to a json array def to_json(json : JSON::Builder) json.array do - each &.to_json(json) + @rows.to_json(json) end end