问题
I was thinking about this recently since Python 3 is changing print
from a statement to a function.
However, Ruby and CoffeeScript take the opposite approach, since you often leave out parentheses from functions, thereby blurring the distinction between keywords/statements and functions. (A function call without parentheses looks a lot like a keyword.)
Generally, what's the difference between a keyword and a function? It seems to me that some keywords are really just functions. For example, return 3
could equally be thought of as return(3)
where the return function is implemented natively in the language. Or in JavaScript, typeof
is a keyword, but it seems very much like a function, and can be called with parentheses.
Thoughts?
回答1:
Keywords are lower-level building blocks than functions, and can do things that functions can't.
You cite return
in your question, which is a good example: In all the languages you mention, there's no way to use a function to provide the same behavior as return x
.
回答2:
A function is executed within a stack frame, whereas a keyword statement isn't necessarily. A good example is the return
statement: If it were a function and would execute in its own stack, there would be no way it could control the execution flow in the way it does.
回答3:
Keywords and functions are ambiguous. Whether or not parentheses are necessary is completely dependent upon the design of the language syntax.
Consider an integer declaration, for instance:
int my_integer = 4;
vs
my_integer = int(4)
Both of these examples are logically equivalent, but vary by the language syntax.
Programming languages use keywords to reserve their finite number of basic functions. When you write a function, you are extending a language.
回答4:
In Python, parenthesis are used for function calls, creating tuples or just for defining precedence.
a = (1) #same as a =1
a = (1,) #tuple with one element
print a #prints the value of a
print(a) #same thing, as (a) == a
def foo(x):
return x+1
foo(10) #function call, one element
foo(10,) #function call, also one element
foo 10 #not allowed!
foo(10)*2 #11 times 2 = 22
def foo2(y):
return (y*2)*2 #Not a function call. Same thing as y*4
Also, keywords can't be assigned as values.
def foo(x):
return x**2
foo = 1234 #foo with new value
return = 10 #invalid!
PS: Another use for parenthesis are generators. Just like list comprehensions but they aren't evaluated after creation.
(x**2 for x in range(10))
sum(x+1 for x in [1,2,3]) #Parenthesis used in function call are 'shared' with generator
来源:https://stackoverflow.com/questions/6054672/whats-the-difference-between-a-keyword-or-a-statement-and-a-function-call