我应该定义函数n! (N-Factorial)
。事情是我不知道如何。
这是我到目前为止,有人可以请帮助吗?我不了解Racket的条件,所以解释会很棒!
(define fact (lambda (n) (if (> n 0)) (* n < n)))
答案 0 :(得分:2)
首先你必须好好看看documentation,这是一个非常简单的例子,但在尝试解决方案之前你必须先了解基础知识,并确保你知道如何编写递归过程。一些评论:
(define fact
(lambda (n)
(if (> n 0)
; a conditional must have two parts:
; where is the consequent? here goes the advance of the recursion
; where is the alternative? here goes the base case of the recursion
)
(* n < n))) ; this line is outside the conditional, and it's just wrong
请注意,最后一个表达式不正确,我不知道它应该做什么,但因为它会引发错误。删除它,集中精力编写条件的主体。
答案 1 :(得分:1)
使用scheme(或lisp)的技巧是在将每个括号组合成更复杂的形式时理解每个括号之间的每一点。
让我们从条件开始吧。 if
有3个参数。它评估第一个,如果是,则返回第二个,如果第一个参数为假,则返回第三个。
(if #t "some value" "some other value") ; => "some value"
(if #f "some value" "some other value") ; => "some other value"
(if (<= 1 0) "done" "go again") ; => "go again"
cond
也会奏效 - 你可以在这里阅读有关条件的球拍介绍:http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29
您可以通过两种不同的方式定义功能。您正在使用匿名函数方法,这很好,但在这种情况下您不需要lambda,因此更简单的语法是:
(define (function-name arguments) result)
例如:
(define (previous-number n)
(- n 1))
(previous-number 3) ; => 2
使用像你一样的lambda,使用不同的语法(不要担心现在的任何其他差异):
(define previous-number* (lambda (n) (- n 1)))
(previous-number* 3) ; => 2
顺便说一句,'*'只是该名称中的另一个角色,没什么特别的(见http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Identifiers%29)。一个 '!'在函数名称末尾通常意味着该函数有副作用,但是n!在这种情况下,你的功能很好。
让我们回到原来的问题,并将函数定义和条件放在一起。我们将使用wiki定义中的“递归关系”,因为它产生了一个很好的递归函数:如果n小于1,则factorial为1.否则,factorial是n小于n的阶乘的n倍。在代码中,它看起来像:
(define (n! n)
(if (<= n 1) ; If n is less than 1,
1 ; then the factorial is 1
(* n (n! (- n 1))))) ; Otherwise, the factorial is n times the factorial of one less than n.
最后一个句子比我想要的更密集一些,所以让我们为n = 2工作吧! (定义n 2) (* n(n!( - n 1))) ; =&GT; (* 2(n!( - 2 1))) (* 2(n!1)) (* 2 1) 2
另外,如果您使用的是Racket,我们很容易确认它是否正常运行:
(check-expect (n! 0) 1)
(check-expect (n! 1) 1)
(check-expect (n! 20) 2432902008176640000)