principleMinor
Project Euler Problem 1 - Functional approach?
Viewed 0 times
problemprojecteulerfunctionalapproach
Problem
I'm trying to learn F# right now coming from C# and I'm finding it a great difficulty to "reconfigure" my mind to the functional programming mindset. So I'm going to attempt a few Project Euler problems to learn how to code functionally.
Here's my attempt at problem 1, now I'm wondering prorimarily, is this an idiomatic approach?
Here's my attempt at problem 1, now I'm wondering prorimarily, is this an idiomatic approach?
// Project Euler - Problem 1
// If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
// Find the sum of all the multiples of 3 or 5 below 1000.
#light
open System
let multiples = [for n in 1..1000 do if n % 3 = 0 || n % 5 = 0 then yield n]
let sum = List.sum multiples
printfn "The sum of all multiples are: %d" sum
ignore (Console.ReadKey ())Solution
Some changes:
You don't need
You don't need
#light any more. I would also use |> more (this is more useful in more complex examples where it helps type inference.open System
[for n in 1..1000 do if n % 3 = 0 || n % 5 = 0 then yield n]
|> List.sum
|> printfn "The sum of all multiples are: %d"
Console.ReadKey () |> ignoreCode Snippets
open System
[for n in 1..1000 do if n % 3 = 0 || n % 5 = 0 then yield n]
|> List.sum
|> printfn "The sum of all multiples are: %d"
Console.ReadKey () |> ignoreContext
StackExchange Code Review Q#68366, answer score: 5
Revisions (0)
No revisions yet.