Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#'s "Hello, world" with 2 fs files

Tags:

f#

I come from C# background to F#. So far I wrote simple programs and spent a lot of time in F# interactive.

I'm stuck creating a VS F# project with two .fs files.

Sample code:

// part 1: functions
let rec gcd (a : uint64) (b : uint64) =
    if b = 0UL then a
    else gcd b (a % b)

// part 2: main()
let a, b = (13UL, 15UL)
do printfn "gcd of %d %d = %d" a b (gcd a b)

I'd like to have two .fs files, namely, Alg.fs and Program.fs, so that Program.fs would contain the code I'm working and Alg.fs having algorithms.

Taken steps:
I've created the two files. Compiler gave an error: Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'

I've inserted module Program and module Alg. The complied program executes only the code from Alg.fs completely ignoring Program.fs...

I'm using F# 2.0 in Visual Studio 2010.
P.S. I've googled and checked some posts, and read documentation on modules and saw relative questions before asking.

like image 670
bohdan_trotsenko Avatar asked Apr 16 '12 20:04

bohdan_trotsenko


2 Answers

Sounds like this is an order-of-files-in-the-project issue. The last file is the entry point ("main method"), sounds like you have Alg.fs last, and you need Program.fs last. You can re-order them via the right-click context menu in VS Solution Explorer.

like image 85
Brian Avatar answered Nov 08 '22 14:11

Brian


There are at least three separate things that need to be looked at here:

  1. As mentioned by @Brian, the order of source control files is also the compile order. This matters in F# where type inference is heavily used. Make sure Alg.fs comes before Program.fs in your Visual Studio file list (try this: select Program.fs and hit Alt+Down Arrow until it's at the bottom).

  2. Since Alg.fs and Program.fs are now in modules, you need to actually open the Alg module in Program to get access to its bindings (open Alg), or add the [<AutoOpen>] attribute on Alg.

  3. As @Daniel says, the last problem could be the definition of the entry point to the program. You need either an [<EntryPoint>] attribute on a top level binding that is also the last function in the last file. Alternatively, this defaults to the last binding in the last file anyway, just make sure it has the right signature (see Daniel's link).

like image 28
yamen Avatar answered Nov 08 '22 15:11

yamen