Reputation: 45911
I'm learning racket, and I used to use lambda
to define my functions. But I have found that it is not needed to use it (as far as I know).
I have tried these two functions in DrRacket and both returns the same result:
#lang racket
(define factorial
(lambda (number)
(cond ((not (number? number))
(error 'factorial "number is not a number"))
((equal? number 0)
1)
(else
(* number (factorial (- number 1)))))))
(define (factorial1 number)
(cond ((not (number? number))
(error 'factorial1 "number is not a number"))
((equal? number 0)
1)
(else
(* number (factorial1 (- number 1))))))
The second one, factorial1
, doesn't use lambda.
Do I need to use lambda
when I have to declare a function?
Upvotes: 2
Views: 368
Reputation: 1282
As said in the comments, you don't need to use lambda
. It is perhaps more conventional and convenient to use the non-lambda version to define a function
If you use the macro stepper in DrRacket, you can see how your program is expanded. (define (factorial1 number) etc.)
becomes the following:
(define-values (factorial1)
(lambda (number)
(if (#%app not (#%app number? number))
(let-values () (#%app error 'factorial1 (quote "number is not a number")))
(if (#%app equal? number (quote 0))
(let-values () (quote 1))
(let-values () (#%app * number (#%app factorial1 (#%app - number (quote 1)))))))))
Interestingly, both define
forms, the function definition and value ones, expand to define-values
Upvotes: 1