Showing posts with label Visual F#. Show all posts
Showing posts with label Visual F#. Show all posts

Example 18: Race to Ten Text-Based Game

Problem: Make a simple Race to Ten text-based game. The details of the game is shown in the following screenshot:



Code:
  1. // Learn more about F# at http://fsharp.net  
  2. open System  
  3. //change the console title  
  4. System.Console.Title<-"Race to Ten"  
  5. //adds the foreground and background color  
  6. System.Console.ForegroundColor<-ConsoleColor.DarkBlue  
  7. System.Console.BackgroundColor<-ConsoleColor.Gray  
  8. //clears the screen. This is to apply the background color once the  
  9. //console application is loaded  
  10. System.Console.Clear()  
  11. //display the game title screen  
  12. printfn "\t\t\t\tRace to Ten"  
  13. printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."  
  14. System.Console.ReadLine()|>ignore  
  15. System.Console.Clear()  
  16. //display the game description screen  
  17. printfn "Instructions:"  
  18. printfn "In this game, each player(you vs. the computer) enters a number between 1 to 3"  
  19. printfn "The previously inputted number will be added to the present number"  
  20. printfn "The first player to enter a number that adds up to 10 wins the game"  
  21. printfn "Press Esc to quit the game"  
  22. printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."  
  23.   
  24. let mutable userkey=System.Console.ReadLine()  
  25. System.Console.Clear()  
  26. //declares our variables  
  27. let rndnum=new Random()  
  28. let mutable intsum=0  
  29. let mutable intusernum=0  
  30. let mutable intremain=0  
  31. //loop while sum is not equal to 10 and   
  32. //the spacebar key has been pressed  
  33. while (intsum < 10 ) do  
  34. //computer generates a number  
  35.         printfn "\n\nAI's turn..."  
  36.         let intainum=rndnum.Next(1,3)  
  37.         printfn "AI num: %d" intainum  
  38. //accumulates the number to the  
  39. //value of sum  
  40.         intsum<-intsum + intainum  
  41.         printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"  
  42.         System.Console.ReadLine()|>ignore  
  43. System.Console.Clear()  
  44. //display how many numbers more to go  
  45. //before 10  
  46. intremain<-intsum-10    
  47.         printfn "%d more to go!" intremain  
  48.  //if the sum is equal to 10   
  49.  //display "computer wins"  
  50.         if intsum>=10 then    
  51. System.Console.Clear()  
  52. //reset the value of sum so that   
  53. //the game will loop again  
  54. //remove intsum<-0 if you want the  
  55.  //game to end after one game  
  56.             printfn "Computer Wins!"   
  57.             intsum<-0  
  58.             printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"  
  59.             System.Console.ReadLine()|>ignore  
  60. System.Console.Clear()            
  61. //otherwise ask for a number           
  62. printfn "\n\nYour turn:"   
  63. intusernum<-(int)(System.Console.ReadLine())  
  64.  //if the number exceeds 3 then  
  65.  //ask for a number again  
  66.         if intusernum>3 then  
  67. printfn "Number must be between 1 to 3"  
  68. printfn "You turn:"  
  69. intusernum<-(int)(System.Console.ReadLine())  
  70.             intsum<-intsum + intusernum  
  71.             System.Console.Clear()  
  72. //accumulates the inputted number to the value of sum  
  73.         intsum<-intsum + intusernum   
  74.         intremain<-intsum-10    
  75.         printfn "%d more to go!" intremain  
  76.         if intsum>=10 then  
  77. System.Console.Clear()  
  78. printfn "You Win!"  
  79. intsum<-0  
  80.             printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"  
  81.             System.Console.ReadLine()|>ignore  
  82. System.Console.Clear()  

Example#17(Array.Iter)

Problem: Make a console application that will convert the following singular nouns to plural. Use Array.Iter:

1. ally
2. army
3. baby
4. lady
5. navy

  1. // Learn more about F# at http://fsharp.net  
  2. open System  
  3. //change the console title  
  4. System.Console.Title<-"Convert to Plural"  
  5. //adds the foreground and background color  
  6. System.Console.ForegroundColor<-ConsoleColor.Blue  
  7. System.Console.BackgroundColor<-ConsoleColor.White  
  8. //clears the screen. This is to apply the background color once the  
  9. //console application is loaded  
  10. System.Console.Clear()  
  11. //assigns the singular nouns to our array variable singularnouns  
  12. let singularnouns=[|"ally";"army";"baby";"lady";"navy"|]  
  13. printfn "Singular words:"  
  14. //iterates through the values of our singularnouns array variable  
  15. singularnouns|>Array.iter(fun singularwords->printfn "%s" singularwords)  
  16. printfn "Plural words:"  
  17. //iterates through the values of our singularnouns array variable  
  18. //replace the word in each array element from "y" to "ies"  
  19. singularnouns|>Array.iter(fun pluralnouns->  
  20. let pluralwords= pluralnouns.Replace("y","ies")  
  21. printfn "%s" pluralwords)  

This will display the following output:

Visual F# 100 Examples: Example Number 16(Search a Record Value)

