1234567891011121314151617181920212223242526272829303132 |
- let printInt = printfn "%d"
-
- let product n =
- let initialValue = 1
- let action productSoFar x = productSoFar * x
- [1..n] |> List.fold action initialValue
-
- printInt (product 10)
-
- let sumOfOdds n =
- let initialValue = 0
- let action sumSoFar x = if x % 2 = 0 then sumSoFar else sumSoFar + x
- [1..n] |> List.fold action initialValue
-
- printInt (sumOfOdds 10)
-
- let alternatingSum n =
- let initialValue = (true, 0)
- let action (isNeg, sumSoFar) x = if isNeg then (false, sumSoFar - x) else (true, sumSoFar + x)
- [1..n] |> List.fold action initialValue |> snd // `snd` means the second in a tuple
-
- printInt (alternatingSum 100)
-
- // Now we can factor out the commonality and re-write these functions like so:
- let iterAct ini act n =
- [1..n] |> List.fold act ini
-
- let product2 = iterAct 1 (fun x y -> x * y)
- printInt (product2 10)
-
- let sumOfOdds2 = iterAct 0 (fun x y -> if y % 2 = 0 then x else x + y)
- printInt (sumOfOdds2 10)
|