A pedant that hangs out in the dark corner-cases of the web.

Monday, May 23, 2011

F# Source that runs interactively or compiles

Here's a simple way to create code that you can run with FSI or compile with FSC:

#if INTERACTIVE
// any #load, #r, or other fsi directives, e.g.:
#r "System.Configuration.dll"
#else
module ModuleName
#endif

// … code …

let main (args:string[]) =
// … main body …

#if INTERACTIVE
main fsi.CommandLineArgs.[1..]
#else
[<EntryPoint>]
let Main args =
try
main args ; 0
with
| ex -> printfn "%s" (string ex) ; 1
#endif

Name the file with a .fsx extension, then you can compile it normally, or run it as a script with fsi filename.fsx -- args, or #load it from within FSI!