在阅读了方法调用表达式,解引用运算符,方法查找和自动解引用之后,我认为我对该主题有了很好的理解。但是后来我遇到了一种情况,我希望自动重新引用会发生,而实际上却没有发生。
示例如下。
#[derive(Clone, Copy, Debug)]
struct Foo();
impl Into<&'static str> for Foo {
fn into(self) -> &'static str {
"<Foo as Into>::into"
}
}
fn vec_into<F: Copy + Into<T>, T>(slice: &[F]) -> Vec<T> {
slice.iter().map(|x| (*x).into()).collect()
}
fn main() {
let array = [Foo(), Foo(), Foo()];
let vec = vec_into::<_, &'static str>(&array);
println!("{:?}", vec);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码有效,但是我认为不需要(*x).into()在函数中vec_into进行显式取消引用。我的理由是,因为x: &Foo,然后x.into()就试图找到接受类型的方法&Foo,&&Foo,&mut &Foo, …
这是对问题的完全重写。希望现在更清楚了。
我想在 C 中实现一个函数,该函数signed int在溢出的情况下执行带包装的s相加。
我想主要针对 x86-64 架构,但当然实现越便携越好。我还主要关心通过 gcc、clang、icc 以及 Windows 上使用的任何东西生成体面的汇编代码。
目标是双重的:
体面的机器代码是指在本机支持该操作的机器上的单个leal或单个addl指令。
我能够满足这两个要求中的任何一个,但不能同时满足。
想到的第一个实现是
int add_wrap(int x, int y) {
return (unsigned) x + (unsigned) y;
}
Run Code Online (Sandbox Code Playgroud)
这似乎适用于gcc、clang和 icc。但是,据我所知,C 标准没有指定从unsigned intto的强制转换signed int,为实现留下了自由(另请参见此处)。
否则,如果新类型是有符号的并且值不能在其中表示;要么结果是实现定义的,要么引发实现定义的信号。
我相信大多数(全部?)主要编译器都会从unsignedto进行预期的转换int,这意味着它们采用正确的代表性模数 2^N,其中 N 是位数,但标准并未强制要求,因此不能依赖(愚蠢的 C 标准再次命中)。此外,虽然这是在二进制补码机上做的最简单的事情,但在补码机上是不可能的,因为有一个类是不可表示的:2^(N/2)。
根据clang docs,可以__builtin_add_overflow像这样使用
int add_wrap(int x, int …Run Code Online (Sandbox Code Playgroud) 在思考另一个问题时,我意识到以下功能smoothSeq和smoothSeq'
smoothSeq :: (Integer, Integer, Integer) -> [Integer]
smoothSeq (a, b, c) = result
where
result = 1 : union timesA (union timesB timesC)
timesA = map (* a) $ result
timesB = map (* b) $ result
timesC = map (* c) $ result
smoothSeq' :: (Integer, Integer, Integer) -> [Integer]
smoothSeq' (a, b, c) = 1 : union timesA (union timesB timesC)
where
timesA = map (* a) $ smoothSeq' (a, b, c) …Run Code Online (Sandbox Code Playgroud) 在https://en.wikibooks.org/wiki/Haskell/Denotational_semantics#Pattern_Matching页面上,进行以下练习:
考虑
or具有以下属性的两个布尔参数的函数:
- 要么 ??=?
- 还是真的?=真
- 要么 ?正确=正确
- 或假y = y
- 或x假= x
此功能是联合严格性的另一个示例,但更加严格:结果仅是?如果两个参数都是(至少在我们将参数限制为True和?时)。这样的功能可以在Haskell中实现吗?
该功能可用下表表示:
| ? | False | True
------|-----------------------
? | ? | ? | True
False | ? | False | True
True | True | True | True
Run Code Online (Sandbox Code Playgroud)
根据https://en.wikibooks.org/wiki/Haskell/Denotational_semantics#Monotonicity中给出的定义,此功能是单调的,因此我看不出有理由排除在Haskell中实现此功能的可能性。但是,我没有实现它的方法。
练习的答案是什么?
PS:我得到的答案是“不,你不能”。我正在寻找的是严格的证明。我觉得我对可以定义什么功能缺少一些重要的限制。绝对不是所有的单调函数。
haskell ×2
c ×1
dereference ×1
integer ×1
memoization ×1
memory ×1
recursion ×1
rust ×1
strictness ×1
traits ×1