Problem: Make a Windows Forms Application that will allow the user to search a record value from a database file.

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Data  
  9. open System.Drawing  
  10. open System.Data.OleDb  
  11. //creates a font  
  12. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  13. //creates a connection object  
  14. let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;  
  15.   Data Source=C:\Documents and Settings\Station03\My Documents\dbEmployee.mdb")  
  16.  //creates an OleDbDataAdapter  
  17. let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)  
  18. //generates a dataset  
  19. let dataset11 = new DataSet()  
  20. //fills the dataset with recod values  
  21. dataadpter.Fill(dataset11,"tblEmployee")|>ignore  
  22. //creates a form  
  23. let dataform = new Form(Text="Search a Record Value",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(400, 360),StartPosition=FormStartPosition.CenterScreen)  
  24. //creates our controls  
  25. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(300, 320))   
  26. let searchbutton=new Button(Text="Search", Location=new System.Drawing.Point(220, 320))    
  27. let label1=new Label(Text="Enter the employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  28. let label2=new Label(Text="Empno:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  29. let label3=new Label(Text="Firstname:",Location=new System.Drawing.Point(0,100),AutoSize=true)  
  30. let label4=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,150),AutoSize=true)  
  31. let empnotext=new TextBox(Location=new System.Drawing.Point(200,10))  
  32. let emplabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)  
  33. let fnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)  
  34. let lnamelabel=new Label(Location=new System.Drawing.Point(100,150),BorderStyle=BorderStyle.FixedSingle)  
  35. //creates a datagrid  
  36. let datagrid = new DataGridView(ColumnHeadersHeightSizeMode=DataGridViewColumnHeadersHeightSizeMode.AutoSize,Size=new System.Drawing.Size(300, 120),Location=new System.Drawing.Point(10, 180))  
  37. //creates a grid control colums  
  38. let chrempnocol=new DataGridViewTextBoxColumn()  
  39. let chrfnamecol=new DataGridViewTextBoxColumn()  
  40. let chrlnamecol=new DataGridViewTextBoxColumn()  
  41. //adds the columns into our datagrid  
  42. datagrid.Columns.Add(chrempnocol)|>ignore  
  43. datagrid.Columns.Add(chrfnamecol)|>ignore  
  44. datagrid.Columns.Add(chrlnamecol)|>ignore  
  45. datagrid.DataSource <- dataset11.Tables.["tblEmployee"]  
  46. //assingns the font to our form  
  47. dataform.Font<-ffont  
  48. //links our fieldname to each grid  
  49. //and change its header text  
  50. chrempnocol.DataPropertyName<-"chrempno"  
  51. chrempnocol.HeaderText<-"Employee No."  
  52. chrfnamecol.DataPropertyName<-"chrfname"  
  53. chrfnamecol.HeaderText<-"First Name"  
  54. chrlnamecol.DataPropertyName<-"chrlname"  
  55. chrlnamecol.HeaderText<-"Last Name"  
  56. //add the datagrid to our form  
  57. dataform.Controls.Add(datagrid)  
  58. //adds the controls to our form  
  59. dataform.Controls.Add(exitbutton)  
  60. dataform.Controls.Add(searchbutton)  
  61. dataform.Controls.Add(label1)  
  62. dataform.Controls.Add(label2)  
  63. dataform.Controls.Add(label3)  
  64. dataform.Controls.Add(label4)  
  65. dataform.Controls.Add(empnotext)  
  66. dataform.Controls.Add(emplabel)  
  67. dataform.Controls.Add(fnamelabel)  
  68. dataform.Controls.Add(lnamelabel)  
  69. //binds the fieldnames to our label  
  70. emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))  
  71. fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))  
  72. lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))  
  73. searchbutton.Click.Add(fun search->    
  74.                     //handles the row index number                 
  75.                     let mutable introws=0  
  76.                     //determines if the record has been found or not  
  77.                     let mutable blnfound=false     
  78.                     //handles the total number of records                  
  79.                     let mutable inttotrec=Convert.ToInt32(dataset11.Tables.["tblEmployee"].Rows.Count)  
  80.                     //handles the data inputted by the user  
  81.                     let strtext=Convert.ToString(empnotext.Text)  
  82.                     //while no match is found and the end of the file has not been reached  
  83.                     while((blnfound=false) && (introws<=inttotrec-1)) do  
  84.                          let strempnum=Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))  
  85.                          //compare the data inputted in the textbox to the employee number in our table  
  86.                          //if they are equal, display the match record  
  87.                          if strtext.ToUpper()=strempnum.ToUpper() then  
  88.                             blnfound<-true  
  89.                             emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))  
  90.                             fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(1))  
  91.                             lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(2))   
  92.                          //compare to the next record while no match is found  
  93.                          introws<-introws + 1      
  94.                     //if no match is found, display this        
  95.                     if blnfound=false then  
  96.                         MessageBox.Show("Record not found.","Search a Record Value",MessageBoxButtons.OK,MessageBoxIcon.Information)|>ignore)                         
  97. //when the exit button is clicked  
  98. exitbutton.Click.Add(fun exit->  
  99. //close the form and dataconnection  
  100.                     dataform.Close()  
  101.                     oleconn.Close())   
  102. //executes our application  
  103. Application.Run(dataform)  

Since Visual F# is very particular with the code indention, I posted below the screenshot of our code in the while loop section.



Here's what it should look like if you click the run icon:

Visual F# 100 Examples: Example 14 and 15(Pattern Matching)

Pattern matching/match with statement is similar to the switch selection statement in other programming languages. The following examples demonstrate how to use it:


Problem: Make an application that will asks a letter and displays its equivalent U. S. military phonetic alphabet.
  1. //use F# library  
  2. open System  
  3. //change the CLI title  
  4. System.Console.Title<-"Display Military Phoenitic Alphabet"  
  5. //adds color to our console application  
  6. System.Console.ForegroundColor<-ConsoleColor.Blue  
  7. //asks the user to enter a letter  
  8. printfn "Enter a letter:"  
  9. //convert the input to character and convert it to uppercase letter  
  10. //this is just for comparison purpose  
  11. let chrletter=Char.ToUpper(Convert.ToChar(System.Console.ReadLine()))  
  12. //clear the screen     
  13. System.Console.Clear()  
  14. //match the value of chrletter to the ff. values  
  15. match chrletter with  
  16. //if the value of chrletter is a or A display Alpha  
  17. 'A' ->printfn "Alpha"  
  18. //if the value of chrletter is b or B display Bravo  
  19. 'B' ->printfn "Bravo"  
  20. //if the value of chrletter is c or C display Charlie  
  21. 'C' ->printfn "Charlie"  
  22. //if the value of chrletter is d or D display Delta  
  23. 'D' ->printfn "Delta"  
  24. //if the value of chrletter is e or E display Echo  
  25. 'E'->printfn "Echo"  
  26. //if the value of chrletter is f or F display Foxtrot  
  27. 'F'->printfn "FoxTrot"  
  28. //if the value of chrletter is g or G display Golf  
  29. 'G'->printfn "Golf"  
  30. //if the value of chrletter is h or H display Hotel  
  31. 'H'->printfn "Hotel"  
  32. //if the value of chrletter is i or I display India  
  33. 'I'->printfn "India"  
  34. //if the value of chrletter is j or J display Juliet  
  35. 'J'->printfn "Juliet"  
  36. //if the value of chrletter is k or K display Kilo  
  37. 'K'->printfn "Kilo"  
  38. //if the value of chrletter is l or L display Lima  
  39. 'L'->printfn "Lima"  
  40. //if the value of chrletter m or M display Mike  
  41. 'M'->printfn "Mike"  
  42. //if the value of chrletter is n or N display November  
  43. 'N'->printfn "November"  
  44. //if the value of chrletter is o or O display Oscar  
  45. 'O'->printfn "Oscar"  
  46. //if the value of chrletter is p or P display Papa  
  47. 'P'->printfn "Papa"  
  48. //if the value of chrletter is q or Q display Quebec  
  49. 'Q'->printfn "Quebec"  
  50. //if the value of chrletter is r or R display Romeo  
  51. 'R'->printfn "Romeo"  
  52. //if the value of chrletter is s or S display Sierra  
  53. 'S'->printfn "Sierra"  
  54. //if the value of chrletter is t or T display Tango  
  55. 'T'->printfn "Tango"  
  56. //if the value of chrletter is u or U display Uniform  
  57. 'U'->printfn "Uniform"  
  58. //if the value of chrletter is v or V display Victor  
  59. 'V'->printfn "Victor"  
  60. //if the value of chrletter is w or W display Whiskey  
  61. 'W'->printfn "Whiskey"  
  62. //if the value of chrletter is x or X display X-Ray  
  63. 'X'->printfn "X-Ray"  
  64. //if the value of chrletter is y or Y display Yankee  
  65. 'Y'->printfn "Yankee"  
  66. //if the value of chrletter is z or Z display Zulu  
  67. 'Z'->printfn "Zulu"  
  68. //otherwise  
  69. | _ ->printfn "Invalid input"  
