hangingfan / Technical-Blog

-----------------个人博客-----------------
1 stars 0 forks source link

lazy evaluate and eager evaluation #7

Open hangingfan opened 6 years ago

hangingfan commented 6 years ago
I'm reading SICP, the notion of lazy evaluation and eager evaluation is very interesting.Or called normal-order evaluation and applicative-order evaluation.

In SICP, the exercise 1.6 shows the difference between "if" and "new-if", It illustrates nicely the eager evaluation. So I experimented the C++ and C# lanaguage ,both shows out that three of them are eager evaluation. Here is the C# code example:

        static float average(float x, float y)
        {
            return (x + y) / 2;
        }

        static float improve(float guess, float x)
        {
            return average(guess, x / guess);
        }

        static bool good_enough(float guess, float x)
        {
            return Math.Abs(guess * guess - x) < 0.001f;
        }

        static float new_if(bool ret, float consequence, float nextConsequence)
        {
            if (ret)
            {
                return consequence;
            }
            else
            {
                return nextConsequence;
            }
        }

        static float sqart_iter(float guess, float x)
        {
            return new_if(good_enough(guess, x), guess, sqart_iter(improve(guess, x), x));
        }

        static void Main(string[] args)
        {
            sqart_iter(1, 9);
            Console.ReadLine();
        }

C++ code example:

float average(float x, float y)
{
    return (x + y) / 2;
}

float improve(float guess, float x)
{
    return average(guess, x / guess);
}

bool good_enough(float guess, float x)
{
    return abs(guess * guess - x) < 0.001f;
}

float new_if(bool ret, float consequence, float nextConsequence)
{
    if (ret)
    {
        return consequence;
    }
    else
    {
        return nextConsequence;
    }
}

float sqart_iter(float guess, float x)
{
    return new_if(good_enough(guess, x), guess, sqart_iter(improve(guess, x), x));
}

int _tmain(int argc, _TCHAR* argv[])
{
    sqart_iter(1, 9);

    system("pause");
    return 0;
}

In C# ,we can use Lazy to show the lazy evaluation, but the normal C# is eager evaluation

public int Sum()
{
    int a = 0;
    int b = 0; 
    Lazy<int> x = new Lazy<int>(() => a + b);
    a = 3;
    b = 5;
    return x.Value; // returns 8
}