Scheme - define a variable as the result of a function?

Starting one of my programs leads to an error. This is a problem area. I am trying to define a variable as the result of a recursive function.

(define (test n)
  (define (a1func i)
    (if (= i 1) 0
        (+ (/ 1 i) (a1func (- i 1))))) 
  (define a1 (a1func (- n 1))))

if you were to tell him the (test 10)error:

procedure: the expected procedure if #<undefined>:; arguments were: 9

I suggested that this can be done in the diagram? ideas?

0
source share
2 answers

In pure FP languages, calculations are performed by passing parameters to functions that return some values ​​as a result. You can associate the result testwith a function called 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)))
+1

lisp, :

(define-macro (test n)
  (define (a1func i)
    (if (= i 1) 0
        (+ (/ 1 i) (a1func (- i 1)))))  
  `(define a1 ,(a1func (- n 1))))

named let

(define-macro (test n)
  `(define a1 ,(let a1func ((i (- n 1)))
                 (if (= i 1)
                     0
                     (+ (/ 1 i) (a1func (- i 1)))))))
0

Source: https://habr.com/ru/post/1788015/


All Articles