Eben Kadile
Eben Kadile

Reputation: 779

Can you give functions specific type signatures in F#?

Hi I've started learning F# and I'm wondering whether or not you can constrain the types of the inputs and outputs of functions.

I tried doing this:

main : unit
let main = printf "Hello World\n" |> (fun x -> printf "Goodbye World\n")
let _ = main

and I also tried putting let before main in the first line. Neither worked. Is there any way to do this sort of thing in F#? I think it's a nice feature of Haskell.

Upvotes: 2

Views: 64

Answers (2)

Thomas Devries
Thomas Devries

Reputation: 889

Input and outputs are constrained however they are implicitly constrained for example the following code.

let add1int arg = number+1
let add1double arg = number+1.0

The function add1int takes an int and returns an int. The compiler knows this because the value of arg is added to another int. Likewise the add1double takes a double and returns a double.

However if you want to explicitly declare your inputs and output types instead of leaving it up to the compiler (This can increase readability in some places).

let add1int (number:int):int = number+1
let add1double (number:double):double = number+1.0

Upvotes: 1

Fyodor Soikin
Fyodor Soikin

Reputation: 80734

Yes, this is totally possible:

let main : unit = printf "Hello World\n" |> (fun x -> printf "Goodbye World\n")

Also, a couple minor points:

First, instead of \n at the end, you can use printfn.

Second, the x in the lambda expression is redundant, and so is the lambda expression itself. To sequence multiple calls, you can simply list them in order, each on new line (or separated with a semicolon):

let main : unit =
    printfn "Hello World"
    printfn "Goodbye World"

Third, this way you're not defining a function, but a value. F#, unlike Haskell, is not lazily evaluated, and so the whole body of this definition will be executed once, as soon as its scope begins, as opposed to every time you call it. If you want to define a function, give it some parameters. If you don't have any meaningful parameters to give it, make it a single unit value:

let main () : unit =
    printfn "Hello World"
    printfn "Goodbye World"

Upvotes: 4

Related Questions