The last statement |_ is similar to the
default statement in other programming languages Switch conditional structure. It is automatically executed when no pattern match is found. Don't forget to add it at the end of every match with statement otherwise you will get an “Incomplete pattern matches on this expression” error.


Problem: Make an application that will ask the month number and display the corresponding month name and the number of days in it. Use pattern matching.

  1. //use F# library  
  2. open System  
  3. //change the CLI title  
  4. System.Console.Title<-"Display Month Name"  
  5. //adds color to our console application  
  6. System.Console.ForegroundColor<-ConsoleColor.Blue  
  7. System.Console.BackgroundColor<-ConsoleColor.White  
  8. //asks the user to enter a month number  
  9. printfn "Enter a month number(1-12):"  
  10. let intmonth=Convert.ToInt32(System.Console.ReadLine())  
  11. //clear the screen     
  12. System.Console.Clear()  
  13. //match the value of intmonth to the ff. values  
  14. match intmonth with  
  15. //if the value of intmonth is 1 display January  
  16. | 1 ->printfn "January(31 days)"  
  17. //if the value of intmonth is 2 display February  
  18. | 2 ->printfn "Febrary(28/29 days)"  
  19. //if the value of intmonth is 3 display March   
  20. | 3 ->printfn "March(31 days)"  
  21. //if the value of intmonth is 4 display April  
  22. | 4 ->printfn "April(30 days)"  
  23. //if the value of intmonth is 5 display May  
  24. | 5 ->printfn "May(31 days)"  
  25. //if the value of intmonth is 6 display June  
  26. | 6 ->printfn "June(30 days)"  
  27. //if the value of intmonth is 7 display July  
  28. | 7 ->printfn "July(31 days)"  
  29. //if the value of intmonth is 8 display August  
  30. | 8 ->printfn "August(31 days)"  
  31. //if the value of intmonth is 9 display September  
  32. | 9 ->printfn "September(30 days)"  
  33. //if the value of intmonth is 10 display October  
  34. | 10 ->printfn "October(31 days)"  
  35. //if the value of intmonth is 11 display November  
  36. | 11 ->printfn "November(30 days)"  
  37. //if the value of intmonth is 12 display December  
  38. | 12->printfn "December(31 days)"  
  39. //otherwise  
  40. | _ ->printfn "Invalid input"  

That's all for now my Visual F# friends. Ciao!

Visual F# 100 Examples: Example 12 and 13

This is the continuation of our planned 100 Visual F# examples. By the way, the bugs in examples number 7 to 11 had been fixed. My apologies, I should’nt have written those without using Visual F# compiler:)


Problem: Make a console application that will asks the user to enter the day that he was born and display his character or future based on the famous nursery rhyme written in England, “Monday’s Child”.

  1. open System  
  2. //changes the console application title  
  3. System.Console.Title<-"Tell the Future"  
  4. //adds foreground color  
  5. System.Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "What day were you born?"  
  7. let strday=System.Console.ReadLine()  
  8. //clears the screen  
  9. System.Console.Clear()  
  10. //converts the inputs to lowercase then compare it our  
  11. //specified values  
  12. if strday.ToLower()="monday" then  
  13.     printfn "Monday's child is fair of face"  
  14. else if strday.ToLower()="tuesday" then  
  15.     printfn "Tuesday's child is full of grace"  
  16. else if strday.ToLower()="wednesday" then  
  17.     printfn "Wednesday's child is full of woe"  
  18. else if strday.ToLower()="thursday" then  
  19.     printfn "Thurdays's child has far to go"  
  20. else if strday.ToLower()="friday" then  
  21.     printfn "Friday's child is loving and giving"  
  22. else if strday.ToLower()="saturday" then  
  23.     printfn "Saturday's child works hard for a living"  
  24. else if strday.ToLower()="sunday" then  
  25.     printfn "Sunday's child is bonny and blithe and good and gay"  
  26. else  
  27.     printfn "Invalid input"  
Problem: Develop a console application that will asks the wind speed in kilometer per hour(kph) and display its equivalent Philippine Storm Signal number.
  1. open System  
  2. //changes the console application title  
  3. System.Console.Title<-"Determine Storm Signal Number"  
  4. //adds foreground color  
  5. System.Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "Enter wind speed(kph):"  
  7. let intspeed=Convert.ToInt32(System.Console.ReadLine())  
  8. //clears the screen  
  9. System.Console.Clear()  
  10. //if the wind speed ranges from 30 to 60  
  11. if intspeed>=30 && intspeed<=60 then  
  12.     printfn "Storm signal number 1"  
  13. //if the wind speed ranges from 61 to 100  
  14. else if intspeed>60 && intspeed<=100 then  
  15.     printfn "Storm signal number 2"  
  16. //if the wind speed ranges from 101 to 185  
  17. else if intspeed>100 && intspeed<=185 then  
  18.     printfn "Storm signal number 3"  
  19. //if the wind speed is greater than 185  
  20. else if intspeed>185 then  
  21. printfn "Storm signal number 4"  
  22. else   
  23. printfn "Invalid input"  

