DOCX

# Introduction to F#

By Arthur Kennedy,2014-09-21 13:44
23 views 0
Introduction to F#

Hands-On Lab Introduction to F#

Lab version: 1.0.0

Last updated: 9/21/2011

Page 1

CONTENTS

OVERVIEW ............................................................................................................................................. 3

EXERCISE 1: TYPES IN F# .................................................................................................................... 4

Task 1 Observing Type Inference in F# ........................................................................................... 4

Task 2 Working with Tuples ........................................................................................................... 6

Task 3 Functions as Values ............................................................................................................ 7

EXERCISE 2: USING THE “LET” KEYWORD IN F#............................................................................. 10

Task 1 Using the Let Keyword to Bind a Value to an Identifier ..................................................... 10

Task 2 Working with tuples and identifiers .................................................................................. 12 EXERCISE 3: FUNCTIONS ................................................................................................................... 16

Task 1 Binding Functions to Identifiers ........................................................................................ 16

Task 2 Binding Functions with Multiple Parameters .................................................................... 17

Task 3 Working with partially-applied functions .......................................................................... 19 EXERCISE 4: LISTS ............................................................................................................................. 21

Task 1 Creating Lists .................................................................................................................... 21

EXERCISE 5: PATTERN MATCHING AND RECURSION ..................................................................... 24

Task 1 Using Simple Pattern Matching to Output Information ..................................................... 25

Task 2 Using Simple Pattern Matching and Recursion to Implement the Fibonacci Sequence ...... 26

Task 3 Using Recursion with F# Lists ............................................................................................ 27 EXERCISE 6: TYPES AND DISCRIMINATED UNIONS ........................................................................ 28

Task 1 Creating a Simple Type in F# ............................................................................................. 29

Task 2 Creating a Discriminated Union ........................................................................................ 30

Task 3 Using Pattern Matching in Discriminated Unions .............................................................. 31 SUMMARY ............................................................................................................................................ 32

Page 2

Overview

F# is a new functional programming language from Microsoft. While it is primarily a functional programming language, it is known as a multi-paradigm language because it also supports object-oriented programming. F#’s tight integration with the entire .NET system of libraries and development

environment enables developers to bring the power of Functional Programming to the .NET platform. Objectives

In this Hands-On Lab, you will learn how to:

; Use F# Types

; Leverage the let keyword to bind values to identifiers

; Use functions in F#

; Use lists in F#

; Leverage Pattern Matching and Recursion

; Create your own types and consume discriminated unions

System Requirements

You must have the following items to complete this lab:

; Microsoft Visual Studio 2010

Setup

All the requisites for this lab are verified using the Configuration Wizard. To make sure that everything is

1. Run the Configuration Wizard for the Training Kit if you have not done it previously. To do this,

browse to Source\Setup folder of this lab, and double-click the Dependencies.dep file. Install

any pre-requisites that are missing (rescanning if necessary) and complete the wizard.

Note: The Configuration Wizard is used for checking dependencies and setting up the

environment. If the Configuration Wizard is not installed on your machine, you must install it

running the DependencyChecker.msi file located on

the %VS2010TKInstallationFolder%\Assets\DependencyChecker folder (e.g. by default the

Training Kit is installed under C:\VS2010TrainingKit).

Page 3

For convenience, much of the code you will be managing along this lab is available as Visual

Studio code snippets. The Dependencies.dep file launches the Visual Studio installer file that

installs the code snippets.

Exercises

This Hands-On Lab is comprised of the following exercises:

; Examine the basic F# types including tuples and functions

; Discover how the let keyword allows values to be bound to identifiers

; See that in F# functions are the same as any other value and are handled the same way.

Demonstrate how this allows advanced language features such as partially-applied functions

(also known as “curried” functions).

; Discover how F# lists are built and explore the power that can be achieved by F#’s “Head + Tail”

approach

; Demonstrate the powerful pattern matching and recursion capabilities of F#

; Demonstrate the usefulness of discriminated unions in F#

Estimated time to complete this lab: 60 minutes.

Next Steps

Exercise 1: Types in F#

Exercise 1: Types in F#

In this exercise, you will be introduced to the F# interactive console built into Visual Studio 2010. You will also learn how you can leverage F#’s type inference and will also be introduced to the concept of

“tuples”.

Task 1 Observing Type Inference in F#

In this task you will use the F# interactive console to see that F# is capable of inferring data type via the context in which is used.

Page 4

F# is a statically typed language that makes heavy use of type inference. When provided with a primitive

type (int, float, string, etc.) it’s able to infer the type the identifier refers to. 1. Open the Visual Studio 2010 Command Prompt from Start | All Programs | Microsoft Visual

Studio 2010 | Visual Studio Tools | Visual Studio 2010 Command Prompt

2. Launch F# Interface by launching fsi.exe:

Figure 1

The F# interactive console

