Reputation: 10204
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
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
.
Consider then this case instead, where we actually return an Exception
. Notice that it generates a compilation error.
Upvotes: 3