advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
 

Working with Objects in F#

Learn how to use common object-oriented techniques in F# so that various shapes know how to calculate their own perimeter. 


advertisement
In the article "An Introduction to F# for Functional Programming" you saw an example of working with basic shapes and calculating the total perimeter of a drawing based on those shapes (see Listing 1). You did that by enumerating the kinds of base shapes that can exist (these were rectangles and circles) in your Shape class, providing a constructor for a square (a new shape) in terms of a rectangle, and adding an instance method to calculate the perimeter for a given shape.

There are times though when you want to extend the kind of shapes you are working with. What about triangles, hexagons or arbitrary polygons, for instance? While it is possible to enumerate these as special forms on a Shape type like you did in your first implementation, having to incorporate the perimeter logic into a single place is not ideal. Instead, you want to switch to a more traditional OO approach where the various shapes "know" how to calculate their own perimeter.


It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com.
Already a member?



advertisement