Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

F# functions

2009-09-01

Functions are declared using the let keyword, followed by a name, a parameter list and a definition.

This creates a function that adds to values and returns the result (first line). The two middle lines calls the function.

let myFunction x y = x + y

let result1 = myFunction 10 20
let result2 = myFunction 15 25

printfn "%d %d" result1 result2

The last line prints the result to the screen. It should be 30 40.

To specify the type of a parameter, you encapsulate it in parentheses, together with the type name. In this example, only the first parameter has a given type:

let myFunction (x:int) y = x + y

To specify the return type, add a colon followed by a type name. The following function divides a value in three. The first line is the function declaration, the second line is a call (note that I cast a int constant to a float), and the third line prints the result to the screen.

let divInThree (t:float) = t / (float)3 : float
let result = divInThree ((float)18)
printfn "%f" result

The result should be 6.

Categories: Microsoft .NET

Tags: F#

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips