f-sharp
  1. f-sharp-arithmetic-operators

F# Arithmetic Operators

Arithmetic operators are used in F# to perform mathematical operations between two or more values. F# supports the basic arithmetic operators such as addition, subtraction, multiplication, and division.

Syntax

The syntax for using arithmetic operators in F# is:

value1 operator value2

Where, value1 and value2 are the two operands on which the operator will perform the operation.

Example

Here is an example of using the arithmetic operators in F#:

let x = 10
let y = 5

let sum = x + y          // Addition
let diff = x - y         // Subtraction
let prod = x * y         // Multiplication
let quot = x / y         // Division
let modu = x % y         // Modulus
let neg = -x             // Negation

printfn "Sum: %d" sum
printfn "Difference: %d" diff
printfn "Product: %d" prod
printfn "Quotient: %d" quot
printfn "Modulus: %d" modu
printfn "Negation: %d" neg

Output

Sum: 15
Difference: 5
Product: 50
Quotient: 2
Modulus: 0
Negation: -10

Explanation

In the example above, we have assigned two integer values to the variables x and y. We have then used the arithmetic operators to perform various mathematical operations on these values.

  • The + operator is used to add the values of x and y and store the result in the sum variable.
  • The - operator is used to subtract the value of y from x and store the result in the diff variable.
  • The * operator is used to multiply the values of x and y and store the result in the prod variable.
  • The / operator is used to divide the value of x by y and store the result in the quot variable.
  • The % operator is used to get the remainder of the division of x by y and store the result in the modu variable.
  • The - operator is used to negate the value of x and store the result in the neg variable.

Use

Arithmetic operators are commonly used in mathematical calculations, such as in calculating the total cost of items in a shopping cart, calculating the average of a set of numbers, or calculating the amount of interest on a loan.

Important Points

  • F# supports the basic arithmetic operators such as +, -, *, /, %, and -.
  • The mathematical operators perform mathematical operations on the operands based on the operator used.
  • Division by zero will result in a runtime error.
  • Integer division (/) will result in integer quotient (truncating the decimal portion of the result).
  • The mod operator calculates the remainder of the division.

Summary

In this tutorial, we have learned about arithmetic operators in F#. We have seen their syntax, example usage, output, explanation of each operator, important points to remember while working with them, and the use cases of arithmetic operators. With this knowledge, you should now be able to use arithmetic operators effectively in your F# programs.

Published on: