Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to view the generated code for derived instances / deriving in Haskell

So, in Haskell, it's really easy to do this:

data Foo = Bar | Baz
    deriving (Read, Show)

This is great, but I'd like to be able to pass some data as a string from Haskell to the Elm language. The languages are similar enough that, if I had a Haskell implementation of Read, I could easily convert it to Elm by hand.

The problem is, when I use deriving, the function is automatically generated, but I can't actually see what it does.

I'm wondering, is there a way to automatically generate the code for parsing and showing using Read and Show, so that I could actually see the code itself?

like image 525
jmite Avatar asked Aug 30 '13 17:08

jmite


People also ask

What is deriving show in Haskell?

Deriving means that your data type is automatically able to "derive" instances for certain type classes. In this case BaseballPlayer derives Show which means we can use any function that requires an instance of Show to work with BaseballPlayer .

What is an instance in 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.


2 Answers

You can use the the -ddump-deriv GHC option to see the code for derived instances:

ghc -ddump-deriv test.hs  [1 of 1] Compiling Test             ( test.hs, test.o )  ==================== Derived instances ==================== Derived instances:   instance GHC.Show.Show Test.FooBar where     GHC.Show.showsPrec _ Test.Foo = GHC.Show.showString "Foo"     GHC.Show.showsPrec _ Test.Bar = GHC.Show.showString "Bar"     GHC.Show.showList = GHC.Show.showList__ (GHC.Show.showsPrec 0)   Generic representation:    Generated datatypes for meta-information:    Representation types: 
like image 57
bennofs Avatar answered Sep 21 '22 03:09

bennofs


For stack:

stack build --ghc-options="-ddump-deriv" 

Output in my specific case is: .stack-work/dist/x86_64-linux-nix/Cabal-2.4.0.1/build/app/app-tmp/src/

like image 35
Chris Stryczynski Avatar answered Sep 23 '22 03:09

Chris Stryczynski