2

Using Visual Studio 2015 Update 3 and fsi.exe from F# v4.0 I' trying to run this script:

//error.fsx

#if INTERACTIVE
    let msg = "Interactive"
#else
    let msg = "Not Interactive"
#endif

let add x y =
    x + y

printfn "%d" (add 1 2)

Output: error.fsx(12,15): error FS0039: The value or constructor 'add' is not defined

If I then comment out the #if-#else-#endif block, it works fine:

// fixed.fsx

//#if INTERACTIVE
//    let msg = "Interactive"
//#else
//    let msg = "Not Interactive"
//#endif

let add x y =
    x + y

printfn "%d" (add 1 2)

Output: 3

I'm sure I'm doing something wrong (rather than this being a bug) but I can't for the life of me figure out how to make this work.

Thoughts?

Matt Klein
  • 7,856
  • 6
  • 45
  • 46

1 Answers1

5

This is caused by the indentation of let msg. The following works fine:

#if INTERACTIVE
let msg = "Interactive"
#else
let msg = "Not Interactive"
#endif

let add x y =
    x + y

printfn "%d" (add 1 2)

I do have to say, I'm not entirely sure why the code gives exactly the error message you mention - I suspect this is a bug in the error reporting and it wold be worth reporting it to the F# team. At the very least, there should be a sensible error message!

It seems that with the indentation, the F# parser actually parses the code as follows:

let msg = "Interactive"
let add x y =
  x + y 
    printfn "%d" (add 1 2)

The spacing before let msg causes the compiler to treat printfn as being indented too. You can see that this is the case if you look at the type of the y variable in your editor using a tool tip...

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • Thanks Tomas! As soon as you pointed that out it made sense. I grabbed the example code from [here](http://brandewinder.com/2016/02/06/10-fsharp-scripting-tips/) (#3) and just assumed that it would work as it. Thanks much! – Matt Klein Sep 19 '16 at 20:21
  • It is a funny error - I spent a bit more time to figure out what's going on and I think this is a bug (in error reporting, at least). – Tomas Petricek Sep 19 '16 at 20:27
  • Matt Klein: sorry about that! I'll fix the post, possibly some formatting got mangled there. – Mathias Sep 19 '16 at 20:30
  • 2
    Woah, you're fast Mathias! I just finished created a Disqus account so I could let you know directly on your blog! – Matt Klein Sep 19 '16 at 20:31
  • Thanks again @TomasPetricek ! I've submitted this issue to the F# team [here](https://github.com/Microsoft/visualfsharp/issues/1564). – Matt Klein Sep 26 '16 at 16:13