Latest update April 1, 2015.

To prevent spambots from collecting mail addresses, all mail addresses on this page have the "@" replaced by "#".

Assignment 1 - Getting started

1) Start up F# on your computer by starting Visual Studio and the F# Interactive Environment by selecting the View -> Other Windows -> F# Interactive menu item.

Enter a few arithmetic expressions at the prompt and press ";;" + enter to evaluate them. (You can also mark expressions to be evaluated with the mouse, and evaluate them with "ALT" + "Enter".) Look at what is returned: you can see both the value that is returned, and its type. The identifier it will be bound to the returned value, and can be used in the next expression to be evaluated. Now try evaluating the following expressions:

   3 :: [4; 5; 2; 7];;
   List.length [4; 5; 2; 7];;
   [4; 5; 2; 7] :: 3;;

The evaluation of the last expression generated an error. Why? What can you do to make it work (that is, to insert the element 3 at the end of the list [4; 5; 2; 7])?

2) You can only evaluate expressions that will fit on a single line at the prompt. If you want to write more complex expressions, or declare your own functions, you need to put the code in a file and then load that file into the F# Interactive Environment.

Create the file "Lab1.fs". You can use any text editor you like, but Visual Studio is recommended. Now declare some values in the file, for example:

   module Lab1

   let x = 42
   let myName = "Kalle"
   let age = 25
   let y = 4 + 2

(Note that you don't have to insert ";;" after each declaration in the file: this is only necessary in the interactive environment, to signal that a line of input is ready to interpret.)

The #light directive allows a "light" syntax, with some convenient shortcuts. Save the file and load it into the system by writing: #load "c:\\...\\Lab1.fs";;. You open the module by writing open Lab1;;. Then you can inspect the values by simply writing x;;, etc. The file and the module do not need to have the same name; however, it is convenient to do so.

Enter the following declarations into the file and evaluate. What values will b and c hold, and why?

   let a = 5
   let b = let a = 10 in a + 5
   let c = a + b

3) Now it is time to declare some functions.

4) Define the function max2 that takes two integers as arguments and returns the largest of them. Then define the function max_list that returns the largest of the elements in a nonempty list of integers by calling max2. For the empty list, it should abort with an error message (raising an exception).

Björn Lisper