Haskell's "deriving Show" in F#?
Asked Answered
C

1

10

In Haskell it is easy to make an algebraic type/discriminated union "displayable" as a string by simply adding deriving Show to the type definition.

In F# I end up writing things like:

type Pos = 
    | Pos of int * int
    override this.ToString() = 
        match this with
        Pos(startp, endp) -> sprintf "Pos(%d, %d)" startp endp

and obviously it gets much worse with more complicated types.

Any way to get something like deriving Show in F#?

Copolymerize answered 19/2, 2010 at 10:29 Comment(1)
Err, F# already does this for you automatically so you don't have to write deriving Show.Indevout
F
21

F# printing functions such as printf are able to format reasonably any data type if you use the %A format specifier (they use ToString if you specify %O). You can implement ToString using sprintf which returns the formatted string:

type Pos =  
    | Pos of int * int 
    override x.ToString() = sprintf "%A" x 

This prints for example "Pos (1, 2)" and it works for most of the F# types (lists, unions, records, tuples). It's a bit longer than just adding deriving Show but at least you don't have to implement the printing yourself.

Frohman answered 19/2, 2010 at 11:37 Comment(1)
and how could one achieve deriving Read in F#?Xylia

© 2022 - 2024 — McMap. All rights reserved.