在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
当前回答
在Python中,函数参数的“编译时”(或声明时)计算可能令人困惑:
def append(v, l = []):
l.append(v)
return l
print append(1)
print append(2)
>>> [1]
>>> [1,2]
其意图可能是:
def append(v, l = None):
if l is None:
l = []
l.append(v)
return l
print append(1)
print append(2)
>>> [1]
>>> [2]
这种行为对于缓存之类的事情很有用,但它可能是危险的。
附加特性:具有可变内容的元组:
a = (1,2,[3])
a[2][:] = [4] # OK
a[2] = [2] # crashes
其他回答
这是我最喜欢的一个,你可以在Java中不使用main()来执行println。
这将编译和运行,给出println,但也有一个异常(java.lang。NoSuchMethodError:主要)
class Test {
static {
System.out.println("I'm printing in Java without main()");
}
}
这是我的两分钱。在c++中:
int* t = new int(15);
delete t;
X = X + 1
当我还是初学者的时候,这很难消化,而现在函数式语言不使用它了,这就更难了!
如果你不明白这有多奇怪:把等号看作断言语句,而不是赋值操作,就像你在基础代数中经常做的那样,那么这相当于说“0 = 1”。
Haskell's use of Maybe and Just. Maybe a is a type constructor that returns a type of Just a, but Maybe Int won't accept just an Int, it requires it to be a Just Int or Nothing. So in essence in haskell parlance Just Int is about as much of an Int as an apple is an orange. The only connection is that Just 5 returns a type of Maybe Interger, which can be constructed with the function Just and an Integer argument. This makes sense but is about as hard to explain as it can theoretically be, which is the purpose of haskell right? So is Just really JustKindaLikeButNotAtAll yea sorta, and is Maybe really a KindaLooksLikeOrIsNothing, yea sorta again.
-- Create a function that returns a Maybe Int, and return a 5, which know is definitly Int'able
> let x :: Maybe Int; x = 5;
<interactive>:1:24:
No instance for (Num (Maybe Int))
arising from the literal `5' at <interactive>:1:24
Possible fix: add an instance declaration for (Num (Maybe Int))
In the expression: 5
In the definition of `x': x = 5
> Just 5
Just 5
it :: Maybe Integer
-- Create a function x which takes an Int
> let x :: Int -> Int; x _ = 0;
x :: Int -> Int
-- Try to give it a Just Int
> x $ Just 5
<interactive>:1:4:
Couldn't match expected type `Int' against inferred type `Maybe t'
In the second argument of `($)', namely `Just 5'
In the expression: x $ Just 5
In the definition of `it': it = x $ Just 5
祝你好运读到这篇文章,我希望它是正确的。
在JavaScript中,undefined是一个全局变量,其默认值为原始值undefined。你可以改变undefined的值:
var a = {};
a.b === undefined; // true because property b is not set
undefined = 42;
a.b === undefined; // false
由于undefined的可变性,通过typeof检查undefined通常是一个更好的主意:
var a = {};
typeof a.b == "undefined"; // always true