tags:

views:

74

answers:

2

Hi, I'm new to programming, working my way through SICP, and loving it. Though I'm a bit confused about scheme's define syntax, mainly, what's the difference between:

(define foo bar)

and:

(define (foo) bar)

Is the first one just assigns bar to foo and execute it? While the second assigns and waits for the call?

if so how would you go about calling the function inside another function, say within an if statement,

(if (foo) ...)

or

(if foo ...)
+3  A: 

The second version of that creates a function (with no parameters), it's equivalent to

(define foo (lambda () bar))

To call it, it would be (foo)

Jeffrey Aylesworth
Thanks for your fast answer.
Ammar Abdulaziz
+6  A: 

The first version creates a variable named foo and assigns it a reference to bar. Nothing else gets executed.

The second version creates a function with the body bar. The function doesn't get executed, it gets filed away (guessing that's what you mean by 'waiting'?).

You always call a function by making it the first item in a list and evaluating the list.

create a variable

> (define a 1)
> a
1

create another variable referencing the other variable

> (define b a)
> b
1

create a function that returns whatever is in a

> (define (c) a)
> c
#<procedure:c>

evaluate the function

> (c)
1

write a function that evaluates another function and returns the result

> (define (d) (if (odd? a) (c) 0))
> (d)
1

now change it to return the function c

> (define (d) (if (odd? a) c 0))
> (d)
#<procedure:c>
Nathan Hughes