7 people like it.

Fibonacci with Rabbit Mortality

Fibonacci function to calculate population after a given number of months (n) and mortality (m)

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
let fib5 (n : int64) (m : int64) = 
    let mutable dead: List<int64> = [1L; 1L]
    let mutable last = 0L
    let mutable next = 1L
    seq {
        1L
        for i in 1L .. (n - 1L) do
            if i < m
            then
                let temp = last + next
                dead <- dead @ [temp]
                last <- next
                next <- temp
                next
            else 
                if i = m
                then
                    let temp = last + next - dead.Item 0
                    dead <- dead.Tail
                    dead <- dead @ [temp]
                    last <- next
                    next <- temp
                    next
                else
                    let temp = last + next - dead.Item 0
                    dead <- dead.Tail
                    dead <- dead @ [temp]
                    last <- next
                    next <- temp
                    next
        }
        |> Seq.toArray
val fib5 : n:int64 -> m:int64 -> int64 []
val n : int64
Multiple items
val int64 : value:'T -> int64 (requires member op_Explicit)

--------------------
type int64 = System.Int64

--------------------
type int64<'Measure> = int64
val m : int64
val mutable dead : List<int64>
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
    interface IReadOnlyList<'T>
    interface IReadOnlyCollection<'T>
    interface IEnumerable
    interface IEnumerable<'T>
    member GetReverseIndex : rank:int * offset:int -> int
    member GetSlice : startIndex:int option * endIndex:int option -> 'T list
    member Head : 'T
    member IsEmpty : bool
    member Item : index:int -> 'T with get
    member Length : int
    ...
val mutable last : int64
val mutable next : int64
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>
val i : int64
val temp : int64
property List.Item: int -> int64 with get
property List.Tail: int64 list with get
module Seq

from Microsoft.FSharp.Collections
val toArray : source:seq<'T> -> 'T []
Raw view Test code New version

More information

Link:http://fssnip.net/88c
Posted:2 years ago
Author:Luke Limpert
Tags: fibonacci , mortality