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)