Visual F# 100 Examples: Example 11

Problem: Make a simple crack the treasure chest console application game.

  1. // Learn more about F# at http://fsharp.net  
  2.   
  3. open System  
  4. //change the title to Crack the Safe  
  5. System.Console.Title<-"Crack the Safe"  
  6. //change the foreground color to green  
  7. Console.ForegroundColor<-ConsoleColor.Green  
  8. //dislay the game title screen  
  9. printfn "\t\t\t Crack the Safe"  
  10. printfn "\t\t\t Press enter to continue..."  
  11. //waits for a keypress from the user  
  12. System.Console.ReadLine()|>ignore  
  13. //Game action sequence  
  14. printfn "\t\t\t You have found a legendary treasure chest"  
  15. printfn "\t\t\t believed to contain the rarest gem on Earth"  
  16. printfn "\t\t\t Press enter to continue... "  
  17. //waits for a keypress from the user  
  18. System.Console.ReadLine()|>ignore  
  19.   
  20. printfn "\t\t\t this chest can be opened only by"  
  21. printfn "\t\t\t entering a mysterious 4-digit key code"  
  22. printfn "\t\t\t Press enter to continue..."  
  23. //waits for a keypress from the user  
  24. System.Console.ReadLine()|>ignore  
  25.   
  26. let random=new Random()  
  27. let intkeycode=Convert.ToInt32(random.Next(1000,9999))  
  28.   
  29. printfn "\t\t\tEnter the keycode:"  
  30. let intusercode= Convert.ToInt32(Console.ReadLine())  
  31. //if usercode is equal to the computer generated code then  
  32. if intusercode=intkeycode then  
  33. //display a congratulatory message  
  34.     printfn "\t\t\Congrats You have opened the treasure chest."  
  35.   
  36. //otherwise   
  37. else  
  38.     printfn "\t\t\tInvalid Code"  
  39.   
  40. printfn "\t\t\tPress enter to continue... "  
  41. System.Console.ReadLine()|>ignore  
  42. printfn "\t\t\tGame Over"  

Visual F# 100 Examples: Example 8 to 10

Problem: Make a console application that will accept five numbers and display the sum.
  1. open System  
  2. //change the title to Add Five Numbers  
  3. System.Console.Title<-"Add Five Numbers "  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "\t\t\tEnter the first number:"  
  7. let intnum1=Convert.ToInt32(System.Console.ReadLine())  
  8. printfn "\t\t\tEnter the second number:"  
  9. let intnum2=Convert.ToInt32(System.Console.ReadLine())  
  10. printfn "\t\t\tEnter the third number:"  
  11. let intnum3=Convert.ToInt32(System.Console.ReadLine())  
  12. printfn "\t\t\tEnter the fourth number:"  
  13. let intnum4=Convert.ToInt32(System.Console.ReadLine())  
  14. printfn "\t\t\tEnter the fifth number:"  
  15. let intnum5=Convert.ToInt32(System.Console.ReadLine())  
  16. let  intsum=intnum1+ intnum2 + intnum3 + intnum4 + intnum5  
  17. printfn "\t\t\tThe sum is:%i" intsum  
Problem: Make a console application that will ask the power transmitted and power received then display the power loss value.
  1. open System  
  2. //change the title to Calculate Power Loss  
  3. System.Console.Title<-"Calculate Power Loss "  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "\t\t\t\tPower transmitted:"  
  7. let dblpowertrans=Convert.ToDouble(System.Console.ReadLine())  
  8. printfn "\t\t\tPower recieved:"  
  9. let dblpowerrec=Convert.ToDouble(System.Console.ReadLine())  
  10. let dblpowerloss= dblpowertrans/ dblpowerrec  
  11. printfn "\t\t\t Power loss:%f " dblpowerloss  
Problem: Develop a console application that will ask the base value and height value then display the volume of a pyramid.
  1. open System  
  2. //change the title to Volume of a Pyramid  
  3. System.Console.Title<-" Volume of a Pyramid"  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "\t\t\tBase value:"  
  7. let dblbase=Convert.ToDouble(System.Console.ReadLine())  
  8. printfn "\t\t\tHeight value:"  
  9. let dblheight=Convert.ToDouble(System.Console.ReadLine())  
  10. let  dblvolume=(dblbase*dblheight)/3.0  
  11. printfn "\t\t\tVolume of a pyramid:%f" dblvolume  

Visual F# 100 Examples: Example Number 7

So far I have been sharing to you guys some examples of Window Based application in Visual F#. This time, for variation sake lets make some console application:

Problem: Make a simple console application mind reader game.
  1. open System  
  2. //change the title to Simple Mind Reader Game  
  3. System.Console.Title<-"Simple Mind Reader Game"  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. //dislay the game title screen  
  7. printfn "\t\t\t Mind Reader Game"  
  8. printfn "\t\t\tPress enter to continue..."  
  9. //waits for a keypress from the user  
  10. System.Console.ReadLine()|>ignore  
  11. System.Console.Clear()  
  12. //the following does the game action sequence  
  13. printfn "\t\t\t Think of a five-digit number that has five unique numbers(Eg. 12345)"  
  14. printfn "\t\t\tPress enter to continue..."  
  15. System.Console.ReadLine()|>ignore  
  16. System.Console.Clear()  
  17.   
  18. printfn "\t\t\t Reverse the numbers then subtract the smaller number from the larger number(Eg.54321- 12345)"  
  19. printfn "\t\t\tPress enter to continue..."  
  20. System.Console.ReadLine()|>ignore  
  21. System.Console.Clear()  
  22.   
  23. printfn "\t\t\t Add 10000 to the difference"  
  24. printfn "\t\t\t Press enter to continue..."  
  25. System.Console.ReadLine()|>ignore  
  26. System.Console.Clear()  
  27.   
  28. printfn "\t\t\tVisualize the sum while I try to read your mind."  
  29. printfn "\t\t\tPress enter to continue..."  
  30. System.Console.ReadLine()|>ignore  
  31. System.Console.Clear()  
  32.   
  33. printfn "\t\t\tThe sum is…"  
  34. printfn "\t\t\tPress enter to continue..."  
  35. System.Console.ReadLine()|>ignore  
  36. System.Console.Clear()  
  37.   
  38. printfn "\t\t\tThe sum is…"  
  39. printfn "\t\t\tPress enter to continue..."  
  40. System.Console.ReadLine()|>ignore  
  41. System.Console.Clear()  
  42.   
  43. printfn "\t\t\tThe sum is…"  
  44. printfn "\t\t\tPress enter to continue..."  
  45. System.Console.ReadLine()|>ignore  
  46. System.Console.Clear()  
  47.   
  48. printfn "\t\t\t51976"  

