scheme / racket:可扩展的功能

时间:2014-12-08 06:30:13

标签: racket

我希望为不同类型的对象构建数据结构,这些对象具有访问相同类型参数的不同方式。例如,

圆形对象在其x-coord之前的组代码为10,而线对象在其x-coord之前的标题为30.此外,对象并不总是具有相同的参数

因此,从任何对象中提取所有必要参数的通用函数如下所示:

(define (build-struct lst)
  (if (empty? lst)
      empty
      (begin (make-entity (find-params (string=? (car (car lst)))))
             (build-struct (cdr lst)))))
    ;function to build structs from a list of lists (that contain an object)

(define-struct entity (name x-coord y-coord layer-name [num-vertices #:auto] [radius #:auto] [start-angle #:auto] [end-angle #:auto])
  #:auto-value empty)
;data struct to store object param values

(define (find-circle-param lst parameter)
  (let ((kw (string-upcase parameter)))
    (if (empty? lst)
        '() ;put error message here
        (cond ((and (string=? kw "X-COORD") (= (car lst) "10"))
               (cadr lst))
              ((and (string=? kw "Y-COORD") (= (car lst) "20"))
               (cadr lst))
              ((and (string=? kw "LAYER-NAME") (= (car lst) "8"))
               (cadr lst))
              ((and (string=? kw "RADIUS") (= (car lst) "40"))
               (cadr lst))
              (else #f)))))
(define (find-line-param lst parameter)
  (let ((kw (string-upcase parameter)))
    (if (empty? lst)
        '() ;put error message here
        (cond ((and (string=? kw "X-COORD-START") (= (car lst) "10"))
               (cadr lst))
              ((and (string=? kw "Y-COORD-START") (= (car lst) "20"))
               (cadr lst))
              ((and (string=? kw "X-COORD-END") (= (car lst) "11"))
               (cadr lst))
              ((and (string=? kw "Y-COORD-END") (= (car lst) "21"))
               (cadr lst))
              ((and (string=? kw "LAYER-NAME") (= (car lst) "8"))
               (cadr lst))
              (else #f)))))
;functions to find parameter value depending on object type

我只想创建一个用于查找参数的函数。

1 个答案:

答案 0 :(得分:1)

结构可以具有超类型。如果你有几个具有共同属性的结构,请考虑给它们一个共同的超类型。这是一个例子:

#lang racket
(struct shape        (x y)         #:transparent) ; all shapes has x and y coordinates
(struct circle shape (radius)      #:transparent) ; a circle has besides the center also a radius
(struct line   shape (x-end y-end) #:transparent) ; a line has besides its start point also end coords    
(define c (circle 1 2 3))
(define l (line   4 5 6 7))

(define (position a-shape)
  (match a-shape
    [(shape x y)  (list "Position:" x y)]
    [_            (error 'position "expected a shape, got ~a" a-shape)]))

(position c)
(position l)

请注意,位置的定义可以找到圆和直线的位置,而不会在位置定义中明确提及圆和直线。