Scheme struct 与另一个 struct

Scheme struct with another struct

我正在尝试自学 scheme (drracket),但遇到了问题。

我正在尝试使用不同的形状,例如圆形、正方形和矩形。 任务如下:

"Define the types "circle", "square" and "rectangle" 并定义主要类型 "shape"。 我需要任务的下一部分的形状结构,我必须定义一个函数 "area-of-shape" 它获得一个 "shape" 数据束并且应该代表任何给定形状的区域。

这是我目前的情况:

(define-struct square (nw lenght))

(define-struct circle (center radius))

(define-struct rectangle (nw width height))

(define-struct shape (...))



(define (area-of-shape shapeA)
  (cond 
    [(square? (shapeA)) (* (square-lenght shapeA) (square-lenght shapeA))]
    [(circle? (shapeA)) (* 3.14 (* (circle-radius shapeA) (circle-radius shapeA)))]
    [(rectangle? (shapeA)) (* (rectangle-width shapeA) (rectangle-height shapeA))]))

如何定义结构 shape?我试过

(define-struct shape (circle square rectangle))

但这没有任何意义,因为该结构需要所有 3 种形状。

如有任何帮助,我们将不胜感激。

我会这样做:

(define (area-of-shape shapeA)
  (cond 
    [(square?    shapeA) (* (square-lenght shapeA) (square-lenght shapeA))]
    [(circle?    shapeA) (* 3.14 (* (circle-radius shapeA) (circle-radius shapeA)))]
    [(rectangle? shapeA) (* (rectangle-width shapeA) (rectangle-height shapeA))]
    [else (error 'area-of-shape "A shape is either a square, a circle, or, a rectangle")]))

球拍结构可以从另一个结构继承。所以:

#lang racket

(struct shape ())
(struct square shape (nw length))
(struct circle shape (center radius))
(struct rectangle shape (nw width height))

(define (area-of-shape shape)
  (if (shape? shape)
    (cond
      [(square? shape)    (* (square-length shape) (square-length shape))]
      [(circle? shape)    (* 3.14 (* (circle-radius shape) (circle-radius shape)))]
      [(rectangle? shape) (* (rectangle-width shape) (rectangle-height shape))]
      [else (error 'area-of-shape "Unhandled Shape Condition.")])
    (error 'area-of-shape "Argument not a Shape.")))

;; Example uses
(area-of-shape (square 0 10))
(area-of-shape (circle 0 10))
(area-of-shape (rectangle 0 10 10))

顺便说一下,对于像 area-of-shape 这样的东西,我发现使用 matchcond:

更方便
(define (area-of-shape shape)
  (match shape
    [(square _ len)    (* len len)]
    [(circle _ rad)    (* 3.14 (* rad rad))]
    [(rectangle _ w h) (* w h)]))