If statement 球拍编程-我的地图
在本程序中,如果出现其他情况,您将如何将If statement 球拍编程-我的地图,if-statement,scheme,lisp,conditional,racket,If Statement,Scheme,Lisp,Conditional,Racket,在本程序中,如果出现其他情况,您将如何将cond替换为if-else #lang racket (define (my-map f lst) (cond [(empty? lst) empty] [else (cons (f (first lst)) (my-map f (rest lst)))])) 每秒钟: (cond (predicate consequent) (predicate2 consequent2-1 cons
cond
替换为if-else
#lang racket
(define (my-map f lst)
(cond
[(empty? lst) empty]
[else (cons (f (first lst))
(my-map f (rest lst)))]))
每秒钟:
(cond (predicate consequent)
(predicate2 consequent2-1 consequent2-2)
(else alternative))
可以重写:
(if predicate
consequent
(if predicate2
(begin
consequent2-1
consequent2-2)
alternative))
您的示例变得特别简单,因为子句不超过2个,并且代码没有使用显式begin 一个
cond
表达式(只有一个条件和一个表达式作为结果)和一个else
部分(有一个表达式作为替代)可以很容易地转换为if
表达式。例如,这:
(cond (<cond1> <exp1>)
(else <exp2>))
还要注意,cond
只是表示一系列嵌套的if
表达式的较短方式。可以把它看作是其他编程语言中IF-ELSE IF-ELSE IF-ELSE
的缩写。事实上,在一般情况下,许多口译员都会这样做:
(cond (<cond1> <exp1> <exp2>) ; we can have any number of conditions
(<cond2> <exp3> <exp4>) ; and any number of expressions after condition
(else <exp5> <exp 6>))
请注意,每个条件后面的表达式都位于
begin
表单中,这意味着在cond
中,它们隐式地位于begin
中,因此您可以编写多个!而在if
表达式中,只有一个表达式可以进入后续表达式或替代表达式,如果需要多个表达式,则必须使用begin
。如往常一样,请参阅了解更多详细信息。Racket不是真正的Scheme,例如,Racket需要与Scheme不同的if
语法。但是,考虑到您实际上是在学习Scheme,您可以查看Scheme R7RS规范;它根据if
提供了cond
的定义。以下是我通过删除涉及“=>”的模板简化的定义:
(define-syntax cond
(syntax-rules (else)
((cond (else result1 result2 ...))
(begin result1 result2 ...))
((cond (test)) test)
((cond (test) clause1 clause2 ...)
(let ((temp test))
(if temp temp
(cond clause1 clause2 ...))))
((cond (test result1 result2 ...))
(if test (begin result1 result2 ...)))
((cond (test result1 result2 ...)
clause1 clause2 ...)
(if test
(begin result1 result2 ...)
(cond clause1 clause2 ...)))))
漂亮,是吗
(cond (<cond1> <exp1> <exp2>) ; we can have any number of conditions
(<cond2> <exp3> <exp4>) ; and any number of expressions after condition
(else <exp5> <exp 6>))
(if <cond1>
(begin
<exp1>
<exp2>)
(if <cond2>
(begin
<exp3>
<exp4>)
(begin ; the last expression is the `else` part
<exp5>
<exp6>)))
(define-syntax cond
(syntax-rules (else)
((cond (else result1 result2 ...))
(begin result1 result2 ...))
((cond (test)) test)
((cond (test) clause1 clause2 ...)
(let ((temp test))
(if temp temp
(cond clause1 clause2 ...))))
((cond (test result1 result2 ...))
(if test (begin result1 result2 ...)))
((cond (test result1 result2 ...)
clause1 clause2 ...)
(if test
(begin result1 result2 ...)
(cond clause1 clause2 ...)))))