为什么这个功能不纯呢? [英] Why is this function not pure?

查看:54
本文介绍了为什么这个功能不纯呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Wikipedia文章中 https://en.wikipedia.org/wiki/Pure_function#Impure_functions它表示以下功能不纯.

In the Wikipedia article https://en.wikipedia.org/wiki/Pure_function#Impure_functions it says that the following function is not pure.

int f(int* x) 
{
    return *x;
}

那是为什么?该函数将为相同的参数返回相同的值,对吗?如果它是一个非可变的引用,是否将其视为纯净的,如下所示?

Why is that? The function would return the same value for the same argument right? Would it be considered pure if it was a non-mutable reference, as in the following?

int f2(const int* x) 
{
    return *x;
}

推荐答案

f 不是纯的,因为对于相同的参数,其返回值不必相同.您可以使用相同的输入两次调用 f 并获得不同的输出.以下程序演示了这一点:

f isn't pure because its return value isn't necessary the same for the same arguments. You could call f twice with the same inputs and get different outputs. The following program demonstrates this:

#include <stdio.h>

int main() {
   int i = 3;
   int * const x = &i;
   printf("%d\n", f(x));
   i = 4;
   printf("%d\n", f(x));
   return 0;
}

由于两次调用之间 x 不变,因此可以优化掉对 f(x)的第二次调用(有利于重用第一次调用的结果调用)(如果 f 是纯净的).显然,这可能会产生错误的结果,因此 f 并不是纯粹的.

Because x doesn't change between the two calls, the second call to f(x) could be optimized away (in favour of reusing the result from the first call) if f was pure. Obviously, that could produce the wrong result, so f isn't pure.

f2 并非出于相同的原因.

f2 isn't pure for the same reason.

这篇关于为什么这个功能不纯呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