Value or constructor not defined

I am studying f #, and I have a rather trivial problem that does not seem to make sense. I am working on a Project Euler 2 issue and I have this:

let fib (x : BigInteger) (y : BigInteger) (max : BigInteger) = let added = x + y if added > max then y else fib y (x + y) max 

I have an error when calling a recursive fic:

The value or constructor 'fib' is not defined

And I'm not sure why. Any help?

+8
f # fibonacci
source share
3 answers

Since fib is a recursive function, it should start with let rec .

+13
source share

In F #, if you want to write a recursive function, you must use the rec keyword :

 let rec fib (x : BigInteger) (y : BigInteger) (max : BigInteger) = let added = x + y if added > max then y else fib y (x + y) max 

This is because in F # under normal circumstances you can only use identifiers declared before the current code, unlike C #.

+7
source share

Speaking of Project Euler Problem 2 , you can consider instead of the recursion coming from Seq.unfold , which is very idiomatic and gives you all the Fibonacci numbers at once:

 let fibs = Seq.unfold (fun (current, next) -> Some(current, (next, current + next))) (1,2) 

Now fibs is a lazy sequence of Fibonacci numbers:

 >fibs;; val it : seq<int> = seq[1; 2; 3; 5; ...] 

And to do this, BigInteger simply substituting (1,2) for (1I,2I) , although this solution allows you to stay within ordinary integers.

+3
source share

All Articles