2014-12-08 2 views
0

동일한 유형의 매개 변수에 액세스하는 다른 방법을 가진 서로 다른 종류의 객체에 대한 데이터 구조체를 만들고 싶습니다. 예 :scheme/racket : extensible functions

circle 객체의 x-coord 앞에는 그룹 코드가 10 인 반면 line 객체에는 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 

난 그냥 매개 변수를 찾기위한 하나 개의 함수를 만들려면 : 모든 개체의 모습에서

그래서 일반적인 기능은 모든 필요한 매개 변수를 추출합니다.

+0

일부 상황이 누락되었습니다. 자신 만의 객체 시스템을 구현하고 있습니까? – soegaard

+0

아니요, 그냥 반복을 줄이고 싶습니다 – KRC

답변

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) 

참고 예를 들면 다음과 같습니다.

+0

실행할 수있는 작은 독립 실행 형 프로그램으로 예제를 확장 할 수 있습니까? 나는 a-shape이 어디에서 유래하는지 확신 할 수 없다. – KRC

+1

a 모양의 a는 이름의 일부입니다. 스 니펫은 완전한 프로그램입니다. – soegaard

+0

오류 -> 원 : 모듈의 언 바운드 식별자 : circle :( – KRC