Reputation: 110572
I've a beginner (if that) to lisp/scheme and come across the following two ways to "create a function" in scheme:
(define (square x) (* xx))
And:
(define square (lambda (x) (* x x)))
What is the difference between these two? Are both versions supported across all versions/dialects of lisp or is one more "generalized" than the other?
Upvotes: 1
Views: 635
Reputation:
In Scheme they are the same where they are both supported: (define (x ...) ...)
is the same as (define x (lambda (...) ...))
. However certainly they are not the same in Lisp-family languages, which includes a huge variety of languages going back long before Scheme was invented.
However, Scheme standards have a notion of essential and non-essential or optional syntax: any implementation must support essential syntax but implementations are allowed not to support optional syntax. In R4RS, (define <variable> <expression>)
is essential but (define (variable ...) ...)
is not. In R5RS this distinction seems to have gone away: both forms are (I think) now essential.
I would be surprised if any implementations didn't support both forms, other than very minimal / tiny ones perhaps.
Note that if you have a Scheme with only the (define <variable> <expression>)
version but which has a macro system you can pretty easily support the other version too:
(define-syntax defyne
(syntax-rules ()
[(_ (name) form ...)
(defyne name (lambda () form ...))]
[(_ (name formal ...) form ...)
(defyne name (lambda (formal ...) form ...))]
[(_ (name . formal) form ...)
(defyne name (lambda formal form ...))]
[(_ name expression)
(define name expression)]))
(This macro may be buggy: I just typed it in.)
Upvotes: 2
Reputation: 92147
"all versions/dialects of lisp" is a very, very broad brush to paint with. Certainly it does not apply here. It's like asking if "Hello, there" is the right way to address someone in every European country. It's narrower than "in every language", but lisps vary plenty.
But they are both valid in all dialects of Scheme I've ever heard of (in every English-speaking country, in my analogy). They both mean exactly the same thing.
Upvotes: 2