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)
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With