Visual F# 100 Examples: Example Number 6

Problem. Create an application that will display the surface area of a cube. The surface area of a cube can be computed by multiplying the inputted side by itself and multiplying the product by 6.
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a new form  
  10. let cubeform=new Form(Text="Compute the Surface Area of a Cube", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //creates our controls  
  12. let n1label=new Label(Text="Enter a side value:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  13. let firsttextbox=new TextBox(Location=new System.Drawing.Point(120, 20))  
  14. let n2label=new Label(Text="Surface area of a cube:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  15. //creates a label that will display the result of the computation  
  16. let anslabel=new Label(Location=new System.Drawing.Point(140, 90), BorderStyle=BorderStyle.FixedSingle)  
  17. //make our buttons  
  18. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))  
  19. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))  
  20. //add the controls into the form  
  21. cubeform.Controls.Add(n1label)  
  22. cubeform.Controls.Add(firsttextbox)  
  23. cubeform.Controls.Add(n2label)  
  24. cubeform.Controls.Add(anslabel)  
  25. cubeform.Controls.Add(computebutton)  
  26. cubeform.Controls.Add(exitbutton)  
  27.   
  28. //when the compute button is clicked  
  29. computebutton.Click.Add(fun ans->  
  30. let sidevalue=Convert.ToDouble(firsttextbox.Text)  
  31. let areaofacube=6.00*(sidevalue*sidevalue)  
  32.   
  33. //display the areaofacube value in the anslabel  
  34. anslabel.Text<-Convert.ToString(areaofacube))  
  35.  //when the exit button is clicked, close the form              
  36. exitbutton.Click.Add(fun exit -> cubeform.Close())    
  37. Application.Run(cubeform)  

We'll be adding some new controls after our tenth example:)

Visual F# 100 Examples:Example Number 5

Problem: Design an application that will ask a length value, height value, and width value and display the volume of the prism.
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates our controls  
  10. let prismform=new Form(Text="Compute the Volume of a Prism", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let n1label=new Label(Text="Length value:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  12. let lenghttxtbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  13. let n2label=new Label(Text="Width value:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  14. let widthtxtbox=new TextBox(Location=new System.Drawing.Point(80,50))  
  15. let n3label=new Label(Text="Height value:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  16. let heighttxtbox=new TextBox(Location=new System.Drawing.Point(130, 90))  
  17.   
  18. let n4label=new Label(Text="Prisms volume:", Location=new System.Drawing.Point(0, 180),AutoSize=true)  
  19. let prismlabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)  
  20. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))  
  21. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))  
  22.   
  23. //add the controls into the form  
  24. prismform.Controls.Add(n1label)  
  25. prismform.Controls.Add(lenghttxtbox)  
  26. prismform.Controls.Add(n2label)  
  27. prismform.Controls.Add(widthtxtbox)  
  28. prismform.Controls.Add(n3label)  
  29. prismform.Controls.Add(heighttxtbox)  
  30. prismform.Controls.Add(n4label)  
  31. prismform.Controls.Add(prismlabel)  
  32. prismform.Controls.Add(computebutton)  
  33. prismform.Controls.Add(exitbutton)  
  34.   
  35. //when the compute button is clicked  
  36. computebutton.Click.Add(fun compute->  
  37. //assign the data inputted in each control to each corresponding variables  
  38. //compute the volume using the formula volume=lengthvalue*widthvalue*heightvalue  
  39. //display the result on outcome on their assigned controls  
  40. let lenghtvalue=Convert.ToDouble(lenghttxtbox.Text)  
  41. let widthvalue=Convert.ToDouble(widthtxtbox.Text)  
  42. let heightvalue=Convert.ToDouble(heighttxtbox.Text)  
  43. let prismvol=lenghtvalue*widthvalue*heightvalue  
  44. prismlabel.Text<-Convert.ToString(prismvol))  
  45.  //when the exit button is clicked, close the form              
  46. exitbutton.Click.Add(fun exit -> prismform.Close())    
  47. Application.Run(prismform)  

Visual F# 100 Examples: Example Number 4

Problem: Make an application that will display the area of an annulus (overlapping circles). The area of an annulus can be calculated by subtracting the area of a small circle from the area of a larger circle.

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a new form  
  10. let annulform=new Form(Text="Dislay the Area of an Annulus", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //creates our controls  
  12. let n1label=new Label(Text="Area of a large circle:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  13. let firsttextbox=new TextBox(Location=new System.Drawing.Point(120, 20))  
  14. let n2label=new Label(Text="Area of a small circle:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  15. let secondtextbox=new TextBox(Location=new System.Drawing.Point(120,50))  
  16. let n3label=new Label(Text="Area of an annulus:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  17. //creates a label that will display the result of the computation  
  18. let anslabel=new Label(Location=new System.Drawing.Point(120, 90), BorderStyle=BorderStyle.FixedSingle)  
  19. //make our buttons  
  20. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))  
  21. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))  
  22. //add the controls into the form  
  23. annulform.Controls.Add(n1label)  
  24. annulform.Controls.Add(firsttextbox)  
  25. annulform.Controls.Add(n2label)  
  26. annulform.Controls.Add(secondtextbox)  
  27. annulform.Controls.Add(n3label)  
  28. annulform.Controls.Add(anslabel)  
  29. annulform.Controls.Add(computebutton)  
  30. annulform.Controls.Add(exitbutton)  
  31.   
  32. //when the compute button is clicked  
  33. computebutton.Click.Add(fun ans ->  
  34. let areaoflargecircle=Convert.ToDouble(firsttextbox.Text)  
  35. let areaofsmallcircle=Convert.ToDouble(secondtextbox.Text)  
  36. let areaofannulus=areaoflargecircle-areaofsmallcircle  
  37.   
  38. //display the area of annulus value in the anslabel  
  39. anslabel.Text<-Convert.ToString(areaofannulus))  
  40.  //when the exit button is clicked, close the form              
  41. exitbutton.Click.Add(fun exit -> annulform.Close())    
  42. Application.Run(annulform)  

Visual F# 100 Examples:Example Number 3

