Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does F# failwith return a generic type rather than Exception type

Tags:

exception

f#

fsi

According to the docs the failwith function returns an Exception But the function signature is string -> 'a

Why is the signature not string -> Exception ?

like image 530
OrdinaryOrange Avatar asked Jun 23 '19 07:06

OrdinaryOrange


People also ask

What does f stand for in math?

more ... A special relationship where each input has a single output. It is often written as "f(x)" where x is the input value. Example: f(x) = x/2 ("f of x equals x divided by 2")

What is the formula of f x?

The slope of a linear function is calculated by rearranging the equation to its general form, f(x) = mx + c; where m is the slope. The vertex of a quadratic function is calculated by rearranging the equation to its general form, f(x) = a(x – h)2 + k; where (h, k) is the vertex.

What is f apostrophe?

The derivative of f(x) is written using an apostrophe after the f. The notation is f´(x) or y´ The notation dy/dx is also commonly used. First look at the constant function, or f(x) = k where k is a constant value, for example f(x) = 2 or y = 2 The graph is shown here.

Does Y equal FX?

Remember: The notation "f (x)" is exactly the same thing as "y". You can even label the y-axis on your graphs with "f (x)", if you feel like it.


1 Answers

The docs don't say that failwith returns an Exception. It says it generates an F# exception. The exception system is separate from the normal control flow of returning values. Hence the name, it's exceptional.

Exceptions, when "thrown" (which is a less ambiguous term than "generated" as used in the docs, I think), will travel up the stack until encountering a try ... with construct that handles this particular type of exception, or if not will terminate the program. See the F# docs on exception handling for details.

failwith returns 'a so that it can be used anywhere, since 'a can be inferred to be anything. It can pretend to return anything because it never actually returns at all, unlike most functions, it always throws an exception instead. If it had returned Exception it would only be able to be used in expressions that are expected to evaluate to Exception, which are exceptionally unusual since exceptions are usually thrown, not returned. For example, given:

if i > 0 then
  i
else
  failwith "i is negative"

If failwith had returned Exception, the compiler would complain here about an int being expected instead of an Exception since the first branch evaluates to an int. But since failwith returns an 'a instead, it's inferred to be an int itself and everything is fine.

like image 107
glennsl Avatar answered Oct 01 '22 01:10

glennsl