Daniil Iaitskov
Daniil Iaitskov

Reputation: 6069

How to use DerivingVia with Arbitrary

I need to write a heck of Arbitrary instances for newtypes. I am trying to cheap on typing and use deriving via GHC extension.

My use case complies, but blows up in runtime! GHCi is 8.8.4

import Test.QuickCheck (Gen, elements, listOf, Arbitrary, arbitrary)
genSafeChar = elements ['a'..'z'] 
genSafeString = listOf genSafeChar
newtype SafeString = SafeString String deriving (Show, Eq)
instance Arbitrary SafeString where arbitrary = fmap SafeString genSafeString
:set -XDerivingVia
newtype MyS = MyS String deriving (Arbitrary, Show) via SafeString
> MyS "3"
SafeString "3"

Show is working fine but Arbitrary doesn't!

> :t (arbitrary :: Gen SafeString)
(arbitrary :: Gen SafeString) :: Gen SafeString
> :t (arbitrary :: Gen MyS)

<interactive>:1:2: error:
    • Couldn't match type ‘SafeString’ with ‘MyS’
      Expected type: Gen MyS
        Actual type: Gen SafeString
    • In the expression: (arbitrary :: Gen MyS)

Upvotes: 3

Views: 147

Answers (0)

Related Questions