SlideShare a Scribd company logo
1 of 38
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

What's hot

C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharpDaniele Pozzobon
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1Hossein Zahed
 
C programming session 01
C programming session 01C programming session 01
C programming session 01Dushmanta Nath
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Dushmanta Nath
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++K Durga Prasad
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and stringsRai University
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in Carshpreetkaur07
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and commentsNilimesh Halder
 
2 expressions (ppt-2) in C++
2 expressions (ppt-2) in C++2 expressions (ppt-2) in C++
2 expressions (ppt-2) in C++Kuntal Bhowmick
 

What's hot (17)

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

Similar to F# Console class

Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input OutputBharat17485
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceKrithikaTM
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxLikhil181
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2ppJ. C.
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 
Chapter3
Chapter3Chapter3
Chapter3Kamran
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput Ahmad Idrees
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java scriptmichaelaaron25322
 
C programming language
C programming languageC programming language
C programming languageAbin Rimal
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxPragatheshP
 
Diploma ii cfpc u-2 datatypes and variables in c language
Diploma ii  cfpc u-2 datatypes and variables in c languageDiploma ii  cfpc u-2 datatypes and variables in c language
Diploma ii cfpc u-2 datatypes and variables in c languageRai University
 

Similar to F# Console class (20)

Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
 
c programming session 1.pptx
c programming session 1.pptxc programming session 1.pptx
c programming session 1.pptx
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2pp
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
Chapter3
Chapter3Chapter3
Chapter3
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
qb unit2 solve eem201.pdf
qb unit2 solve eem201.pdfqb unit2 solve eem201.pdf
qb unit2 solve eem201.pdf
 
C programming language
C programming languageC programming language
C programming language
 
Introduction to C
Introduction to CIntroduction to C
Introduction to C
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptx
 
Diploma ii cfpc u-2 datatypes and variables in c language
Diploma ii  cfpc u-2 datatypes and variables in c languageDiploma ii  cfpc u-2 datatypes and variables in c language
Diploma ii cfpc u-2 datatypes and variables in c language
 

More from DrRajeshreeKhande

More from DrRajeshreeKhande (20)

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

Recently uploaded

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

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)