简体   繁体   中英

Racket Scheme nested define

My target is to write method which by given х and n calculate the sum:

S = 1 + x/1! + x2/2! + ... + xn/n!

My code:

#lang racket
(define (func n)
  (define (n1! f)
    (if (= f 0) 1
        (* f (n1! (- f 1)))))
  (define (iter i res)
    (if (= i n) (+ 1 res)
       (iter (+ i 1) (/ i (n1! i))))))
(func 3)

There is error which I do not understand. It says:

begin (possibly implicit): no expression after a sequence of internal definitions in:
  (begin (define (n1! f) (if (= f 0) 1 (* f (n1! (- f 1))))) (define (iter i res) (if (= i n) (+ 1 res) (iter (+ i 1) (/ i (n1! i))))))
  (define (n1! f) (if (= f 0) 1 (* f (n1! (- f 1)))))
  (define (iter i res) (if (= i n) (+ 1 res) (iter (+ i 1) (/ i (n1! i)))))

What I do wrong?

You need to add an expression after the two defines, so that func will actually do something. Currently your code is equivalent to (define (func n)) .

Your code is this

(define (func n)
  (define (n1! f)
    (if (= f 0) 1
        (* f (n1! (- f 1)))))
  (define (iter i res)
    (if (= i n) (+ 1 res)
       (iter (+ i 1) (/ i (n1! i))))))

you need to do this

(define (func n)
  (define (n1! f)
    (if (= f 0) 1
        (* f (n1! (- f 1)))))
  (define (iter i res)
    (if (= i n) (+ 1 res)
       (iter (+ i 1) (/ i (n1! i)))))
  (iter n 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM