Reading structures with typed slots in SBCL

Consider this simple code example:

(defstruct test
  (:example nil :type (simple-array single-float)))

(defparameter test-struct
  (make-test :example (make-array 10 :element-type 'single-float
                                     :initial-element 1.0)))

Nothing crazy here, as we can see, a simple structure with one slot is defined. We also point out that the slot :exampleis a highly anticipated array type of single floats. There are no questions, everything is working fine.

Now write test-structto the file:

(with-open-file (out "~/Desktop/out.test"
             :direction :output
             :if-exists :supersede)
  (format out "~s" test-struct))

Again, no surprises, we get a small small file on the desktop with the following contents:

#S(TEST :EXAMPLE #(1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0))

The voltage begins to creep in, however, as we notice that nothing says that this particular literal array should contain single floats. With this suspicion, let's try to load this structure back:

(defparameter loaded-struct
  (with-open-file (in "~/Desktop/out.test")
    (read in nil)))

And here we are, SBCL happily throws us into the debugger:

SBCL gets into the debugger when trying to read a typed array

: SBCL, , ? , , , ?

+4
1

, :

(equalp test-struct
        (read-from-string 
          (with-output-to-string (o)
            (write test-struct :readably t :stream o))))
=> T ;; no error while reading the structure back

:

"#S(TEST
   :EXAMPLE #.(COERCE #(1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0)
                      '(SIMPLE-ARRAY SINGLE-FLOAT (*))))"

format, ~W, *print-readably* - T.

+7

Source: https://habr.com/ru/post/1683102/


All Articles