Foundamentals of Operations

Introduction

An operation is a combination of two or more items with the goal of producing a new result, reaching a concllusion, or making a decision. One or both items involved in an operation can be a constant value, a variable, a symbol or a combination of those.

Operators in F#

As a normal computer language, F# includes many operators that can be used to perform various types of operations. Most operators use only one symbol. Some operators use a combination of symbols. Some operators use words. The operators are:

&&& <| :: @ ! << (Functions Composition, Left) <<<
<> (Inequality) <> (Generic Records) | |> || >> (Functions Composition, Right) >>>
= (Assignment) ||| |> ^^^ : , && >= = (Equality)
> -> (Lambda Expression) -> (Delegate Creation) < <= - _ (Member Placeholder) +
** -> (Signature) ' (Single Quote) ' (Generic Records) <- ... :=
! .. " () % \ /

Unary Operations

A unary operator is a symbol that acts on a single value for its operation. There are various typsof unary operators with different goals.

A Coma

There are various ways a coma is used. As one way we saw already, a coma can be used to separate variable names and their values in a declaration. Here is an example we saw already:

let x, y, z = 16, 24, 58;

A Positive Value

One of the unary operators available is the + sign. It can be used to indicate that a number or a variable is positive. To indicate this, type the + (plus) operator to the left of a number of a variable.

A Negaitive Value

Another unary operator is the - (minus) operator. It is used to indicate that a number is negative or that a variable is holding a negative value. To indicate that a number is negative, add a - sign to its left.

The Equality Operators

Assigning a Variable

We already saw that, when you are declaring a variable, you must initialize it. This is done by using the assignment operator, =, to provide a value to it.

Updating a Reference Cell

The := operator is used to update a reference variable.

Accessing a Referenced Variable

The exclamation point, !, is used to access the value of a reference variable.

Updating a Mutable Variable

The <- operator is used to update a mutable variable.

Reading a Line of Value(s)

Athough most of the values your application displays will come from you, in many cases you will want the users to provide one or more values on which you want to perform some operations. In this type of scenario, you will want to request and get one or more values from the user. To let you do this, the F# language provides an expression as stdin.ReadLine(). To get a value from a user, you can declare a variable and assign this expression to that variable. Here is an example:

let name = stdin.ReadLine();

When this code executes, the window display a caret, expecting the user to type something, but nothing indicates to the user what to type. Therefore, you should precede the above line by a printf string that indicates to the user what is expected. Here is an example:

printf "First Name: "
let firstName = stdin.ReadLine();

Operations on Integers

Coverting a Value to an Integer

By default, when you request a value from the user, the value the user types is a string. If you want to use such a value as a number and involve it in an arithmetic operatlon, you must first convert that value. If the value must be onverted to an integer, type int followed by the value to cconvert. You can assign that expression to an integer variable. Here is an example:

let strYearlySalary = int "45000"

printfn "Yearly Salary %i" strYearlySalary

This would produce:

Yearly Salary 45000

Press any key to close this window . . .

In the above example, we converted a constant value. In most cases, the value you want to convert will come from another part of the program or even from another application. Probably the most type of value you deal with will come from the user. We saw that this is done a stdin.ReadLine() expression, and we saw that you could assign that expression to a string variable. Here is an example:

printfn "Enter the following pieces of information"
printf "Employee Name: "
let emplName = stdin.ReadLine()

printf "Yearly Salary: "
let strYearlySalary = stdin.ReadLine()
printfn "=============================="

printfn "Employee Record"
printfn "------------------------------"
printfn "Employee Name: %s" emplName
printfn "Yearly Salary: %s" strYearlySalary

Here is an example of running the program:

Enter the following pieces of information
Employee Name: Jules Fein
Yearly Salary: 42680
==============================
Employee Record
------------------------------
Employee Name: Jules Fein
Yearly Salary: 42680

Press any key to close this window . . .

If a value is stored in a string variable and you want to convert that value to an integer, you can type that variable after int. After doing that, if the conversion is successful, you can use the new value in its new converted number. This can be done as follows:

printfn "Enter the following pieces of information"
printf "Employee Name: "
let emplName = stdin.ReadLine()