We are now on our third example of our planned 100 Visual F# windows form applications learning examples. If you noticed we are just using basic controls such as textboxes, labels, and buttons. We will add some new controls in our future examples. Meanwhile, try the following:

Problem: Create an application that will ask the name of an object or material, its voltage and current values then display its electrical resistance.

Solution:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates our controls  
  10. let resistanceform=new Form(Text="Compute Resistance", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let n1label=new Label(Text="Material:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  12. let materialtextbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  13. let n2label=new Label(Text="Current(volts):", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  14. let currenttextbox=new TextBox(Location=new System.Drawing.Point(80,50))  
  15. let n3label=new Label(Text="Voltage(amperes):", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  16. let voltstextbox=new TextBox(Location=new System.Drawing.Point(130, 90))  
  17.   
  18. let n4label=new Label(Text="Material:", Location=new System.Drawing.Point(0, 180),AutoSize=true)  
  19. let materiallabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)  
  20. let n5label=new Label(Text="Resistance(ohms):", Location=new System.Drawing.Point(0, 210),AutoSize=true)  
  21. let resistancelabel=new Label(Location=new System.Drawing.Point(130, 210),BorderStyle=BorderStyle.FixedSingle)  
  22. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))  
  23. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))  
  24.   
  25. //add the controls into the form  
  26. resistanceform.Controls.Add(n1label)  
  27. resistanceform.Controls.Add(materialtextbox)  
  28. resistanceform.Controls.Add(n2label)  
  29. resistanceform.Controls.Add(currenttextbox)  
  30. resistanceform.Controls.Add(n3label)  
  31. resistanceform.Controls.Add(voltstextbox)  
  32. resistanceform.Controls.Add(n4label)  
  33. resistanceform.Controls.Add(materiallabel)  
  34. resistanceform.Controls.Add(n5label)  
  35. resistanceform.Controls.Add(resistancelabel)  
  36. resistanceform.Controls.Add(computebutton)  
  37. resistanceform.Controls.Add(exitbutton)  
  38.   
  39. //when the compute button is clicked  
  40. computebutton.Click.Add(fun compute->  
  41. //assign the data inputted in each control to each corresponding variables  
  42. //compute the resistance using the formula resistance=voltage divided by current  
  43. //display the result on outcome on their assigned controls  
  44. let material=materialtextbox.Text  
  45. let current=Convert.ToDouble(currenttextbox.Text)  
  46. let voltage=Convert.ToDouble(voltstextbox.Text)  
  47. let resistance=voltage/current  
  48. materiallabel.Text<-material  
  49. resistancelabel.Text<-Convert.ToString(resistance))  
  50.  //when the exit button is clicked, close the form              
  51. exitbutton.Click.Add(fun exit -> resistanceform.Close())    
  52. Application.Run(resistanceform)  

Visual F# 100 Examples: Example Number 2

Last time I have shared to you our first simple example of window forms application using Visual F#, let’s now proceed to our second example:

Problem: Make a windows forms application that will ask the amount of consumption, amount of investment, government spending, amount of exports and imports and display the net emports and Gross Domestic Product (GDP).

Solution:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates our controls  
  10. let gdpform=new Form(Text="Compute GDP", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let n1label=new Label(Text="Consumption:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  12. let firsttextbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  13. let n2label=new Label(Text="Investment:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  14. let secondtextbox=new TextBox(Location=new System.Drawing.Point(80,50))  
  15. let n3label=new Label(Text="Government spending:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  16. let thirdtextbox=new TextBox(Location=new System.Drawing.Point(130, 90))  
  17. let n4label=new Label(Text="Exports:", Location=new System.Drawing.Point(0, 120),AutoSize=true)  
  18. let fourthtextbox=new TextBox(Location=new System.Drawing.Point(130, 120))  
  19. let n5label=new Label(Text="Imports:", Location=new System.Drawing.Point(0, 150),AutoSize=true)  
  20. let fifthtextbox=new TextBox(Location=new System.Drawing.Point(130, 150))  
  21. let n6label=new Label(Text="Imports:", Location=new System.Drawing.Point(0, 180),AutoSize=true)  
  22. let netemlabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)  
  23. let n7label=new Label(Text="GDP:", Location=new System.Drawing.Point(0, 210),AutoSize=true)  
  24. let gdplabel=new Label(Location=new System.Drawing.Point(130, 210),BorderStyle=BorderStyle.FixedSingle)  
  25. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))  
  26. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))  
  27. //add the controls into the form  
  28. gdpform.Controls.Add(n1label)  
  29. gdpform.Controls.Add(firsttextbox)  
  30. gdpform.Controls.Add(n2label)  
  31. gdpform.Controls.Add(secondtextbox)  
  32. gdpform.Controls.Add(n3label)  
  33. gdpform.Controls.Add(thirdtextbox)  
  34. gdpform.Controls.Add(n4label)  
  35. gdpform.Controls.Add(fourthtextbox)  
  36. gdpform.Controls.Add(n5label)  
  37. gdpform.Controls.Add(fifthtextbox)  
  38. gdpform.Controls.Add(n6label)  
  39. gdpform.Controls.Add(netemlabel)  
  40. gdpform.Controls.Add(n7label)  
  41. gdpform.Controls.Add(gdplabel)  
  42. gdpform.Controls.Add(computebutton)  
  43. gdpform.Controls.Add(exitbutton)  
  44. //when the compute button is clicked  
  45. computebutton.Click.Add(fun compute->  
  46. //assigned the numbers inputted to each textbox to their corresponding variable  
  47. //compute the net emport using the formula net emport=export-import  
  48. //compute the gdp using the formula gdp=consumption+investment+govspending+netemport  
  49. let consumption=Convert.ToDouble(firsttextbox.Text)  
  50. let investment=Convert.ToDouble(secondtextbox.Text)  
  51. let govspending=Convert.ToDouble(thirdtextbox.Text)  
  52. let export=Convert.ToDouble(fourthtextbox.Text)  
  53. let import=Convert.ToDouble(fifthtextbox.Text)  
  54. let netemport=export-import  
  55. let gdp=(consumption+investment+govspending+netemport)  
  56. netemlabel.Text<-Convert.ToString(netemport)  
  57.                  gdplabel.Text<-Convert.ToString(gdp))  
  58.  //when the exit button is clicked, close the form              
  59. exitbutton.Click.Add(fun exit -> gdpform.Close())    
  60. Application.Run(gdpform)  

