F# Basic Tutorial
F# Useful Resources
Selected Reading
- F# - Namespaces
- F# - Modules
- F# - Events
- F# - Interfaces
- F# - Inheritance
- F# - Operator Overloading
- F# - Structures
- F# - Classes
- F# - Exception Handling
- F# - Pattern Matching
- F# - Enumerations
- F# - Delegates
- F# - Generics
- F# - Basic I/O
- F# - Mutable Dictionary
- F# - Mutable Lists
- F# - Arrays
- F# - Mutable Data
- F# - Discriminated Unions
- F# - Maps
- F# - Sets
- F# - Sequences
- F# - Lists
- F# - Records
- F# - Tuples
- F# - Options
- F# - Strings
- F# - Functions
- F# - Loops
- F# - Decision Making
- F# - Operators
- F# - Variables
- F# - Data Types
- F# - Basic Syntax
- F# - Program Structure
- F# - Environment Setup
- F# - Overview
- F# - Home
F# Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
F# - Operator Overloading
F# - Operator Overloading
You can redefine or overload most of the built-in operators available in F#. Thus a programmer can use operators with user-defined types as well.
Operators are functions with special names, enclosed in brackets. They must be defined as static class members. Like any other function, an overloaded operator has a return type and a parameter pst.
The following example, shows a + operator on complex numbers −
//overloading + operator static member (+) (a : Complex, b: Complex) = Complex(a.x + b.x, a.y + b.y)
The above function implements the addition operator (+) for a user-defined class Complex. It adds the attributes of two objects and returns the resultant Complex object.
Implementation of Operator Overloading
The following program shows the complete implementation −
//implementing a complex class with +, and - operators //overloaded type Complex(x: float, y : float) = member this.x = x member this.y = y //overloading + operator static member (+) (a : Complex, b: Complex) = Complex(a.x + b.x, a.y + b.y) //overloading - operator static member (-) (a : Complex, b: Complex) = Complex(a.x - b.x, a.y - b.y) // overriding the ToString method override this.ToString() = this.x.ToString() + " " + this.y.ToString() //Creating two complex numbers let c1 = Complex(7.0, 5.0) let c2 = Complex(4.2, 3.1) // addition and subtraction using the //overloaded operators let c3 = c1 + c2 let c4 = c1 - c2 //printing the complex numbers printfn "%s" (c1.ToString()) printfn "%s" (c2.ToString()) printfn "%s" (c3.ToString()) printfn "%s" (c4.ToString())
When you compile and execute the program, it yields the following output −
7 5 4.2 3.1 11.2 8.1 2.8 1.9Advertisements