[Haskell-cafe] Deriving with generics without values
Roman Cheplyaka
roma at ro-che.info
Fri Jul 12 10:57:27 CEST 2013
Well, in your case, you need not 'from', but 'to', in order to convert
from a generic representation to yours.
Take a look at how a similar task is done in SmallCheck:
https://github.com/feuerbach/smallcheck/blob/master/Test/SmallCheck/Series.hs#L180
https://github.com/feuerbach/smallcheck/blob/master/Test/SmallCheck/Series.hs#L352
Roman
* JP Moresmau <jpmoresmau at gmail.com> [2013-07-12 10:45:39+0200]
> Hello all,
> My problem is the following: I have my own data types, and I'd like to
> derive automatically instances of some type class from them. I've started
> looking at GHC.Generics, which offer tools to do exactly that. However,
> some functions of my typeclass do not take my data type as a parameter, but
> as a result. Basically:
> class MyClass where
> fromString :: String -> a
>
> data MyData=MkMyData {
> myField ::Int
> } deriving (Generic)
>
> and I want to automatically generate the instance instance MyClass MyData,
> using default methods, etc.
> The GHC Generic class does say that it uses a from function that convert
> from the datatype to its representation: from :: a ->
> Rep<http://www.haskell.org/ghc/docs/7.4.1/html/libraries/ghc-prim-0.2.0.0/GHC-Generics.html#t:Rep>
> a
> xfrom :: a -> Rep<http://www.haskell.org/ghc/docs/7.4.1/html/libraries/ghc-prim-0.2.0.0/GHC-Generics.html#t:Rep>
> a
> x
> But I don't have a "a" to start from! I see from the related papers that
> the automatically generated code from from actually does pattern matches on
> constructors, so I need a value, undefined won't work. However I see the
> GHC.Generics also provide :+: (Sums: encode choice between constructors).
> If I have to provide an value, then the choice between constructor has been
> done! The examples about generics on
> http://www.haskell.org/haskellwiki/GHC.Generics do provide an example of
> defining the instance for :+: but I don't understand how we can get there.
> If I have a class method that takes a value as a parameter, and I pass
> undefined to it, the code will crash, since it can't pattern match on
> undefined.
>
> Can somebody shed some light on this? Am I using the wrong tool for the
> job? How can I achieve what I want? I want the full type representation
> with sums, but without a value to start from.
>
> Thanks a million!
>
> JP
> --
> JP Moresmau
> http://jpmoresmau.blogspot.com/
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list