Visual F# 100 Examples: Example Number 1

Starting today, I will be sharing to you guys some learning examples that will aid you in learning windows forms application programming in Visual F#. Our target is to be able to share at least 100 examples. Let’s start with example number 1:

Problem: Make a windows form application that will ask the user’s mental age and chronological age and display his intelligence quotient (IQ).

Solution:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a new form  
  10. let iqform=new Form(Text="Compute IQ", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //creates a label  
  12. let n1label=new Label(Text="Mental age:",Top=20,Left=5,AutoSize=true)  
  13. let firsttextbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  14. //creates another label and change its text to “Second number:”  
  15. let n2label=new Label(Text="Chronological age:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  16. let secondtextbox=new TextBox(Location=new System.Drawing.Point(100,50))  
  17. //creates another label and change its text to sum  
  18. let n3label=new Label(Text="IQ:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  19. //creates a label that will display the result of the computation  
  20. let anslabel=new Label(Location=new System.Drawing.Point(80, 90), BorderStyle=BorderStyle.FixedSingle)  
  21. //make our buttons  
  22. let addbutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))  
  23. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))  
  24. //add the controls into the form  
  25. iqform.Controls.Add(n1label)  
  26. iqform.Controls.Add(firsttextbox)  
  27. iqform.Controls.Add(n2label)  
  28. iqform.Controls.Add(secondtextbox)  
  29. iqform.Controls.Add(n3label)  
  30. iqform.Controls.Add(anslabel)  
  31. iqform.Controls.Add(addbutton)  
  32. iqform.Controls.Add(exitbutton)  
  33.   
  34. //when the compute button is clicked  
  35. addbutton.Click.Add(fun addfunction ->  
  36. let manum=Convert.ToDouble(firsttextbox.Text)  
  37. let canum=Convert.ToDouble(secondtextbox.Text)  
  38. let iq=Convert.ToDouble((manum/canum)*100.00)  
  39.   
  40. //display the iq value in the anslabel  
  41. anslabel.Text<-Convert.ToString(iq))  
  42.  //when the exit button is clicked, close the form              
  43. exitbutton.Click.Add(fun exit -> iqform.Close())    
  44. Application.Run(iqform)  

Simplest input validation using Char.IsNumber and Char.IsLetter

The following example demonstrates how to validate a user input by using the Char.IsNumber and Char.IsLetter character manipulation functions:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a font  
  10. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  11. let validateform = new Form(Text="Validate Inputs",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)  
  12. //creates our controls  
  13. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 170))    
  14. let okbutton=new Button(Text="Ok", Location=new System.Drawing.Point(100, 170))   
  15. let label1=new Label(Text="Enter a name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  16. let nametxtbox=new TextBox(Location=new System.Drawing.Point(120,10),BorderStyle=BorderStyle.FixedSingle)  
  17. validateform.Font<-ffont  
  18. //adds the controls to our form  
  19. validateform.Controls.Add(exitbutton)  
  20. validateform.Controls.Add(okbutton)  
  21. validateform.Controls.Add(label1)  
  22. validateform.Controls.Add(nametxtbox)  
  23. //when the oK button is clicked  
  24. okbutton.Click.Add(fun ok->  
  25. //if the input begins with a letter then  
  26. if (Char.IsLetter(Convert.ToChar(nametxtbox.Text.Chars(0)))) then  
  27. //prompt that its a valid name  
  28. MessageBox.Show("The name you entered is valid ""Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore  
  29. //if the input begins with a number then                           
  30. if (Char.IsNumber(Convert.ToChar(nametxtbox.Text.Chars(0)))) then  
  31. //prompt that its an invalid name  
  32. MessageBox.Show("You must enter a valid name""Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore)  
  33. //when the exit button is clicked  
  34. exitbutton.Click.Add(fun exit->validateform.Close())  
  35. //executes our application  
  36. Application.Run(validateform)  
Click the run icon when done entering these codes in Visual F# code editor window. Try entering any number in the name text box and clicking the ok button. You should see an output similar to the following:

Paint Application in Visual F#

The following example demonstrates how to make a simple Paint-like application in Visual F#:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. open System.Drawing.Drawing2D  
  10. let drawingform = new Form(Text="Draw Objects",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  13. let erasebutton=new Button(Text="Erase", Location=new System.Drawing.Point(120, 200))  
  14. let colorbutton=new Button(Text="Brush Color", Location=new System.Drawing.Point(40, 200))  
  15. drawingform.Controls.Add(exitbutton)  
  16. drawingform.Controls.Add(erasebutton)  
  17. drawingform.Controls.Add(colorbutton)  
  18. //creates a color dialog box  
  19. let colordlg=new ColorDialog()  
  20. //creates a colorblend object  
  21. let mutable color=new ColorBlend()  
  22.   
  23. let gr=drawingform.CreateGraphics()  
  24. gr.SmoothingMode<-SmoothingMode.HighQuality  
  25. //when the form is loaded, change its color to white  
  26. drawingform.Load.Add(fun background->  
  27. //set the default brush color to indigo  
  28. color.Colors<-[|Color.Indigo|]  
  29.                         drawingform.BackColor<-Color.White)  
  30.   
  31. drawingform.MouseMove.Add(fun trail->  
  32. //when the mouse button is moved and the left button is clicked  
  33.   
  34. if (trail.Button=System.Windows.Forms.MouseButtons.Left)then  
  35. //draw the object assign the color seleted from the color dialog as a brush color  
  36. gr.FillRectangle(new SolidBrush(color.Colors.[0]),new Rectangle(trail.X,trail.Y,5,5)))   
  37. //when the erase button is clicked  
  38. //erase the object drawn in the form  
  39. erasebutton.Click.Add(fun erase->gr.Clear(Color.White))   
  40. //when the exit button is clicked  
  41. //quit the form                                                                                                                
  42. exitbutton.Click.Add(fun quit->drawingform.Close())  
  43. //when the brush color button is selected                                                            
  44. colorbutton.Click.Add(fun colors->  
  45. //display the Color Dialog box  
  46. if colordlg.ShowDialog()=DialogResult.OK then  
  47. //store the value selected by the user in our colorblend object  
  48. color.Colors<-[|colordlg.Color|])  
  49. //executes our application  
  50. Application.Run(drawingform)  
Click the run icon once you are done entering these codes in the code editor window. You should see the following outputs:

Mouse Trails using Basic shapes

Obsessed with mouse trails? Try the following sample applications:
1. Line Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawLine(Pens.Peru,trail.X,trail.Y,trail.X+1,trail.Y+1))                                                                                                                  
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

2. Circle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawEllipse(Pens.IndianRed,new Rectangle(trail.X,trail.Y,10,10)))                                                                                                                      
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

3. Rectangle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawRectangle(Pens.Fuchsia,new Rectangle(trail.X,trail.Y,5,5)))                                                                                                                      
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

4. Arc Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawArc(Pens.Violet,new Rectangle(trail.X,trail.Y,5,5),180.0f,-180.0f))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

5. Filled-Arc/FillPie Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.FillPie(Brushes.MidnightBlue,new Rectangle(trail.X,trail.Y,10,10),180.0f,180.0f))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