3. Type the following command into the F# interactive console:

F#

42;;

Response

val it : int = 42

Note: The F# console will evaluate the value by determining its type and binding it to an

identifier called “it”.

4. Type the following command in the F# interactive console and press enter:

F#

Page 5

it;;

Response

val it : int = 42

Note: In absence of an identifier, the F# environment has bound the value to an identifier called “it”. This identifier is available to other code in the same interactive session.

5. At the command prompt in the F# interactive session enter the following command and press enter:

F#

42.0;;

Response

val it : float = 42.0

Note: By adding a decimal to your value F# has inferred that it is float.

6. At the command prompt in the F# interactive session type the following command and press enter:

F#

"42";;

Response

val it : string = "42"

Note: By enclosing your value in double quotes F# is able to infer that this value is a string.

Page 6

In this task, you will see how to work with tuples in F#. Tuples are structures in F# that allow developers

to ensure that two or more pieces of information are always presented together. This is useful in situations where it may not be sensible to separate data (i.e. a transaction amount, transaction date and

transaction ID number).

Note: In F#, a tuple is simply several values grouped together. Tuples are a fundamental type in F# and

can be used anywhere any other value would be used.

1. At the F# interactive command prompt type the following command and press enter:

F#

(42, "Hello F#");;

Response

val it : int * string = (42, "Hello F#")

Note: F# has inferred this value as a tuple. In this case, the tuple is composed of an integer

value and a string value. The type description shown in the interpreter (“int * string”) indicates

that there are two values in this tuple and that the first is an integer and the second is a string.

2. Tuples are not limited to pairs of values; they can contain as many values as are needed. Type

the following command into the F# interactive console and press enter:

F#

(42, "Hello F#", 42.0);;

Response

val it : int * string * float = (42, "Hello F#", 42.0)

Note: In this case, the tuple that was created is of type “int * string * float” or a structure that

takes an integer, a string and a float respectively.

In this task, you will see that functions in F# are values like any other and can be used in the exact same

way.

Page 7

Note: In F#, there is no distinction between values and functions because functions themselves are values. They are first-class citizens. As such, a function can be bound to an identifier just like any other value.

1. Type the command below at the F# interactive command prompt and press enter:

F#

fun x -> x + 1;;

Response

val it : int -> int =

2. Since the function that was created in the last step was bound to the it identifier, it can be

accessed via that identifier. Enter the following command at the F# interactive command

prompt:

F#

it 41;;

Response

val it : int = 42

Note: F# accessed the function that was bound to the “it” identifier and executed the function.

But how did F# know this was a function call? Unlike traditional Object-Oriented languages

that use parentheses and commas to denote function calls (i.e. “MyFunction (firstParam,

secondParam)”), F# knows that the first identifier is a function type (since functions are first-

class citizens in F#) and expects all parameters of a function call to be separated by spaces (i.e.

“MyFunction firstParam secondParam”).

Hence, the F# code “it 41” is telling F# to call the function bound to the identifier it and passing

it 41 as the first parameter.

3. As a side effect, the value returned from the function was itself bound to it. At the command

prompt, type the following command and press enter:

F#

it;;

Page 8

Response

val it : int = 42

Note: In this case you can see that the return value of 42 has been bound to the “it” identifier.

This means that your function is no longer bound the identifier “it” and therefore cannot be

used any longer. Well, that’s just a bit unfortunate. So, in the next section you will learn how

to bind values to identifiers that will allow you to access those values as needed.

Next Step

Exercise 2: Using the “Let” Keyword in F#

Page 9

Exercise 2: Using the “Let” Keyword in F#

Strictly speaking, functional languages like F# do not have variables. Instead, values are said to be bound to identifiers so that they may be referenced elsewhere in the program. Accordingly, the F# “let”

keyword allows you to assign any expression to an identifier.

In this exercise you learn how to use the let keyword to bind values to identifiers. Task 1 Using the Let Keyword to Bind a Value to an Identifier

1. If it is not already open, open the F# interactive console (see the beginning of Exercise 1 for

instructions)

2. Enter the following command at the F# interactive command prompt:

F#

let a = 42;;

Response

val a : int = 42

3. The value 42 is now accessible by the identifier a that it is bound to. To verify this, enter the

following command at the F# interactive console prompt:

F#

a;;

Response

val it : int = 42

Note: In functional languages like F#, instead of assigning a value to a variable, a value is said

to be bound to an identifier. This is because in pure functional languages once a value is

assigned to an identifier it never changes. If a developer binds a value to an identifier (i.e. “let

x = 42;;”) and then later in the same scope binds a new value to an identifier of the same name

(i.e. “let x = ‘forty two’”) F# creates a new identifier, and gives it the same name. The previous

identifier (in this case, the one bound to 42) still exists, but is no longer reachable.

Page 10

Report this document

For any questions or suggestions please email
cust-service@docsford.com