Changeset 30558 in project


Ignore:
Timestamp:
03/14/14 20:02:50 (7 years ago)
Author:
certainty
Message:

data-generators: updated example to a faster implementation

File:
1 edited

Legend:

Unmodified
Added
Removed
  • wiki/eggref/4/data-generators

    r30555 r30558  
    2525=== Examples
    2626<enscript highlight=scheme>
    27 
    2827(use json data-generators)
    2928
     
    3231  (generator
    3332   (with-output-to-string
    34      (lambda ()
    35        (json-write (<- (gen-json-value nesting)))))))
    36 
     33     (lambda ()  (json-write (<- (gen-json-value nesting)))))))
     34
     35;; this is the only tricky part
     36;; we need to stop the recursion at a certain level of nesting and yet
     37;; we want to reduce the construction of generators to a minimum
    3738(define (gen-json-value nesting)
    38   (generator
    39    (if (positive? nesting)
    40        (<- (gen-sample-of (gen-json-string) (gen-json-array nesting) (gen-json-null) (gen-json-number) (gen-json-object nesting)))
    41        (<- (gen-sample-of (gen-json-string) (gen-json-null) (gen-json-number))))))
     39  (let ((scalar (gen-json-scalar)))
     40    (if (positive? nesting)
     41        (let ((complex (gen-json-complex (sub1 nesting)))
     42              (bool    (gen-bool)))
     43          (generator
     44           (if (<- bool)
     45               (<- scalar)
     46               (<- complex))))
     47        scalar)))
     48
     49(define (gen-json-scalar)
     50  (gen-sample-of (gen-json-null) (gen-json-string) (gen-json-number)))
    4251
    4352(define (gen-json-string)
    44   (with-size (range 0  20)
    45     (gen-string-of (gen-char char-set:letter+digit))))
    46 
    47 (define (gen-json-object nesting)
    48   (with-size (range 0  5)
    49     (gen-vector-of (gen-pair-of (gen-json-string) (gen-json-value (sub1 nesting))))))
     53  (with-size (range 0 20)
     54    (gen-string-of (gen-char #\A #\z))))
    5055
    5156(define (gen-json-null)
     
    5560  (gen-sample-of (gen-fixnum) (gen-real)))
    5661
     62(define (gen-json-complex nesting)
     63  (gen-sample-of (gen-json-object (sub1 nesting)) (gen-json-array (sub1 nesting))))
     64
     65(define (gen-json-object nesting)
     66  (gen-vector-of (gen-pair-of (gen-json-string) (gen-json-value (sub1 nesting)))))
     67
    5768(define (gen-json-array nesting)
    58   (with-size (range 0  5)
    59     (gen-list-of (gen-json-value (sub1 nesting)))))
    60 
    61 
    62 (gen-for-each 10 print (gen-json-doc))
     69  (gen-list-of (gen-json-value (sub1 nesting))))
     70
     71;; now let's print our documents
     72(with-size (range 0 20)
     73  (gen-for-each 10 print (gen-json-doc 10)))
     74
    6375</enscript>
    6476
Note: See TracChangeset for help on using the changeset viewer.