printf "Yearly Salary: "
let strYearlySalary = stdin.ReadLine()
let yearlySalary = int strYearlySalary
printfn "=============================="

printfn "Employee Record"
printfn "------------------------------"
printfn "Employee Name: %s" emplName
printfn "Yearly Salary: %i" yearlySalary

Of course, after performing the converssion, you can involve the new variable in any appropriate operation.

Calling Into an Integer

In the above code, we first declared a string variable to hold a value from a stdin.ReadLine() expression. F# provides a shortcut. You can provide the stdin.ReadLine() expression directly to the int operator. But, you must add parentheses to int, as in int(). In those parentheses, enter the stdin.ReadLine() expression. Therefore, the above code can be written as follows:

printfn "Enter the following pieces of information"
printf "Employee Name: "
let emplName = stdin.ReadLine()

printf "Yearly Salary: "
let yearlySalary = int(stdin.ReadLine())
printfn "=============================="

printfn "Employee Record"
printfn "------------------------------"
printfn "Employee Name: %s" emplName
printfn "Yearly Salary: %i" yearlySalary

Arithmetic Operations

Integral numbers support all the regular arithmetic operators learned in elementary school:

Real Numbers

Arithmetic Operations

Real numbers support the regular arithmetic operators that are the addition, the subtraction, the multiplication, and the division.

Converting a Value to Decimal

We already saw how to request a regular value from the user, which is done with a stdin.ReadLine() expression. We also saw that, if you are planning to use the value as a number, you must convert it. When it comes to decimal numbers, if you want to treat the value as such, you can convert it using the float type. Here is an example:

printfn "Enter the following pieces of information"
printf "Employee Name: "
let emplName = stdin.ReadLine()

printf "Hourly Salary: "
let strHourlySalary = stdin.ReadLine()
let hourlySalary = float strHourlySalary
printfn "=============================="

printfn "Employee Record"
printfn "------------------------------"
printfn "Employee Name: %s" emplName
printfn "Hourly Salary: %f" hourlySalary

Here is an example of running the program:

Enter the following pieces of information
Employee Name: James Finley
Hourly Salary: 22.58
==============================
Employee Record
------------------------------
Employee Name: James Finley
Hourly Salary: 22.580000

Press any key to close this window . . .

Once again, instead of first storing the value in a string variable, you apply directly to the float type. You must add parentheses to float, as in float(). In the parentheses, type the stdin.ReadLine() expression. Here is an example:

printfn "Enter the following pieces of information"
printf "Employee Name: "
let emplName = stdin.ReadLine()

printf "Hourly Salary: "
let hourlySalary = float(stdin.ReadLine())
printfn "=============================="

printfn "Employee Record"
printfn "------------------------------"
printfn "Employee Name: %s" emplName
printfn "Hourly Salary: %f" hourlySalary

The Power of a Number

Decimal numbers support the operation that consists of raising one number to the power of another number. This is done using the ** operator. Here is an example:

let a = 8.25;
let b = 5.14;
let power = a ** b;

printfn "%.2f raised to %.2f = %.2f" a b power;

This would produce:

8.25 raised to 5.14 = 51353.88

Press any key to close this window . . .

This operation is not supported on natural numbers. If you want to perform it on integers, simply add .00 to each number.

Options on Variables

Mutable Variables

When you declare and initialize a variable by binding it to a constant value, the compiler reserves memory for that variable and stores the value in the reserved memory. Here are examples:

let firstName = "Mark";
let lastName  = "Lambert";

printfn "First Name %s" firstName;
printfn "Last Name: %s" lastName;

This would produce:

First Name Mark
Last Name: Lambert

Press any key to close this window . . .

Normally, you cannot change the value of a variable after it has been declared and initialized. That is, you cannot remove the value in that reserved memory to replace it with another value. Consider the following example:

let firstName = "Mark";
let lastName  = "Lambert";

printfn "First Name %s" firstName;
printfn "Last Name: %s" lastName;

lastName  = "Alley";
printfn "Last Name: %s" lastName;

Notice that the variable lastName changes value. The above program would produce:

First Name Mark
Last Name: Lambert
Last Name: Lambert

Press any key to close this window . . .

