views:

146

answers:

4

In scheme, why is this:

(define foo
  (lambda (x)
    42))

considered better style than this:

(define (foo x)
  42)

And is there any reason to favour one over the other?

+4  A: 

I don't think that's considered better style, the first is redundant. The real question is whether you define the named function foo or just use lambda instead. If you've already decided to make a named function foo then I don't see why you would put the lambda inside. lambda relieves you of having to separately name and define every little function you make, so that's really where the decision is: is this function important enough to be defined and named separately.

bshields
A: 

What you're showing is equivalent to this in Javascript:

var foo = function(x) {42;}

vs

function foo(x) {
  42;
}

The latter is syntactic sugar of the former. The first style is the general form, that latter is a shortcut for defining functions.

As to style, I don't know why the former would be preferred. It's longer and requires more nesting.

Will Hartung
A: 

If style is another word for preference then I agree that the former is a better style. It says, straightforwardly, "foo is a function of x". Hard to go wrong there. The argument for the "defun" style in your second example is that you define it the way you call it.

It is the lisp-equivalent of where you put the * when declaring a pointer variable in C. Means nothing: pick either what you like, or whatever the group you are working with has already decided. No one will misunderstand you.

anonymous
A: 

This is because

(define (foo x)
   42)

add a special form to the language.

1.

 (define foo 45)

Is one special form

2.

 (lambda (x) (+ x 1)

Is an other special form so:

(define foo (lambda (x) (+ x 1)))

Added no other special form than the 2 above.

So adding a shorthand for defining a function is a syntactic sugar. As scheme tend to be minimalist it is not necessary for the language to add more special form than necessary. Now I think that:

(define foo (x) (+ x 1))

Is readable and it does not cost that mush to remeber and understand so I don't mind to have it in scheme.

mathk