gpt4 book ai didi

c - 在 C 中实现 F# List.scan?

转载 作者:行者123 更新时间:2023-12-03 19:11:46 28 4
gpt4 key购买 nike

您将如何实现与 List.scan 具有相同行为的函数在 F# 中?

这是描述:

Applies a function to each element of the collection, threading an accumulator argument through the computation. This function takes the second argument, and applies the function to it and the first element of the list. Then, it passes this result into the function along with the second element, and so on. Finally, it returns the list of intermediate results and the final result. (link)



当然,我已经尝试过自己,这是我的伪代码(顺便说一句,我不希望您提供有效的 c 代码): 对于电话 scan(myop, ne, x) ,我有伪代码
int n = length(x);
char *b = (char*)malloc(n); //Allocate n bytes
b[0] = ne;
int i = 0;
while (i < n) {
bool tmp = myop(b[i-1], x[i]);
bool b[i] = tmp;
i = i+1;
}
bool list y = b;

但这对 i > 0 失败了从此 b[i]未初始化。你将如何实现这一点?

最佳答案

but this fails for i > 0 since then b[i] is not initialized



在你的伪代码中:
bool tmp = myop(b[i-1], x[i]);
i = 0时会失败(意思是第一次进入while循环),因为你尝试访问索引 -1 ( i = 0 ,所以 b[i-1] 变成 b[-1] ) 的 b ,这是未定义的行为。

你必须开始 whilei = 1 处循环至少。所以,在循环之前:
b[0] = ne;
int i = 0;

可以改为:
b[0] = ne;
// do something with b[0] if you want.
int i = 1;

关于c - 在 C 中实现 F# List.scan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61823304/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com