3

So I have a program that, currently, finds the fibonacci equivalent of a user inputted value, e.g. 6 would be 5 (or 13 depending on whether or not you start with a 0). Personally I prefer the sequence starting with 0.

    open System

    let rec fib (n1 : bigint)  (n2 : bigint) c =
        if c = 1 then
            n2
        else
            fib n2 (n1+n2) (c-1);;

    let GetFib n =
        (fib 1I 1I n);;

    let input = Console.ReadLine()
    Console.WriteLine(GetFib (Int32.Parse input))

The problem is that ALL it does is find the equivalent number in the sequence. I am trying to get it to print out all the values up to that user inputted value, e.g. 6 would print out 0,1,1,2,3,5. If anyone could help me figure out how to print out the whole sequence, that would be very helpful. Also if anyone can look at my code and tell me how to make it start at 0 when printing out the whole sequence, that would also be very much appreciated.

Thank you in advance for any help.

Marc Karam
  • 445
  • 6
  • 22
  • 1
    Before you print out something you need to generate it first, take a look at [Infinite Fibonacci Sequence](http://stackoverflow.com/questions/22914448/infinite-fibonacci-sequence) and others. – s952163 Sep 14 '16 at 03:38
  • See [Rosetta Code](http://www.rosettacode.org/wiki/Fibonacci_sequence#F.23). It's a great site for learning more about a language by example, especially as you can compare to solutions in other languages you might be more familiar with. – TheQuickBrownFox Sep 14 '16 at 09:06

1 Answers1

2

Take a look at the link s952163 gave you in the comments - that shows ways of generating a fibonnaci sequence using Seq expressions and also explains why these are useful.

The following will print a sequence up until the specified sequence number:

let fibsTo n = Seq.unfold (fun (m,n) -> Some (m, (n,n+m))) (0I,1I)  
              |>Seq.takeWhile (fun x -> x <= n)

let input = Console.ReadLine()

(fibsTo  (Numerics.BigInteger.Parse input))|>Seq.iter(printfn "%A")

Note the use of printfn rather than console.writeline, the former is more idiomatic.

Also, you may want to consider handling negative inputs here as these will throw an error.

Pash101
  • 631
  • 3
  • 14
  • 2
    Your `Seq.take(n)` should probably be `Seq.takeWhile (fun x -> x <= n)`; the OP was asking for "all Fibonacci numbers up to the specified number". He doesn't want the first `n` numbers of the sequence, he wants all numbers that are equal to or less than the specified cutoff number. – rmunn Sep 14 '16 at 12:11
  • Good point. I misinterpreted what the OP was asking for (and coincidentally, his input value of 6 should also return the first 6 elements of the sequence). – Pash101 Sep 15 '16 at 12:58