learning F#, it seems pretty cool, favourite functional language so far.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

folding.fsx 988B

1234567891011121314151617181920212223242526272829303132
  1. let printInt = printfn "%d"
  2. let product n =
  3. let initialValue = 1
  4. let action productSoFar x = productSoFar * x
  5. [1..n] |> List.fold action initialValue
  6. printInt (product 10)
  7. let sumOfOdds n =
  8. let initialValue = 0
  9. let action sumSoFar x = if x % 2 = 0 then sumSoFar else sumSoFar + x
  10. [1..n] |> List.fold action initialValue
  11. printInt (sumOfOdds 10)
  12. let alternatingSum n =
  13. let initialValue = (true, 0)
  14. let action (isNeg, sumSoFar) x = if isNeg then (false, sumSoFar - x) else (true, sumSoFar + x)
  15. [1..n] |> List.fold action initialValue |> snd // `snd` means the second in a tuple
  16. printInt (alternatingSum 100)
  17. // Now we can factor out the commonality and re-write these functions like so:
  18. let iterAct ini act n =
  19. [1..n] |> List.fold act ini
  20. let product2 = iterAct 1 (fun x y -> x * y)
  21. printInt (product2 10)
  22. let sumOfOdds2 = iterAct 0 (fun x y -> if y % 2 = 0 then x else x + y)
  23. printInt (sumOfOdds2 10)