To calculate the area of โโthe square and the circle, I defined the following type:
type Square = {width: float; length: float;} with member this.area = this.width * this.length member this.perimeter = (this.width + this.length) * 2. type Circle = {r:float} with member this.area = System.Math.PI * this.r * this.r member this.perimeter = 2. * System.Math.PI * this.r let s1 = {width = 3.; length = 4.} let c1 = {r = 8.3} printfn "%A" s1 printfn "The area of s1 is: %A" s1.area printfn "The perimeter of s1 is: %A" s1.perimeter printfn "%A" c1 printfn "The area of c1 is: %A" c1.area printfn "The perimeter of c1 is: %A" c1.perimeter
When I read this article: http://fsharpforfunandprofit.com/posts/type-extensions/
It states:
- Methods do not work well with output type
- Methods do not work well with higher order functions
So, a plea for you, new to functional programming. Do not use methods if you can, especially when you are studying. They have a crutch that will stop you, taking full advantage of functional programming.
Then what is a functional way to solve this problem? or what is the F # ideal way?
Edit
After reading the F # Component Design Guide (curtsy to @VB) and the @JacquesB comment, I believe that implementing a member method inside this type is the easiest, internal way:
type Square2 (width: float, length: float) = member this.area = width * length member this.perimeter = (width + length) * 2.
(This is almost identical to my original Square type - this Square2 only saves the prefix seveal this. As in this.width , this.length .)
Again, the F # Component Design Guide is quite helpful.
source share