簡體   English   中英

方案結構與另一個結構

[英]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這樣的東西,我發現使用matchcond更方便:

(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM