开发者

Question about define syntax

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 开发者_JS百科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 ...)


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>


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