How to call a method within a constructor?
-
Monday, April 01, 2013 6:24 PM
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?
- Edited by Borys Dibrov Monday, April 01, 2013 6:24 PM
All Replies
-
Monday, April 01, 2013 7:50 PMModerator
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
- Proposed As Answer by Keith BattocchiMicrosoft Contingent Staff, Moderator Monday, April 01, 2013 7:50 PM
- Marked As Answer by Borys Dibrov Monday, April 01, 2013 8:04 PM
-
Monday, April 01, 2013 7:51 PM
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
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