let div0 n =
n / 0;;

let safeDiv0 (n: Lazy<_>) =
try
printf "%d\n" (div0 (n.Force()))
with
e -> printf "Error %d\n" (n.Force())

if I run

safeDiv0 (lazy 5)

the error is handled.

However, if I run

safeDiv0 (lazy (div0 5))

I get

System.DivideByZeroException: Attempted to divide by zero.
at Microsoft.FSharp.Control.Lazy`1.UnsynchronizedForce()
at Microsoft.FSharp.Control.Lazy`1.Force()
at FSI_0005.safeDiv0(Lazy`1 n)
at <StartupCode$FSI_0007>.$FSI_0007._main()

It looks like F# isn't being very lazy about evaluating (div0 5).

So your error might be happening when (body a) is being evaluated as an argument, since F# seems to be doing that before (body a) is forced?

I can't get around this with

> let x = lazy (div0 5);;

val x : Lazy<int>

> safeDiv0 x;;
System.DivideByZeroException: Attempted to divide by zero.
at Microsoft.FSharp.Control.Lazy`1.UnsynchronizedForce()
at Microsoft.FSharp.Control.Lazy`1.Force()
at FSI_0005.safeDiv0(Lazy`1 n)
at <StartupCode$FSI_0011>.$FSI_0011._main()
stopped due to error

either. So maybe I'm doing something wrong here.

Or maybe F# forces a value when it is passed as an argument, and it's supposed to. I'm pretty confused at this point.

By on 2/26/2009 4:37 PM ()

You are calling n.Force() in the printout of the error, which will just raise the same exception again. Your 'with e' clause should print 'e', and then maybe things will be less confusing.

By on 2/26/2009 7:44 PM ()

Doh!

OK, throw out that theory...

By on 2/27/2009 5:33 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper