[英]Scheme - define variable as the result of a function?
我的程序之一的開始導致錯誤。 這是問題區域。 我正在嘗試將變量定義為遞歸函數的結果。
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(define a1 (a1func (- n 1))))
如果您要說(test 10)
則錯誤為:
過程應用程序:預期過程,給定:
#<undefined>
; 論據是:9
我以為可以在Scheme中完成? 想法?
在純FP語言中,通過將參數傳遞給函數來完成計算,結果將返回一些值。 您可以將test
結果綁定到名為test
的函數中:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(a1func (- n 1)))
(define (calltest x)
(define (r (test (+ 2 x))))
(- r 4))
變量通常綁定一次,並且不能更改。 函數必須返回值,即表達式的結果,但是(define a1 (a1func(- n 1)))
只是一個定義,而不是表達式,因此正確的代碼應為:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(define a1 (a1func(- n 1)))
a1)
而且由於定義變量並立即返回它是沒有意義的,因此更正確的代碼是:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(a1func(- n 1)))
如果您的方案實現支持lisp宏,則可以這樣編寫:
(define-macro (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
`(define a1 ,(a1func (- n 1))))
或使用命名的let
(define-macro (test n)
`(define a1 ,(let a1func ((i (- n 1)))
(if (= i 1)
0
(+ (/ 1 i) (a1func (- i 1)))))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.