0 people like it.

Accumulate a value by applying a function - in two different styles

Two different approaches to the problem of starting with a value, applying a function to it n times, and accumulating a result.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
// Mutable and loop.
let accumulate (count : int) (f : 'T -> 'T) (initial : 'T) =
    let mutable acc = initial
    for _ in 1..count do
        acc <- f acc
    acc

// Recursion.
let accumulate2 (count : int) (f : 'T -> 'T) (initial : 'T) =
    let rec helper i acc =
        if i < count then
            helper (i + 1) (f acc)
        else
            acc
    helper 0 initial
val accumulate : count:int -> f:('T -> 'T) -> initial:'T -> 'T

Full name: Script.accumulate
val count : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val f : ('T -> 'T)
val initial : 'T
val mutable acc : 'T
val accumulate2 : count:int -> f:('T -> 'T) -> initial:'T -> 'T

Full name: Script.accumulate2
val helper : (int -> 'T -> 'T)
val i : int
val acc : 'T
Raw view Test code New version

More information

Link:http://fssnip.net/7Qc
Posted:8 years ago
Author:Kit Eason
Tags: recursion