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"