How to call a method within a constructor?

已答覆 How to call a method within a constructor?

  • Monday, April 01, 2013 6:24 PM
     
      Has Code

    Hi,

    I have a question about classes in F# and hope you can help.

    I'm trying call a static method from a constructor like this:

    type Node(one : Node option, two : Node option) =
      member this.Value = GetValue one + GetValue two
      static member GetValue (some : Node option) =
        match some with
        | Some(s) -> s.Value
        | None -> 0

    The desired result looks like this in C#:

    class Node {
      readonly Int32 Value;
      static Int32 GetValue(Node some) {
        return some == null ? 0 : some.Value;
      }
      public Node(Node one, Node two) {
        Value = GetValue(one) + GetValue(two);
      }
    }

    Could you suggest a way to resolve this?


All Replies

  • Monday, April 01, 2013 7:50 PM
    Moderator
     
     Answered Has Code

    In F# you need to qualify static method names with the type name (even if you're defining another member within the same type):

      member this.Value = Node.GetValue one + Node.GetValue two
    

  • Monday, April 01, 2013 7:51 PM
     
     Answered Has Code

    Use type qualifier: Node.GetValue

    type Node(one : Node option, two : Node option) =
      member this.Value = Node.GetValue one + Node.GetValue two
      static member GetValue (some : Node option) =
        match some with
        | Some(s) -> s.Value
        | None -> 0
    


    Petr

    • Marked As Answer by Borys Dibrov Monday, April 01, 2013 8:04 PM
    •  
  • Tuesday, April 02, 2013 4:19 AM
     
      Has Code

    You can use private "let" functions instead:

    type Node(?one: Node, ?two: Node) =
        let getValue (node: Node option) = 
            match node with 
            | Some n -> n.Value
            | _ -> 0
        member this.Value = getValue one + getValue two