2
votes

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?

1
You say "by given x and n..." but you only call (func 3) with one argument. I don't fully understand x, x2, xn the way you describe it here. Can you show an example of x and y and the expected result? - Mulan
You function defines 2 local functions and then does nothing more. Some Scheme implementations would return "BaNaNa" while others might try to tell that the function does nothing. Racket does this. Also the two local functions are dead code as they are never used and thus was never needed to be defined. (n1! is called by iter, but since iter is never used n1! is never used either`) - Sylwester

1 Answers

4
votes

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))