这不是Python中lambda表达式中Assignment的重复,也就是说,我不会问如何欺骗Python在lambda表达式中赋值.
我有一些λ演算背景.考虑到以下代码,看起来Python非常愿意在lambda
表达式中执行副作用:
#!/usr/bin/python
def applyTo42(f):
return f(42)
def double(x):
return x * 2
class ContainsVal:
def __init__(self, v):
self.v = v
def store(self, v):
self.v = v
def main():
print('== functional, no side effects')
print('-- print the double of 42')
print(applyTo42(double))
print('-- print 1000 more than 42')
print(applyTo42(lambda x: x + 1000))
print('-- print c\'s value instead of 42')
c = ContainsVal(23)
print(applyTo42(lambda x: c.v))
print('== not functional, side effects')
print('-- perform …Run Code Online (Sandbox Code Playgroud) 容器接口是否应该将包含元素的指针声明为const?
任务:用C设计一个容器(注意:这显然是关于普通的C, 不是关于C++,也不是C#).容器将被指向项目的指针,并应返回指向项目的指针.
有点无意义的MWE,但这个想法也扩展到有用的容器:
#include <stdio.h>
typedef struct {
void *data;
} container_t;
void put(container_t *c, void *data)
{
c->data = data;
}
void *get(container_t *c)
{
return c->data;
}
int main(void)
{
container_t c;
int x = 42;
int *y;
put(&c, &x);
y = get(&c);
printf("value = %d\n", *y);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.
好吧,容器不应该使用指针来修改存储的数据.我想通过一个小小的改变在界面中明确这一点:
void put(container_t *c, const void *data)
^new
Run Code Online (Sandbox Code Playgroud)
现在编译器要求我做另一个更改,我真的同意这个:
typedef struct { const void *data; } container_t;
^new
Run Code Online (Sandbox Code Playgroud)
然后编译器要求我再做一次更改,这也很合乎逻辑:
const void *get(container_t *c) …Run Code Online (Sandbox Code Playgroud)