Programming:F Sharp Basic Concepts

From testwiki
Jump to navigation Jump to search

Template:Prognav


Template:FsharpTitle


Now that we have a working installation of F# we can explore the syntax of F# and the basics of functional programming.

We'll start of in the Interactive F Sharp environment as this gives us some very valuable type information, which helps get to grips with what is actually going on in F#.

Open a command-line prompt and type fsi

Basic Maths

Functions as First-Order Types

F# is a functional programming language and this means that functions are first-order data types: They can be declared and used in exactly the same way that any other variable can be used.

In an imperative language like Visual Basic there is a fundamental difference between variables and functions.

Dim myVal as Integer
Dim myParam as Integer
myParam = 2
Public Function MyFunc(Dim param as Integer)
  MyFunc = (param * 2) + 7
End Function
myVal = MyFunc(myParam)

In the previous code there is a difference between the syntax for defining and evaluating a function and defining and assigning a variable. In the preceding Visual Basic code we could perform a number of different actions with a variable:

  • we can create a token (the variable name) and associate it with a type
  • we can assign it a value
  • we can interrogate its value
  • we can pass it into a function or sub-routine (which is essentially a function that returns no value)
  • we can return it from a function

In a functional programming language we can consider functions to be equal to all other data types. That means that we can:

  • we can create a token (the function variable name) and associate it with a type
  • we can assign it a value (the actual calculation)
  • we can interrogate its value (perform the calculation)
  • we can pass a function as a parameter of another function or sub-routine
  • we can return a function as the result of another function

We will consider a fairly simple first case, a simple cubic expression and a function that performs differentiation.

Numerical Differentiation

We will define a function to represent a very simple cubic equation:

f(x)=x3
> let cubic_function x = x *. x *. x;;
val cubic_function : float -> float

It is straight-forward to use this function.

> cubic_function 1.0;;
val it : float = 1.0
> cubic_function 2.0;;
val it : float = 8.0
> cubic_function 1.3;;
val it : float = 2.197
> cubic_function -9.0;;
val it : float = -729.0


d(f,x)=f(x+0.01)f(x)f(x)


Template:Prognav