球拍和逻辑语句或嵌套的if's与结构



我正试图用AND或嵌套的if逻辑语句制作一个简单的Racket代码块。这应该只是指定在名为24hourClock的结构中,变量hours是否高于0并低于24小时,minutes是否高于0但低于60分钟,如果不是,则应分别为hours或minutes键入else错误语句。如果可以的话,如果有一个小的语法错误,请告诉我,我现在正在学习struct和Racket。谢谢

;Attempt 1
(struct 24HourClock (hours minutes)
#:transparent
#:guard     (if (number? hours)
(error name "24HourClock: Hours must between 0 and 23:24.")
(if (number? minutes)
(error name "24HourClock: Minutes must between 0 and 59:60.")                
(values x y))))            
;Attempt 2                 
(struct 24HourClock5 (hours minutes)
#:guard (lambda (hours minutes error_name)
(if (not (and (number? hours) (number? minutes)))
(error error_name "Both fields hours and minutes must be between 0:24 and 0:60")
(values hours minutes)))) 

保护参数必须是过程,就像第二次尝试中一样
在结构定义之外定义它可能是个好主意,因为它并不是很小
也许是这样的:

(define (valid-hours h)
(and (>= h 0) (< h 24)))
(define (valid-minutes m)
(and (>= m 0) (< m 60)))
(define (valid-time h m name)
(cond
[(not (valid-hours h)) (error name "Bad hours")]
[(not (valid-minutes m)) (error name "Bad minutes")]
[else (values h m)]))
(struct 24HourClock (hours minutes)
#:transparent
#:guard valid-time)

相关内容

  • 没有找到相关文章

最新更新