Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does F# interactive console not consider "assert (2=3)" as wrong?

Tags:

f#

I send this line to F# interactive console in Visual Studio

assert (2=3)

To my surprise, the console does not report errors, but

 

val it : unit = ()

Similarly, if I run

printf ("hello!")

assert (2=3)

printf ("hello2")

on an REPL, I got "hellohello2" without any error messages.

How could I make the F# interactive tell me 2=3 is wrong?

like image 221
zell Avatar asked Jul 20 '20 08:07

zell


1 Answers

Under the cover, the assert keyword translates to a method call to the Debug.Assert method from the .NET library (see the method documentaiton). This has a conditional compilation attribute [Conditional("DEBUG")], meaning that the call is only included if the symbol DEBUG is defined.

By default, this is not the case in F# Interactive. You can do that by adding --define:DEBUG to the command line parameters for fsi.exe. This will be somewhere in the options of your editor, depending on what you are using. For example, in Visual Studio, you need something like this:

enter image description here

EDIT: How to do something like this if you do not want to modify the command line parameters? This really depends on what exactly behaviour you want. The default behaviour of assert is that it shows a message box where you can either terminate the program or ignore the error. You could do that using:

open System.Windows.Forms

let ensure msg b = 
  let res = 
    MessageBox.Show("Assertion failed: " + msg + 
      "\n\nDo you want to terminate the exection? Press 'Yes' " + 
      "to stop or 'No' to ignore the error.", "Assertion failed", 
      MessageBoxButtons.YesNo)
  if res = DialogResult.Yes then exit 42

ensure "Mathematics is broken" (2=3)
like image 98
Tomas Petricek Avatar answered Oct 03 '22 02:10

Tomas Petricek