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
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()
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
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
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)