Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell's "deriving Show" in F#?

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#?

like image 787
Miron Brezuleanu Avatar asked Feb 19 '10 10:02

Miron Brezuleanu


People also ask

What does deriving show do in Haskell?

The second line, deriving (Eq, Show) , is called the deriving clause; it specifies that we want the compiler to automatically generate instances of the Eq and Show classes for our Pair type. The Haskell Report defines a handful of classes for which instances can be automatically generated.

What is show in Haskell?

The shows functions return a function that prepends the output String to an existing String . This allows constant-time concatenation of results using function composition.

What is instance Haskell?

An instance of a class is an individual object which belongs to that class. In Haskell, the class system is (roughly speaking) a way to group similar types. (This is the reason we call them "type classes"). An instance of a class is an individual type which belongs to that class.


1 Answers

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.

like image 183
Tomas Petricek Avatar answered Oct 17 '22 17:10

Tomas Petricek