Pum*_*ath -1 functional-programming boolean function racket
我被要求为大学学习一些球拍,最终将不得不用树结构和数据集做一些相当复杂的事情。我才刚刚开始,即使使用Racket docs,google和SO,也无法理解此代码的工作方式。
我正在尝试编写一个带有三个数字参数并返回最大数的函数,这就是我所拥有的:
(define (mymax x1 x2 x3)
(cond
((and (x1 > x2) (x1 > x3)) x1)
(else (and (x2 > x1) (x2 > x3)) x2)
(else (and (x3 > x1) (x3 > x2)) x3)
))
(print (mymax 10 5 1))
Run Code Online (Sandbox Code Playgroud)
所以...
很抱歉,如此无知,但这只是没有道理,对这些要点的任何帮助都将是一个巨大的帮助
这是条件表达式的语法:
(cond
[ConditionExpression1 ResultExpression1]
[ConditionExpression2 ResultExpression2]
...
[ConditionExpressionN ResultExpressionN])
(cond
[ConditionExpression1 ResultExpression1]
[ConditionExpression2 ResultExpression2]
...
[else DefaultResultExpression])
Run Code Online (Sandbox Code Playgroud)
条件表达式的求值遵循2条规则
1)规则cond_false
(cond == (cond
[#false ...] ; first line removed
[condition2 answer2] [condition2 answer2]
...) ...)
Run Code Online (Sandbox Code Playgroud)
2)规则cond_true
(cond == answer-1
[#true answer-1]
[condition2 answer2]
...)
Run Code Online (Sandbox Code Playgroud)
当条件为其他条件时,第二条规则也适用(但请注意,其他条件只能在最后一个子句中出现)。
范例:
(cond
[(= 2 0) #false]
[(> 2 1) (string=? "a" "a")]
[else (= (/ 1 2) 9)])
Run Code Online (Sandbox Code Playgroud)
== {由评估(= 2 0)到#false}
(cond
[#false #false]
[(> 2 1) (string=? "a" "a")]
[else (= (/ 1 2) 9)])
Run Code Online (Sandbox Code Playgroud)
== {根据规则cond_false }
(cond
[(> 2 1) (string=? "a" "a")]
[else (= (/ 1 2) 9)])
Run Code Online (Sandbox Code Playgroud)
== {由评估(> 2 1)到#true}
(cond
[#true (string=? "a" "a")]
[else (= (/ 1 2) 9)])
Run Code Online (Sandbox Code Playgroud)
== {根据规则cond_true }
(string=? "a" "a")
Run Code Online (Sandbox Code Playgroud)
== {由评估(string=? "a" "a")到true}
#true
Run Code Online (Sandbox Code Playgroud)
(define (mymax x1 x2 x3)
(cond
((and (x1 > x2) (x1 > x3)) x1)
(else (and (x2 > x1) (x2 > x3)) x2)
(else (and (x3 > x1) (x3 > x2)) x3)
))
(print (mymax 10 5 1))
Run Code Online (Sandbox Code Playgroud)
这样的表达是(2 > 1)行不通的。应该是(> 2 1)。函数应用程序的语法是前缀语法,即,在圆括号后应加上函数名,并在其后加上参数。
您得到的错误是第二句的语法错误。(else (and (x2 > x1) (x2 > x3)) x2)这一条款有3个:else,(and (x2 > x1) (x2 > x3)),和x2。但是,根据的语法cond,子句只能有2个。
除去elses并添加>前缀后:
(define (mymax x1 x2 x3)
(cond
((and (> x1 x2) (> x1 x3)) x1)
((and (> x2 x1) (> x2 x3)) x2)
((and (> x3 x1) (> x3 x2)) x3)))
(print (mymax 10 5 1))
Run Code Online (Sandbox Code Playgroud)
程序打印10。但请注意,它不适用于(mymax 5 5 5),因此我们将所有>s改为>=s:
(define (mymax x1 x2 x3)
(cond
[(and (>= x1 x2) (>= x1 x3)) x1]
[(and (>= x2 x1) (>= x2 x3)) x2]
[(and (>= x3 x1) (>= x3 x2)) x3]))
(mymax 10 5 1)
; => 10
(mymax 5 5 5)
; => 5
Run Code Online (Sandbox Code Playgroud)
最后,函数不会“返回”值。更好的心理模型是认为他们的身体减少到一定价值。
(define (f x-1 ... x-n)
f-body)
(f v-1 ... v-n)
; == f-body
; with all occurrences of x-1 ... x-n
; replaced with v-1 ... v-n, respectively
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |