How to F # implement let rec?

I am wondering how F # implements let rec, and I could not find the answer. As a preface, I will look at how Scheme implements letrec:

  • In the diagram, it letis simply syntactic sugar for determining lambda and its application:

(let ((x 1)) (+ x 2))

converted to

((lambda (x) (+ x 2)) 1)

(in each case, the expression is evaluated as 3).

  1. letrecIt is also syntactic sugar, but it #fis passed as an initial argument to the lambda parameters, and expressions set!are entered in front of the body letrec, as in this transformation:

(letrec ((x 1)) (+ x 2)) => ((lambda (x) (begin (set! x 1) (+ x 2))) #f).

Given that F # does not have an equivalent operator for a Schema set!, how does it implement let rec? Does the function parameters indicate how mutableand then mutate them in the body of the function?

+4
source share
1 answer

In F #, let recit allows you to refer to a binding inside a function before it is bound. let recdoesn’t have an implementation as such, because this is just a compiler hint.

In this contrived example

let rec even =
    function 0 -> true  | 1 -> false | x -> odd (x - 1)
and odd =
    function 0 -> false | 1 -> true  | x -> even (x - 1)

compiled IL translates very secretly into:

public static bool even(int _arg1)
{
    switch (_arg1)
    {
    case 0:
        return true;
    case 1:
        return false;
    default:
        return odd(_arg1 - 1);
    }
}

public static bool odd(int _arg2)
{
    switch (_arg2)
    {
    case 0:
        return false;
    case 1:
        return true;
    default:
        return even(_arg2 - 1);
    }
}

All function definitions are statically compiled in IL. F # is ultimately a language that runs on the CLR. There is no meta programming.

+3
source

Source: https://habr.com/ru/post/1664092/


All Articles