6 people like it.

How to check whether an F# function/method has been initialized

Sometimes, we may run into this kind of situation that we want to check if the given method/function has been initialized. We all know this is fairly easy in C#, since we can use delegate to invoke the function , then verify if the value of delegate is null. But in F# , delegate is rarely needed because F# can treat a function as a value, without the need for any wrapper. So , here is an easy way to solve this problem.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
C# code:
public class Class1
    {
        public delegate void CancelHandler(Object sender);
        public CancelHandler onCancel;
 
        public void Verify()
        {
            if (onCancel == null)
            {
                //do something;
            } 
        } 
    }
		
Usually , the null is converted to option type in F# , but in this situation , that
	
F# code:

type public Class1() =
    [<DefaultValue>]
    val mutable public onCancel : System.Object -> unit
 
    member public this.Verify() = 
        if box(this.onCancel) = null then
            ()//do something
type 'T option = Option<'T>

Full name: Microsoft.FSharp.Core.option<_>
Multiple items
type DefaultValueAttribute =
  inherit Attribute
  new : unit -> DefaultValueAttribute
  new : check:bool -> DefaultValueAttribute
  member Check : bool

Full name: Microsoft.FSharp.Core.DefaultValueAttribute

--------------------
new : unit -> DefaultValueAttribute
new : check:bool -> DefaultValueAttribute
namespace System
Multiple items
type Object =
  new : unit -> obj
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member GetType : unit -> Type
  member ToString : unit -> string
  static member Equals : objA:obj * objB:obj -> bool
  static member ReferenceEquals : objA:obj * objB:obj -> bool

Full name: System.Object

--------------------
System.Object() : unit
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
val box : value:'T -> obj

Full name: Microsoft.FSharp.Core.Operators.box

More information

Link:http://fssnip.net/bW
Posted:11 years ago
Author:ZackZhou
Tags: f# , null