How do I write, “if typeclass a, then a is also an instance of b by this definition.”

后端 未结 6 944
故里飘歌
故里飘歌 2020-11-29 04:36

I have a typeclass MyClass, and there is a function in it which produces a String. I want to use this to imply an instance of Show, s

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 05:05

    As Ed Kmett pointed out, this is not possible at all for your case. If however you have access to the class you want to provide a default instance for, you can reduce the boilerplate to a minimum with a default implementation and constrain the input type with the default signature you need:

    {-# LANGUAGE DefaultSignatures #-}
    
    class MyClass a where
        someFunc :: a -> Int
    
    class MyShow a where
        myShow :: a -> String
        default myShow :: MyClass a => a -> String
        myShow = show . someFunc
    
    instance MyClass Int where
        someFunc i = i
    
    instance MyShow Int
    
    main = putStrLn (myShow 5)
    

    Note that the only real boilerplate (well, apart from the whole example) reduced to instance MyShow Int.

    See aesons ToJSON for a more realistic example.

提交回复
热议问题