I have been wanting to learn functional programming for real for a while now. I must say, it has been tough. Being used to procedural and object oriented programming languages like C, C#, and Java, I am used to being able to grasp new programming languages quite fast. But functional languagues, that's a completely different story.
In pure functional programming there are no variables, no states, none of the things you are used to in an object oriented language. It is like starting over from scratch.
Let me give you an example, assume you want to calculate the sum of all even numbers between 0 and 100 squared. How would you go about implementing that?
Well, I would define a variable, sum, that keeps track of the sum so far. Then I would create a for loop, for (int i = 2; i <= 100; i += 2), in which I add i * i to sum.
In functional programming however, you should avoid mutable values and loops. So what to do? Well here is one example on how you can do it in F#:
[0..100]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * 2)
|> List.sum
Slightly different, don't you think? This will be a challange...
In pure functional programming there are no variables, no states, none of the things you are used to in an object oriented language. It is like starting over from scratch.
Let me give you an example, assume you want to calculate the sum of all even numbers between 0 and 100 squared. How would you go about implementing that?
Well, I would define a variable, sum, that keeps track of the sum so far. Then I would create a for loop, for (int i = 2; i <= 100; i += 2), in which I add i * i to sum.
In functional programming however, you should avoid mutable values and loops. So what to do? Well here is one example on how you can do it in F#:
[0..100]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * 2)
|> List.sum
Slightly different, don't you think? This will be a challange...
Kommentarer
Skicka en kommentar