Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Override ToString in a Composite Type in F#?

I'm learning about creating composite* types in F# and I ran into a problem. I have this type and a ToString override.

type MyType =
    | Bool of bool
    | Int of int
    | Str of string
    with override this.ToString() =
            match this with
            | Bool -> if this then "I'm True" else "I'm False"
            | Int -> base.ToString()
            | Str -> this

let c = Bool(false)
printfn "%A" c

I get an error inside the ToString override that says "This constructor is applied to 0 argument(s) but expects 1". I was pretty sure this code wouldn't compile, but it shows what I'm trying to do. When I comment out the override and run the code, c is printed out as "val c : MyType = Bool false". When I step into that code, I see that c has a property Item set to the boolean false. I can't seem to access this property in the code however. Not even if I annotate c.

How should I be overriding ToString in this situation?

* I'm pretty sure these are called composite types.

like image 692
user2023861 Avatar asked Dec 08 '14 15:12

user2023861


People also ask

How do I override toString method in exception?

To display the message override the toString() method or, call the superclass parameterized constructor bypassing the message in String format. Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword.

Can toString be overridden?

Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.


1 Answers

When you are using a Discriminated Union (DU) (that's the appropriate name for that type), you need to unpack the value in the match statement like this:

type MyType =
    | Bool of bool
    | Int of int
    | Str of string
    with override this.ToString() =
            match this with
            | Bool(b) -> if b then "I'm True" else "I'm False"
            | Int(i) -> i.ToString()
            | Str(s) -> s

let c = Bool(false)
printfn "%A" c

The Item property that you're seeing is an implementation detail and is not intended to be accessed from F# code. Merely using this doesn't work because the DU is a wrapper around the value, so this refers to the wrapper, not to the contained value.

like image 160
N_A Avatar answered Oct 31 '22 18:10

N_A