6. Filled Circle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.FillEllipse(Brushes.Tomato,new Rectangle(trail.X,trail.Y,10,10)))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

7. Filled Rectangle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.FillRectangle(Brushes.Indigo,new Rectangle(trail.X,trail.Y,20,20)))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

Creating a Customized Mouse Pointer

Aside from using pre-defined mouse pointers such as Cursors.Arrow and Cursors.Cross, you can also use customized mouse pointers in Visual F#. Follow these steps for a simple example:

1. Download a cursor creator software such as Axialis CursorWorkShop or Icon Craft.

2. Create a .cur file and name it “pointer.cur”.

3. Start Visual F#>Create a new Project.

4. Enter the following codes:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let mouseform = new Form(Text="Cutom Mouse Pointer",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let customcur=new System.Windows.Forms.Cursor("pointer.cur")  
  13. mouseform.MouseHover.Add(fun cutom->mouseform.Cursor<-customcur)   
  14. mouseform.Controls.Add(exitbutton)                                                                                                  
  15. exitbutton.Click.Add(fun quit->mouseform.Close())                                                            
  16. //executes our application  
  17. Application.Run(mouseform)  

5. Click the Open Folder>bin>debug> then copy and paste pointer.cur.

6. Run your application

Printing an Image Data

To print an image or text, use a PrintDocument control. To following example shows how to print an image data, using a PrintDocument control.

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. open System.Drawing.Printing  
  10.   
  11. open System.Drawing.Imaging  
  12. let imageform = new Form(Text="Print Form",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  13. //creates our control  
  14. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  15. let loadbutton=new Button(Text="Load", Location=new System.Drawing.Point(120, 200))  
  16. let prnbutton=new Button(Text="Print", Location=new System.Drawing.Point(40, 200))  
  17. let pic=new PictureBox(SizeMode=PictureBoxSizeMode.StretchImage,Location=new System.Drawing.Point(20, 20),BorderStyle=BorderStyle.FixedSingle,Size=new System.Drawing.Size(100, 100))  
  18. let label=new Label(AutoSize=true,Location=new System.Drawing.Point(0, 120))  
  19. let dlg=new OpenFileDialog()  
  20. let gr=imageform.CreateGraphics()  
  21. let prn=new System.Drawing.Printing.PrintDocument()  
  22. imageform .Controls.Add(pic)  
  23. imageform.Controls.Add(loadbutton)  
  24. imageform.Controls.Add(label)  
  25. imageform.Controls.Add(prnbutton)  
  26. imageform.Controls.Add(exitbutton)  
  27. //sends the data to the printer  
  28. prnbutton.Click.Add(fun startprint->prn.Print())  
  29.   
  30. loadbutton.Click.Add(fun load->  
  31. //filter dialog result  
  32. dlg.Filter <- "JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif Images (*.gif)|*.gif"  
  33. //adds title to your dialog box  
  34.                    dlg.Title<-"Select an Image File"  
  35.                    if dlg.ShowDialog()=DialogResult.OK then  
  36. //creates a bitmap object  
  37. //assigns the image selected by the user as its value  
  38.                       let bmp=new System.Drawing.Bitmap(dlg.FileName)  
  39.                       bmp.RotateFlip(RotateFlipType.RotateNoneFlipNone)  
  40. //assigns the loaded image as a picturebox value  
  41.                       pic.Image<-bmp  
  42. //displays the image url in our label  
  43.                       label.Text<-"\t\tFilename:" + Convert.ToString(Convert.ToChar(32))+ (dlg.FileName))   
  44. //specifies the data to be printed  
  45. //in this case our image                        
  46. prn.PrintPage.Add(fun printdata->gr.DrawImage(pic.Image,10,10))  
  47. //close the form                                                                                                          
  48. exitbutton.Click.Add(fun quit->imageform.Close())                                           
  49. [<stathread>]                      
  50. //executes our application  
  51. Application.Run(imageform)  
  52. </stathread>  

Drawing Triangles and Circles

To draw a triangle, use the DrawLine or DrawPolygon method. Here’s an example that uses DrawPolygon method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Triangle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14. let array=[|new Point(0,150);new Point(150,10);new Point(300,150)|]  
  15. let pen=new Pen(Color.Blue,Width=12.0f)  
  16. draw.Graphics.DrawPolygon(pen,array))  
  17. graphicform.Controls.Add(exitbutton)  
  18. //executes our application  
  19. Application.Run(graphicform)  
To draw a filled triangle, use the FillPolygon method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Triangle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14. let array=[|new Point(0,150);new Point(150,10);new Point(300,150)|]  
  15. let brush=new SolidBrush(Color.Blue)  
  16. draw.Graphics.FillPolygon(brush,array))  
  17. graphicform.Controls.Add(exitbutton)  
  18. //executes our application  
  19. Application.Run(graphicform)  
To draw a circle, use the DrawEllipse method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Circle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14.   
  15. let pen=new Pen(Color.Blue,Width=12.0f)  
  16. draw.Graphics.DrawEllipse(pen,0.0f,0.0f,100.0f,100.0f))  
  17.   
  18. graphicform.Controls.Add(exitbutton)  
  19. //executes our application  
  20. Application.Run(graphicform)  
To draw a solid circle, use the FillEllipse method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Circle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14.   
  15. let brush=new SolidBrush(Color.Blue)  
  16. draw.Graphics.FillEllipse(brush,0.0f,0.0f,100.0f,100.0f))  
  17.   
  18. graphicform.Controls.Add(exitbutton)  
  19. //executes our application  
  20. Application.Run(graphicform)