zell
zell

Reputation: 10204

Understanding the type of "failwith" in F#?

How to make sense of the type of failwith in F#?

> failwith;;
val it : (string -> 'a)

Why is it associated with a generic type 'a instead of an exception?

Upvotes: 0

Views: 204

Answers (1)

torbonde
torbonde

Reputation: 2459

Because 'a is the type of the return value, and a function cannot return values of multiple different types. If failwith returned an Exception, any other path in the function calling failwith would need to return an Exception as well. Keep in mind that, when a function calls failwith (which throws an exception) on a certain path, that path actually doesn't return a value, but rather interrupts the execution flow.

In the case below, the generic return type of failwith is forced to be an int, because a different path in the code returns an int.

enter image description here

Consider then this case instead, where we actually return an Exception. Notice that it generates a compilation error.

enter image description here

Upvotes: 3

Related Questions