[英]Scheme struct with another struct
我试图自己学习计划(运货),但遇到了问题。
我正在尝试使用不同的形状,例如圆形,正方形和矩形。 任务如下:
“定义类型“圆形”,“正方形”和“矩形”并定义主要类型“形状”。我需要在任务的下一部分中使用形状结构,其中我必须定义一个函数“形状区域” ”将获得“形状”数据束,并应表示任何给定形状的区域。
这是我到目前为止的内容:
(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种形状。
任何帮助,将不胜感激。
球拍结构可以从另一个结构继承。 所以:
#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
这样的东西,我发现使用match
比cond
更方便:
(define (area-of-shape shape)
(match shape
[(square _ len) (* len len)]
[(circle _ rad) (* 3.14 (* rad rad))]
[(rectangle _ w h) (* w h)]))
我将按以下方式进行操作:
(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")]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.