F# Command Line File Order?
Why does it seem like the order of the arguments matters for F#?开发者_如何学C It doesn't matter for C# (which uses the same compilation model). When I try this:
# main.fs
module Main
let main = Printer.print_repeatedly 5 "hello, world"
# printer.fs
module Printer
let print_repeatedly n str = for x in 1..n do printfn "%s" str
And I execute the compiler (both Microsoft's and Mono's) with main.fs preceding printer.fs, I get an error:
main.fs(4,12): error FS0039: The namespace or module 'Printer' is not defined
If I do printer.fs before main.fs on the command line, it's fine. Is there a reason the compiler requires this for F#?
In F#, the order of files passed to the compiler absolutely does matter: the F# compiler reads programs strictly left-to-right and top-to-bottom. Variables and types may only refer to those defined before them, unless you explicitly indicate a mutually recursive relationship via and
.
If you come from C#, this may seem like a limitation at first. But you learn that in practice it is actually an incredibly effective enforcement of code organization and prevents recursive reference madness.
Note that forward references are actually a fairly modern feature of programming languages and compilers (you don't get them for "free"), if you've ever had to work with early C++ compilers you may remember the need for forward declarations to enable this (having the compiler do the work cost memory which has not always been so abundant).
精彩评论