Theodor Berza
Theodor Berza

Reputation: 583

Racket using lambda instead of 2 functions

I want to make a program that finds out if a number is prime or not.

First I made this function that works but requires the user to insert 2 as the second argument:

(define (prim? number counter)
  (if (>= counter number)
      #t
      (if (= (modulo number counter) 0)
          #f
          (prim? number (+ counter 1)))))

So I wanted the user the be able to use the function by using only the necessary information, the number he wants to test. This was the solution:

(define (is-prime? number)
  (prim? number 2))

(define (prim? number counter)
  (if (>= counter number)
      #t
      (if (= (modulo number counter) 0)
          #f
          (prim? number (+ counter 1)))))

My question then was, how can I rewrite the code by using lambdas and having only one elegant function? So I wrote this:

(define (prim number)
   (lambda(counter) (set! counter 2)   
     (if (>= counter number)
         #t
         (if (= (modulo number counter) 0)
             #f
             ((lambda(x) (set! counter (+ counter 1)))
              (prim number))))))

When I run (prim 5) in the REPL it gives me the message #<procedure:D:/Racket/prim.rkt:5:2> and not if the number is prime or not.

How could I write the function with lambdas?

Upvotes: 0

Views: 164

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236034

I think using a named let and a cond would be more elegant, and you should avoid using set! at all costs. Try this:

(define (is-prime? number)
  (let prim? ((number number) (counter 2))
    (cond ((>= counter number) #t)
          ((= (modulo number counter) 0) #f)
          (else (prim? number (+ counter 1))))))

The above defines an inner helper function called prim?. That's simpler than defining a "lambda" as you suggested.

Upvotes: 4

Related Questions