Notice that the lastName variable is given a new value the second time but when that variable is accessed a second time, it still has its original value. The variable is said to be immutable: its value cannot change after it has been initialized.

If you want to be able to change the value of a variable, you must indicate that it is mutable. To do this, when declaring the variable, precede it with the mutable keyword. Here is an example:

let mutable lastName = "Lambert";

You can then use the variable any way you want. When a variable has been declared mutable, you can change its value by assigning another value to it. To do this, instead of =, use the <- operator.

Practical LearningPractical Learning: Introducing Mutable Variables

  1. Type the following lines of code:
    let firstName = "Mark";
    let mutable lastName  = "Lambert";
    
    printfn "First Name %s" firstName;
    printfn "Last Name: %s" lastName;
    
    lastName <- "Alley";
    
    printfn "First Name %s" firstName;
    printfn "Last Name: %s" lastName;
  2. To execute and see the result, on the main menu, click Debug -> Start Without Debugging:
    First Name Mark
    Last Name: Lambert
    First Name Mark
    Last Name: Alley
    
    Press any key to close this window . . .
  3. Press Enter to close the window and return to Microsoft Visual Studio

Reference Cells

The values you declare in your programs are stored in the computer memory when your application starts. Every one of those values has or uses an address as its location. The compiler can refer to that address to locate the variable and use its value. You too can get a reference to that address and use it as you see fit. For example, you can change the value of the variable located at a particular address.

To get a reference to a variable, you use the ref keyword. To use it, when declaring a variable, add this keyword between = and the initial value stored in the variable. Here is an example:

let x = ref 16

To get the value to which the variable refers, you must dereference the variable. This is done by applying the ! operator to the name of the variable. Here is an example:

let price = ref 45.00;

printfn "Item Price: $%0.02f\n" !price;

This would produce:

Item Price: 45.00

Press any key to close this window . . .

When necessary, you can change the value of the variable by assigning another value to it. This is done using the := operator. Here is an example:

let price = ref 45.00;

printfn "Item Price: $%0.02f" !price;
     
price := 38.75;

printfn "Discount Price: $%0.02f\n" !price;

This would produce:

Item Price: $45.00
Discount Price: $38.75

Press any key to close this window . . .

This feature works likt that of mutable variables and allows you to declare a variable whose value you plan to change while the program is running.

Bitwise Operations

Introduction

A bitwise operation consists of adding or removing (actually replacing or switching) the 1 and 0 values stored in the computer memory.

Adding Two Bits for Conjunction

To add two bits, use the &&& operator. This operation is called the bitwise-AND operator. Here is an example of applying this operator:

let a = 248;
let b = 125;
let bitwise = a &&& b;

printfn "The bitwise-AND operation between %d AND %d is %d" a b bitwise;

This would produce:

The bitwise-AND operation between 248 AND 125 is 120

Press any key to close this window . . .

Adding Two Bits for Disjunction

The bitwise OR operation consists of reversing the value of a bit. During this operator, if the value of a bit is 1, it is changed to 0, and vice-versa. To perform this operation, use the ||| operator. Here is an example:

let a = 248;
let b = 125;
let bitwise = a ||| b;

printfn "The bitwise-OR operation between %d and %d is %d" a b bitwise;

This would produce:

The bitwise-OR operation between 248 and 125 is 253

Press any key to close this window . . .

Adding Two Bits for Exclusion

To perform a bitwise XOR operation, use the ^^^ operator.

Byte-Shift Operations

Introduction

The F# language supports operations that consist of moving the values, namely 0 or 1, stored in the bits of the computer memory.

Shifting a Number of Bytes to the Left

To shift a certain number of bytes from a number (actually the memory area where a number is stored) to its left in the computer memory, use the <<< operator. Here is an example:

let a = 248;
let b = 5;
let leftShift = a <<< b;

printfn "%d shifted to the left by %d bytes is %d" a b leftShift;
This would produce:
248 shifted to the left by 5 bytes is 7936

Press any key to close this window . . .

Shifting a Number of Bytes to the Right

The >>> operator is used to shift a certain number of bytes from a number to its right.


Previous Copyright © 2009-2024, FunctionX Monday 14 February 2016 Next