How can I read a set from a file in Racket?

It seems that if I write a set to a file, it is not in a format where it can be easily read as a set. Here is an example:

#lang racket

(let ([out (open-output-file "test.rkt" #:exists 'replace)])
  (write (set 1 2 3 4 5) out)
  (close-output-port out))

This makes the file c #<set: 1 3 5 2 4>, which the reader complains about. There is the following unanswered question on the mailing list here .

The way I get around now is to literally write a line "(set "to a file, then all integers with spaces, and then close ")". Super ugly and I would use a reader if possible.

+4
source share
1 answer

You can use the Racket serialization library for this. Here is an example:

Welcome to Racket v6.4.0.7.
-> (require racket/serialize)
-> (with-output-to-file "/tmp/set.rktd"
     (lambda () (write (serialize (set 1 2 3)))))
-> (with-input-from-file "/tmp/set.rktd"
     (lambda () (deserialize (read))))
(set 1 3 2)

, s-, , (, , , ..):

-> (serialize (set 1 2 3))
'((3)
  1
  (((lib "racket/private/set-types.rkt")
    .
    deserialize-info:immutable-custom-set-v0))
  0
  ()
  ()
  (0 #f (h - (equal) (1 . #t) (3 . #t) (2 . #t))))
+6

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


All Articles