SlideShare a Scribd company logo
Chapter 7
Console Class
F# - Basic I/O
Console
Class
Basic I/O
System.IO
Files &
Directories
Streams
F# - Basic I/O
• Basic Input Output includes −
1. Reading from and writing into console.
2. Reading from and writing into file.
Core.Printf Module
• We have used the various form of functions for writing into
the console such as printf and the printfn.
• Apart from the above functions, we have also seen
the Core.Printf module of F# which has various other
methods for printing and formatting using % markers as
placeholders.
Core.Printf Module
printf : TextWriterFormat<'T> → 'T Prints formatted output to stdout.
printfn : TextWriterFormat<'T> → 'T Prints formatted output to stdout, adding
a newline.
sprintf : StringFormat<'T> → 'T Prints to a string by using an internal
string buffer and returns the result as
a string.
fprintfn : TextWriter →
TextWriterFormat<'T> → 'T
Prints to a text writer, adding a newline.
fprintf : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer.
Core.Printf Module
bprintf : StringBuilder → BuilderFormat<'T> →
'T
Prints to a StringBuilder.
eprintf : TextWriterFormat<'T> → 'T Prints formatted output to stderr.
eprintfn : TextWriterFormat<'T> → 'T Prints formatted output to stderr,
adding a newline.
fprintf : TextWriter → TextWriterFormat<'T> →
'T
Prints to a text writer.
fprintfn : TextWriter → TextWriterFormat<'T>
→ 'T
Prints to a text writer, adding a
newline.
Format Specifications
• Used for formatting the input or output,
• These are strings with % markers indicating format
placeholders.
• The syntax of a Format placeholders is −
%[flags][width][.precision]type
Format Specifications
printfn "d: %10d" 212
printfn “%010d” 212
Flag
Type
Type Description
%b Formats a bool, formatted as true or false.
%c Formats a character.
%s Formats a string, formatted as its contents, without interpreting any
escape characters.
%d, %i Formats any basic integer type formatted as a decimal integer, signed
if the basic integer type is signed.
%u Formats any basic integer type formatted as an unsigned decimal
integer.
%x Formats any basic integer type formatted as an unsigned
hexadecimal integer, using lowercase letters a through f.
%X Formats any basic integer type formatted as an unsigned
hexadecimal integer, using uppercase letters A through F.
Type
Type Description
%o Formats any basic integer type formatted as an unsigned octal integer.
%e, %E, %f,
%F, %g, %G
Formats any basic floating point type (float, float32) formatted using a C-style floating point format
specifications.
%e, %E Formats a signed value having the form [-]d.dddde[sign]ddd where d is a single decimal digit, dddd is one or
more decimal digits, ddd is exactly three decimal digits, and sign is + or -.
%f Formats a signed value having the form [-]dddd.dddd, where dddd is one or more decimal digits. The number of
digits before the decimal point depends on the magnitude of the number, and the number of digits after the
decimal point depends on the requested precision.
%g, %G Formats a signed value printed in f or e format, whichever is more compact for the given value and precision.
%M Formats a Decimal value.
%O Formats any value, printed by boxing the object and using its ToString method.
%A, %+A Formats any value, printed with the default layout settings. Use %+A to print the structure of discriminated
unions with internal and private representations.
Width
Value Description
0 Specifies to add zeros instead of spaces to make up the required width.
- Specifies to left-justify the result within the width specified.
+ Specifies to add a + character if the number is positive (to match a - sign for
negative numbers).
' ' (space) Specifies to add an extra space if the number is positive (to match a - sign for
negative numbers).
# Invalid.
• The width is an optional parameter.
• It is an integer that indicates the minimal width of the result.
• For example, %5d prints an integer with at least spaces of 5 characters.
Width &Flag
Flag Value Description
0 Specifies to add zeros instead of spaces to make up the required width.
- Specifies to left-justify the result within the width specified.
+ Specifies to add a + character if the number is positive (to match a - sign for
negative numbers).
' ' (space) Specifies to add an extra space if the number is positive (to match a - sign for
negative numbers).
# Invalid.
• The width is an optional parameter.
• It is an integer that indicates the minimal width of the result.
• For example, %5d prints an integer with at least spaces of 5 characters.
Precision (optional)
• Represents the number of digits after a floating point number.
printf "%.2f" 12345.67890 O/P 12345.67
printf "%.7f" 12345.67890 O/P 12345.6789000
Read/Write Using Console Class
• We can read and write to the console
using the System.Console class
1. ReadLine
2. Write
3. WrileLine
Example
open System
let main() =
Console.Write(“Enter your name: ")
let name = Console.ReadLine()
Console.Write("Hello,{0}", name)
main()
Example:Date
open System
let main() =
Console.WriteLine(System.String.Format("|{0:yy
yy-MMM-dd}|", System.DateTime.Now))
main()
Method
Read Reads the next character from the standard input
stream.
ReadKey() Obtains the next character or function key
pressed by the user. The pressed key is displayed
in the console window.
Clear Clears the console buffer and corresponding
console window
System.IO Namespace
Files and Directories
System.IO.File
System.IO.Directory
System.IO.Path
System.IO.FileSystemWatcher
System.IO Namespace :streams
streams
System.IO.StreamReader
System.IO.StreamWriter
System.IO.MemoryStream
open System.IO
type Data() =
member x.Read() =
// Read in a file with StreamReader.
use stream = new StreamReader @"E:Fprogfile.txt"
// Continue reading while valid lines.
let mutable valid = true
while (valid) do
let line = stream.ReadLine()
if (line = null) then
valid <- false
else
// Display line.
printfn "%A" line
// Create instance of Data and Read in the file.
let data = Data()
data.Read()
Reading from File And Display the
content line by line
Use: ensures the
StreamReader is correctly
disposed of when it is no
longer needed.
• This is a simpler way to read all the lines in a file, but
it may be less efficient on large files.
• ReadAllLines returns an array of strings.
• We use Seq.toList to get a list from the array.
• And with Seq.where we get a sequence of only
capitalized lines in the list.
File.ReadAllLines
open System
open System.IO
let lines = File.ReadAllLines(@“E:Fprogfile.txt")
// Convert file lines into a list.
let list = Seq.toList lines
printfn "%A" list
// Get sequence of only capitalized lines in list.
let uppercase = Seq.where (fun (n : String) -> Char.IsUpper(n, 0)) list
printfn "%A" uppercase
ABC
abc
Cat
Dog
bird
fish
File.txt
O/P
["ABC"; "abc"; "Cat"; "Dog"; "bird"; "fish"]
seq ["ABC"; "Cat"; "Dog"]
open System.IO // Name spaces can be opened just as modules
File.WriteAllText("test.txt", "Hello Theren Welcome All”)
let msg = File.ReadAllText("test.txt")
printfn "%s" msg
Creates a file called test.txt, writes a message there, reads the text from the
file and prints it on the console.
Delegates in F#
• A special function that encapsulate a method and
represents a method signature.
• Similar to pointers to functions in C or C++.
• A reference type variable that holds the address of
functions.
• The reference can be changed at runtime.
• Used for implementing events and call-back
functions.
Delegates in F#
• A delegate is referred to as type-safe function
pointers,
• If the method with two int parameters and a return
type is an int then the delegate that you are declaring
should also have the same signature.
• That is why a delegate is referred to as type-safe
function.
3 ways to define Delegates
Methods
Declaration
Instantiation
Invocation
Types of Delegates
Delegates Types
Simple Delegate Multicast Delegate
Delegates in F# :Syntax
type delegate-typename = delegate of type1 -> type2
// Delegate1 works with tuple arguments.
type Delegate1 = delegate of (int * int) -> int
// Delegate2 works with curried arguments.
type Delegate2 = delegate of int * int -> int
Syntax
Both the delegates can be used to reference any method that has
two int parameters and returns an int type variable.
argument type(s). return type.
Point to Remember
• Delegates can be attached to function values, and static
or instance methods.
• F# function values can be passed directly as arguments to
delegate constructors.
• For a static method the delegate is called by using the
name of the class and the method.
• For an instance method, the name of the object instance
and method is used.
Point to Remember
• The Invoke method on the delegate type calls the
encapsulated function.
• Also, delegates can be passed as function values by
referencing the Invoke method name without the
parentheses.
Example: Implementation of Add & Sub operation using
Delegates
1. Define two types of Methods : Static & Instance
2. Define Delegates
3. Invoke delegates
4. Calling static method using delegates
5. Calling Instance method using delegates
6. Calling Delegates
Method Defining-Static & Instance
type Test1() =
static member add(a : int, b : int) =
a + b
static member sub(a : int) (b : int) =
a - b
member x.Add(a : int, b : int) =
a + b
member x.Sub(a : int) (b : int) =
a - b
Defining Delegates
// Delegate1 works with tuple arguments.
type Delegate1 = delegate of (int * int) -> int
// Delegate2 works with curried arguments.
type Delegate2 = delegate of int * int -> int
Invoking Delegates
let InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) =
dlg.Invoke(a, b)
let InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) =
dlg.Invoke(a, b)
Calling static Method
// For static methods, use the class name, the dot operator, and the name of the
static method.
let del1 : Delegate1 = new Delegate1( Test1.add )
let del2 : Delegate2 = new Delegate2( Test1.sub )
For Instance Method
// For instance methods, use the instance value name,
the dot operator, and the instance method name.
let testObject = Test1()
let del3 : Delegate1 = new Delegate1( testObject.Add )
let del4 : Delegate2 = new Delegate2( testObject.Sub )
Calling Delegates
for (a, b) in [ (100, 200); (10, 20) ] do
printfn "%d + %d = %d" a b (InvokeDelegate1 del1 a b)
printfn "%d - %d = %d" a b (InvokeDelegate2 del2 a b)
printfn "%d + %d = %d" a b (InvokeDelegate1 del3 a b)
printfn "%d - %d = %d" a b (InvokeDelegate2 del4 a b)

More Related Content

PPT
Data type in c
PDF
Python unit 2 as per Anna university syllabus
PPT
02a fundamental c++ types, arithmetic
PPS
C programming session 05
PPTX
PPTX
Memory management of datatypes
PDF
Python Programming
Data type in c
Python unit 2 as per Anna university syllabus
02a fundamental c++ types, arithmetic
C programming session 05
Memory management of datatypes
Python Programming

What's hot (17)

PPS
C programming session 02
PPT
pointer, structure ,union and intro to file handling
PPTX
Functional programming with FSharp
PPT
Basics of c++
PDF
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
PPTX
CSharp Language Overview Part 1
PPTX
C# overview part 1
PPS
C programming session 01
PPS
C programming session 08
PPT
Getting started with c++
PPTX
function, storage class and array and strings
PPS
C programming session 04
PDF
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
PDF
Functions, Strings ,Storage classes in C
PPTX
Presentation 5th
PDF
Lesson 03 python statement, indentation and comments
PDF
2 expressions (ppt-2) in C++
C programming session 02
pointer, structure ,union and intro to file handling
Functional programming with FSharp
Basics of c++
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
CSharp Language Overview Part 1
C# overview part 1
C programming session 01
C programming session 08
Getting started with c++
function, storage class and array and strings
C programming session 04
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
Functions, Strings ,Storage classes in C
Presentation 5th
Lesson 03 python statement, indentation and comments
2 expressions (ppt-2) in C++
Ad

Similar to F# Console class (20)

PPSX
Esoft Metro Campus - Certificate in c / c++ programming
PPTX
basic C PROGRAMMING for first years .pptx
PPTX
Each n Every topic of C Programming.pptx
PPTX
C programming(part 3)
PPTX
the refernce of programming C notes ppt.pptx
PPT
Introduction to C Programming
PPT
Unit 4 Foc
PPT
Stream Based Input Output
PDF
Chapter Functions for grade 12 computer Science
PPTX
c programming session 1.pptx
PPTX
C_Programming_Language_tutorial__Autosaved_.pptx
PPT
Chapter2pp
PPTX
C Programming - Basics of c -history of c
PDF
The New Yorker cartoon premium membership of the
PPTX
programming concepts with c ++..........
PPTX
Functions.pptx, programming language in c
PPTX
Learn Python The Hard Way Presentation
PPTX
MODULE. .pptx
PDF
Module_1_Introduction-to-Problem-Solving.pdf
PPT
Chapter3
Esoft Metro Campus - Certificate in c / c++ programming
basic C PROGRAMMING for first years .pptx
Each n Every topic of C Programming.pptx
C programming(part 3)
the refernce of programming C notes ppt.pptx
Introduction to C Programming
Unit 4 Foc
Stream Based Input Output
Chapter Functions for grade 12 computer Science
c programming session 1.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
Chapter2pp
C Programming - Basics of c -history of c
The New Yorker cartoon premium membership of the
programming concepts with c ++..........
Functions.pptx, programming language in c
Learn Python The Hard Way Presentation
MODULE. .pptx
Module_1_Introduction-to-Problem-Solving.pdf
Chapter3
Ad

More from DrRajeshreeKhande (20)

PPTX
.NET F# Inheritance and operator overloading
PPTX
Exception Handling in .NET F#
PPTX
.NET F# Events
PPTX
.NET F# Class constructor
PPTX
.NET F# Abstract class interface
PPTX
.Net F# Generic class
PPTX
.net F# mutable dictionay
PPTX
F sharp lists & dictionary
PPTX
F# array searching
PPTX
Net (f#) array
PPTX
.Net (F # ) Records, lists
PPT
MS Office for Beginners
PPSX
Java Multi-threading programming
PPSX
Java String class
PPTX
JAVA AWT components
PPSX
Dr. Rajeshree Khande :Introduction to Java AWT
PPSX
Dr. Rajeshree Khande Java Interactive input
PPSX
Dr. Rajeshree Khande :Intoduction to java
PPSX
Java Exceptions Handling
PPSX
Dr. Rajeshree Khande : Java Basics
.NET F# Inheritance and operator overloading
Exception Handling in .NET F#
.NET F# Events
.NET F# Class constructor
.NET F# Abstract class interface
.Net F# Generic class
.net F# mutable dictionay
F sharp lists & dictionary
F# array searching
Net (f#) array
.Net (F # ) Records, lists
MS Office for Beginners
Java Multi-threading programming
Java String class
JAVA AWT components
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande :Intoduction to java
Java Exceptions Handling
Dr. Rajeshree Khande : Java Basics

Recently uploaded (20)

PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Basic Mud Logging Guide for educational purpose
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Insiders guide to clinical Medicine.pdf
PPH.pptx obstetrics and gynecology in nursing
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
TR - Agricultural Crops Production NC III.pdf
Anesthesia in Laparoscopic Surgery in India
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Cell Types and Its function , kingdom of life
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Basic Mud Logging Guide for educational purpose
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Insiders guide to clinical Medicine.pdf

F# Console class

  • 2. F# - Basic I/O Console Class Basic I/O System.IO Files & Directories Streams
  • 3. F# - Basic I/O • Basic Input Output includes − 1. Reading from and writing into console. 2. Reading from and writing into file.
  • 4. Core.Printf Module • We have used the various form of functions for writing into the console such as printf and the printfn. • Apart from the above functions, we have also seen the Core.Printf module of F# which has various other methods for printing and formatting using % markers as placeholders.
  • 5. Core.Printf Module printf : TextWriterFormat<'T> → 'T Prints formatted output to stdout. printfn : TextWriterFormat<'T> → 'T Prints formatted output to stdout, adding a newline. sprintf : StringFormat<'T> → 'T Prints to a string by using an internal string buffer and returns the result as a string. fprintfn : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer, adding a newline. fprintf : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer.
  • 6. Core.Printf Module bprintf : StringBuilder → BuilderFormat<'T> → 'T Prints to a StringBuilder. eprintf : TextWriterFormat<'T> → 'T Prints formatted output to stderr. eprintfn : TextWriterFormat<'T> → 'T Prints formatted output to stderr, adding a newline. fprintf : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer. fprintfn : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer, adding a newline.
  • 7. Format Specifications • Used for formatting the input or output, • These are strings with % markers indicating format placeholders. • The syntax of a Format placeholders is − %[flags][width][.precision]type
  • 8. Format Specifications printfn "d: %10d" 212 printfn “%010d” 212 Flag
  • 9. Type Type Description %b Formats a bool, formatted as true or false. %c Formats a character. %s Formats a string, formatted as its contents, without interpreting any escape characters. %d, %i Formats any basic integer type formatted as a decimal integer, signed if the basic integer type is signed. %u Formats any basic integer type formatted as an unsigned decimal integer. %x Formats any basic integer type formatted as an unsigned hexadecimal integer, using lowercase letters a through f. %X Formats any basic integer type formatted as an unsigned hexadecimal integer, using uppercase letters A through F.
  • 10. Type Type Description %o Formats any basic integer type formatted as an unsigned octal integer. %e, %E, %f, %F, %g, %G Formats any basic floating point type (float, float32) formatted using a C-style floating point format specifications. %e, %E Formats a signed value having the form [-]d.dddde[sign]ddd where d is a single decimal digit, dddd is one or more decimal digits, ddd is exactly three decimal digits, and sign is + or -. %f Formats a signed value having the form [-]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision. %g, %G Formats a signed value printed in f or e format, whichever is more compact for the given value and precision. %M Formats a Decimal value. %O Formats any value, printed by boxing the object and using its ToString method. %A, %+A Formats any value, printed with the default layout settings. Use %+A to print the structure of discriminated unions with internal and private representations.
  • 11. Width Value Description 0 Specifies to add zeros instead of spaces to make up the required width. - Specifies to left-justify the result within the width specified. + Specifies to add a + character if the number is positive (to match a - sign for negative numbers). ' ' (space) Specifies to add an extra space if the number is positive (to match a - sign for negative numbers). # Invalid. • The width is an optional parameter. • It is an integer that indicates the minimal width of the result. • For example, %5d prints an integer with at least spaces of 5 characters.
  • 12. Width &Flag Flag Value Description 0 Specifies to add zeros instead of spaces to make up the required width. - Specifies to left-justify the result within the width specified. + Specifies to add a + character if the number is positive (to match a - sign for negative numbers). ' ' (space) Specifies to add an extra space if the number is positive (to match a - sign for negative numbers). # Invalid. • The width is an optional parameter. • It is an integer that indicates the minimal width of the result. • For example, %5d prints an integer with at least spaces of 5 characters.
  • 13. Precision (optional) • Represents the number of digits after a floating point number. printf "%.2f" 12345.67890 O/P 12345.67 printf "%.7f" 12345.67890 O/P 12345.6789000
  • 14. Read/Write Using Console Class • We can read and write to the console using the System.Console class 1. ReadLine 2. Write 3. WrileLine
  • 15. Example open System let main() = Console.Write(“Enter your name: ") let name = Console.ReadLine() Console.Write("Hello,{0}", name) main()
  • 16. Example:Date open System let main() = Console.WriteLine(System.String.Format("|{0:yy yy-MMM-dd}|", System.DateTime.Now)) main()
  • 17. Method Read Reads the next character from the standard input stream. ReadKey() Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window. Clear Clears the console buffer and corresponding console window
  • 18. System.IO Namespace Files and Directories System.IO.File System.IO.Directory System.IO.Path System.IO.FileSystemWatcher
  • 20. open System.IO type Data() = member x.Read() = // Read in a file with StreamReader. use stream = new StreamReader @"E:Fprogfile.txt" // Continue reading while valid lines. let mutable valid = true while (valid) do let line = stream.ReadLine() if (line = null) then valid <- false else // Display line. printfn "%A" line // Create instance of Data and Read in the file. let data = Data() data.Read() Reading from File And Display the content line by line Use: ensures the StreamReader is correctly disposed of when it is no longer needed.
  • 21. • This is a simpler way to read all the lines in a file, but it may be less efficient on large files. • ReadAllLines returns an array of strings. • We use Seq.toList to get a list from the array. • And with Seq.where we get a sequence of only capitalized lines in the list. File.ReadAllLines
  • 22. open System open System.IO let lines = File.ReadAllLines(@“E:Fprogfile.txt") // Convert file lines into a list. let list = Seq.toList lines printfn "%A" list // Get sequence of only capitalized lines in list. let uppercase = Seq.where (fun (n : String) -> Char.IsUpper(n, 0)) list printfn "%A" uppercase
  • 23. ABC abc Cat Dog bird fish File.txt O/P ["ABC"; "abc"; "Cat"; "Dog"; "bird"; "fish"] seq ["ABC"; "Cat"; "Dog"]
  • 24. open System.IO // Name spaces can be opened just as modules File.WriteAllText("test.txt", "Hello Theren Welcome All”) let msg = File.ReadAllText("test.txt") printfn "%s" msg Creates a file called test.txt, writes a message there, reads the text from the file and prints it on the console.
  • 25. Delegates in F# • A special function that encapsulate a method and represents a method signature. • Similar to pointers to functions in C or C++. • A reference type variable that holds the address of functions. • The reference can be changed at runtime. • Used for implementing events and call-back functions.
  • 26. Delegates in F# • A delegate is referred to as type-safe function pointers, • If the method with two int parameters and a return type is an int then the delegate that you are declaring should also have the same signature. • That is why a delegate is referred to as type-safe function.
  • 27. 3 ways to define Delegates Methods Declaration Instantiation Invocation
  • 28. Types of Delegates Delegates Types Simple Delegate Multicast Delegate
  • 29. Delegates in F# :Syntax type delegate-typename = delegate of type1 -> type2 // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int Syntax Both the delegates can be used to reference any method that has two int parameters and returns an int type variable. argument type(s). return type.
  • 30. Point to Remember • Delegates can be attached to function values, and static or instance methods. • F# function values can be passed directly as arguments to delegate constructors. • For a static method the delegate is called by using the name of the class and the method. • For an instance method, the name of the object instance and method is used.
  • 31. Point to Remember • The Invoke method on the delegate type calls the encapsulated function. • Also, delegates can be passed as function values by referencing the Invoke method name without the parentheses.
  • 32. Example: Implementation of Add & Sub operation using Delegates 1. Define two types of Methods : Static & Instance 2. Define Delegates 3. Invoke delegates 4. Calling static method using delegates 5. Calling Instance method using delegates 6. Calling Delegates
  • 33. Method Defining-Static & Instance type Test1() = static member add(a : int, b : int) = a + b static member sub(a : int) (b : int) = a - b member x.Add(a : int, b : int) = a + b member x.Sub(a : int) (b : int) = a - b
  • 34. Defining Delegates // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int
  • 35. Invoking Delegates let InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) = dlg.Invoke(a, b) let InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) = dlg.Invoke(a, b)
  • 36. Calling static Method // For static methods, use the class name, the dot operator, and the name of the static method. let del1 : Delegate1 = new Delegate1( Test1.add ) let del2 : Delegate2 = new Delegate2( Test1.sub )
  • 37. For Instance Method // For instance methods, use the instance value name, the dot operator, and the instance method name. let testObject = Test1() let del3 : Delegate1 = new Delegate1( testObject.Add ) let del4 : Delegate2 = new Delegate2( testObject.Sub )
  • 38. Calling Delegates for (a, b) in [ (100, 200); (10, 20) ] do printfn "%d + %d = %d" a b (InvokeDelegate1 del1 a b) printfn "%d - %d = %d" a b (InvokeDelegate2 del2 a b) printfn "%d + %d = %d" a b (InvokeDelegate1 del3 a b) printfn "%d - %d = %d" a b (InvokeDelegate2 del4 a b)