learning F#, it seems pretty cool, favourite functional language so far.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

folding.fsx 990B

12345678910111213141516171819202122232425262728293031323334
  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)