Reputation: 96391
Consider 2 Scheme
functions
; Define function
(define (square n) (* n n ))
(square 12)
144
; Another way to define same function
(define square (lambda (n) (* n n)))
(square 12)
144
Both seem to produce the same result.
Is there any functional difference between these function declarations? Should one be preferred over another in some situations?
Upvotes: 3
Views: 126
Reputation: 971
sepp2k is absolutely correct in that the two procedures you define are identical. In simple procedure definitions like this either is correct and it comes down to a matter of preference.
One case where it does make sense to use an explicit lambda
statement is if you need to keep track of some sort of state in the procedure. For example, we could make a counter like this:
(define counter
(let ((count 0))
(lambda ()
(set! count (+ count 1))
count)))
(counter) ;=> 1
(counter) ;=> 2
(counter) ;=> 3
Upvotes: 1
Reputation: 370162
There is no difference between the two definitions - the former is syntactic sugar for the latter.
Which one you prefer is a matter of style, but my impression is that the former is generally the preferred way of defining functions as it is somewhat more succinct and perhaps also more readable.
Introductory texts often use the latter to make it clear that a named function is simply a variable holding a lambda - something that's not that clear when using the first variant.
Upvotes: 4