将字符串转换为结构列表方案

时间:2014-06-11 09:51:29

标签: scheme racket

例如我有这样的结构:

(define-struct example (n1 n2)) 

我有这个清单:

(list (make-example 1 3) (make-example 7 9) empty)

并转换为字符串给我这个:

"(#(struct:example 1 3) #(struct:example 7 9) ())"

因为它可以转换回结构列表 像这样:

(list (make-example 1 3) (make-example 7 9) empty)

2 个答案:

答案 0 :(得分:2)

我想你想要"prefab" structures

以下是一个例子:

#lang racket

(define-struct abc (a b c)
  #:prefab)

(define struct-list (list (abc 1 2 3)
                          (abc 4 5 6)))
;; => '(#s(abc 1 2 3) #s(abc 4 5 6))

(define output-port (open-output-string))
(write struct-list output-port)
(define struct-list-string (get-output-string output-port))
;; => "'(#s(abc 1 2 3) #s(abc 4 5 6))"

(define input-port (open-input-string struct-list-string))
(define struct-list-again (read input-port))
;; => '(#s(abc 1 2 3) #s(abc 4 5 6))

(equal? struct-list struct-list-again)
;; => #t

答案 1 :(得分:0)

以结构形式读取数据可以这样做:

(define (string->structure str)
  (with-input-from-string str (lambda () (read))))

使用kayleefrye's suggestion似乎也使这个结构兼容:

(define-struct example (n1 n2) #:prefab)  
(define in (string->structure 
            (any->string (list (example 1 3)
                               (example 7 9) 
                               empty))))
(example-n2 (car in)) ; ==> 3

any->string来自my earlier answer关于如何进行相反的操作。 基本上这个答案与kayleefrye非常相似,但我把它留在这里因为我更喜欢with-input-from-string,但你应该接受另一个答案,因为他提出了#:prefab标志。 / p>