sdgfsdh
sdgfsdh

Reputation: 37121

Functions that accept functions in F#

I would like to make a function that accepts two values and a function. I am having trouble understanding the syntax, so I have made a minimal example:

let foo (x : int, y : int, func : int -> int -> int) =
    func(x, y)

An intended output:

> foo(2, 3, fun x y -> x + y)
5

However I get the compilation error:

The expression was expected to have type int, but here has type 'a * 'b 

How should this be written?

Upvotes: 1

Views: 127

Answers (2)

DaveShaw
DaveShaw

Reputation: 52818

You should call func passing the args like this

func x y

Using parens like you would in a C type language will create a tuple, which is what 'a * 'b is.

Also when you declare/call foo you are using tuples too.

You can probably just do this

let foo x y f =
    f x y

And let type inference figure it out. Putting things in brackets like (x, y) is creating tuples, when you don't need to.

Upvotes: 6

Ringil
Ringil

Reputation: 6537

If you want to do type inference and curried arguments you can do:

let foo (x : int) (y : int) (func : int -> int -> int) =
    func x y

Using it like foo 2 3 (fun x y -> x + y)

If you want to use a tuple you can do:

let foo (x, y, func) =
    func x y

Then you can use it like in your example: foo(2, 3, fun x y -> x + y)

If you want to do type inference and a tuple you can do:

let foo ((x, y, func) : (int * int * (int -> int -> int))) =
        func x y

and use it like when it was just tupled.

Upvotes: 3

Related Questions