Question

Following is the function, which I wrote in F# editor and it works as I expected (answer:18).

let quadruple x = x*2
let cal(u:int) = quadruple u + 10;
let result = cal 4

But if I change the order of code, such as

let cal(u:int) = quadruple u + 10;
let quadruple x = x*2
let result = cal 4

I am getting "the value or constructor 'quadrule' not defined". From the error, I presume, the failure is due to a function call before its declaration. For me, it something like an interpreter style.

Question: Why such constrains ? Is this purposeful to keep some compatibility issue ? Or is it because I don't have any module/class defined ?

Was it helpful?

Solution

Despite the minimal amount of type declarations required in idiomatic code, F# is a statically strongly typed language. This is possible because of compiler ability to infer types where it can be done unambiguously thru the process known as type inference.

Simplistically, the processing direction that type inference works in F# is one pass top down left to right over the code. This factor affects both intra- and inter-file placement of definitions and usage of F# code elements.

Applying this principle to your second snippet: when compiler first comes over quadruple in the first line there is nothing known about the type of this element based on information parsed so far that would allow to disambiguat it; that's what the error message communicates.

Note: there is a certain deviation from this principle in the area of F# related to OOP, where usage before definition is allowed to some extent, like for Code property usage in a Sample class method Double() below, where it is used prior to the property definition:

type Sample() =
    member this.Double() = this.Code * 2
    member this.Code with get() : int = 3

For the fine-grain details upon type inference workings the best place to check is F# Language Specification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top