Scheme 用火柴缩短
如何将if语句替换为代码更易于阅读和理解的match语句Scheme 用火柴缩短,scheme,racket,Scheme,Racket,如何将if语句替换为代码更易于阅读和理解的match语句 (: f (t1 -> integer)) (define f (lambda (x) (if (natural? (t1-b x)) (+ (t1-a x) (t1-b x) (t1-c x)) (if (and (= (t2-e (t1-b x)) 1) (= (t2-d (t1-b x)) 1)) 1
(: f (t1 -> integer))
(define f
(lambda (x)
(if (natural? (t1-b x))
(+ (t1-a x)
(t1-b x)
(t1-c x))
(if (and (= (t2-e (t1-b x)) 1)
(= (t2-d (t1-b x)) 1))
10
(- (+ (t2-d (t1-b x))
(t2-e (t1-b x)))
(t1-a x))))))
对于
匹配
,这不是一个好的用例,这些条件不适合模式匹配。但是我们可以使用cond
简化嵌套条件:
(define (f x)
(cond ((natural? (t1-b x))
(+ (t1-a x)
(t1-b x)
(t1-c x)))
((and (= (t2-e (t1-b x)) 1)
(= (t2-d (t1-b x)) 1))
10)
(else
(- (+ (t2-d (t1-b x))
(t2-e (t1-b x)))
(t1-a x)))))
您没有为
t1
或t2
提供结构定义,因此我将进行猜测
(struct t1 [a b c] #:transparent)
(struct t2 [d e] #:transparent)
假设这些定义与您的定义相符,我可以翻译每个分支的问题和答案
分支1,使用?
模式的条件,命名以消除选择器
第一个分支条件(自然?(t1-b x))
可以转换为
(t1 _ (? natural?) _)
(t1 _ (t2 1 1) _)
[(t1 _ (t2 1 1) _)
10]
?
模式将谓词应用于匹配的值,并且仅在谓词返回true时匹配。要查找其文档,请在中搜索(?expr pat…
而且,由于您在分支回答中使用了选择器t1-a
、t1-b
和t1-c
,因此您可以命名它们
(t1 a (? natural? b) c)
所以整个树枝看起来像
[(t1 a (? natural? b) c)
(+ a b c)]
分支2,使用像1
第二分支条件
(and (= (t2-e (t1-b x)) 1)
(= (t2-d (t1-b x)) 1))
可以翻译成
(t1 _ (? natural?) _)
(t1 _ (t2 1 1) _)
[(t1 _ (t2 1 1) _)
10]
而且,由于在分支答案中不使用任何选择器,因此命名通配符也无济于事,整个问题-答案对可以转换为
(t1 _ (? natural?) _)
(t1 _ (t2 1 1) _)
[(t1 _ (t2 1 1) _)
10]
分支3,消除从内到外的嵌套选择器
对于这个问题,没有分支问题,但正文中使用了选择器:
(- (+ (t2-d (t1-b x))
(t2-e (t1-b x)))
(t1-a x))))
首先消除x
上的t1
选择器:
[(t1 a b _)
(- (+ (t2-d b)
(t2-e b))
a)]
然后消除b
上的t2
选择器:
[(t1 a (t2 d e) _)
(- (+ d e)
a)]
把它放在一起
将三个分支放在主体中的(匹配x branch1 branch2…
)
; assuming these struct definitions
(struct t1 [a b c] #:transparent)
(struct t2 [d e] #:transparent)
(: f (t1 -> integer))
(define f
(lambda (x)
(match x
[(t1 a (? natural? b) c)
(+ a b c)]
[(t1 _ (t2 1 1) _)
10]
[(t1 a (t2 d e) _)
(- (+ d e)
a)])))
t1
的定义在哪里?它看起来像是某种结构,所以您可以显示结构定义吗?如何使用match
将取决于t1
和t2
的结构定义。