Michael Ray Lovett
Michael Ray Lovett

Reputation: 7050

What control expression in f# allows calling functions with different signatures?

Let's say you have some item you want to test in your code, and based on its value you want to call one of several functions, but the functions have different signatures - how can you do this in f#?

I've tried to do this from within pattern matching and within if then else expressions, and both complain because the functions don't have the same value.

For example

let fn1 () = ()
let fn2 (name : string) = ()

let a = 1

if a = 1 then fn1 else fn2 "mary"

This causes "expression expected unit -> unit, but has type unit". The error goes away if I make the function signatures match.

I understand that both if-then-else and pattern-matching are expressions and thus all branches have to return the same type. (I admit I was surprised that this means if you call functions in the different branches their signatures have to exactly match!)

At any rate, how are you supposed to do this in f#?

My specific case in point is that I have a small script that examines some user input and based on it, calls one of several functions, representing uses cases that correspond to the user input...each of these functions has a different signature and I can't figure out what kind of a "control expression" in f# that would allow me to test the input and invoke these functions.

Michael

Upvotes: 0

Views: 77

Answers (1)

phoog
phoog

Reputation: 43046

You're looking for this:

let fn1 () = ()
let fn2 (name : string) = ()

let a = 1

if a = 1 then fn1 () else fn2 "mary"

The way you had it, the "then" value is a function of type unit -> unit. You need to call it, so it has a value of unit. The () is the argument to the function, analogous to the "mary" argument for fn2.

Upvotes: 4

Related Questions