###
Euler Project Problem 1 with F#

Maybe no better place like Euler project problems suitable for starting my F# journey.

Although have been programming a computer more than a decade, I still find present something involve a loop a little bit of strange. Why I should say for (i = 0; i<100; i++) do something?! The difference between an imperative programming language and my human language decrease my productivity. I want something is more similiar to my human language to present my idea and am eager to find a more natural way to write a program. At least F# solves the problem on how to present processing a data set.

Euler project problem 1 is to find the sum of all multiples of a 3 or 5 below 1000. I do not want to involve any for-loop or temporary variable in this case. Computer should be smart enough to translate my idea into a program. If there is a temporary variable needed for plumbing purpose, compiler should generate it for me, what I need is a sum of some numbers.

First of all, let us start to present a data set.

{ 1..999 } is the data set below 1000.

the problem only needs the number which is mulitple of 3 or 5, which means I need to filter it to get a sub-set. Let us do a definition of a number is multiple of 3 or 5.
let *isMultiple3Or5 *i = **i%3=0 || i%5=0**

the good part about this definition is that you do not have to specify *i *is what type, which is a big relief to my lazy brain. Data type is not part of my human language.

Now I got a data set and the fitering function, let F# to do the plumbing for me:

I use |> to input a data as a parameter into a function, the data is either I defined or some result from a function.

{ 1...999 } |> Seq.filter isMultiple3Or5 |> Seq.sum

{ 1...999 } as input into the Seq.filter function with isMultiple3Or5 as the filtering criteria. When the data comes out of the Seq.filter, only number which is multiple of 3 or 5 is left. The last step is to sum the new data set by applying Seq.sum.

That's the way I like to think and talk to a computer, how about you?

the following is the full program:

let isMultiple3Or5 i = i%3=0 || i%5=0

let sum = {1..999} |> Seq.filter isMultiple3Or5 |> Seq.sum

printfn "%A" sum

## No comments:

Post a Comment