Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the recursive value null?

Tags:

f#

I'm F# beginner, I'm having this problem when I'm learning "recursive values".

type Type = 
    | N of int * Type
    | E

let rec a = N(2, b)
and b = N(3, E)

a |> printfn "%A"

I expect the output is:

N(2, N(3, E))

but the actual output is:

N (2,null)

output

like image 459
ChaoJie Sun Avatar asked Apr 29 '19 16:04

ChaoJie Sun


People also ask

Does a recursive function always return a value?

All functions - recursive or not - have one or more return . The return may or may not include a value. It is for you to decide when you write the function.

Why you shouldn't use recursion?

So even though recursion represented the algorithm in a natural way, it is very inefficient in this case. Thus, recursion may cause memory overflow if your stack space is large, and is also inefficient in cases where the same value is calculated again and again.

Why is recursion not infinite?

If a recursion never reaches a base case, it will go on making recursive calls forever and the program will never terminate. This is known as infinite recursion, and it is generally not considered a good idea. In most programming environments, a program with an infinite recursion will not really run forever.

What is the special about recursive function?

A recursive function is a function in code that refers to itself for execution. Recursive functions can be simple or elaborate. They allow for more efficient code writing, for instance, in the listing or compiling of sets of numbers, strings or other variables through a single reiterated process.


1 Answers

This is actually a bug in the F# compiler, filed here: https://github.com/fsharp/fsharp/issues/847

There has been no indication about when (or if) it will be fixed.

For your particular example, I would recommend simply removing the rec modifier: it is not needed, since the values aren't actually recursive. That will make the bug go away.

For more general case, you can create a system of mutually recursive functions for initialization, or simply a nested let block. For example, this should work:

let a, b =
    let rec a = N(2, b)
    and b = N(3, E)
    a, b
like image 186
Fyodor Soikin Avatar answered Sep 18 '22 08:09

Fyodor Soikin