Even more generalized newtype deriving

雨燕双飞 提交于 2019-12-04 03:58:36
Philip JF

Look, GeneralizedNewtypeDeriving is unsafe. In that vein, here is an unsafe way of doing it

{-# LANGUAGE GADTs, ConstraintKinds #-}
import Data.Monoid
import Unsafe.Coerce

data Dict c where
  Dict :: c => Dict c

newtype Wrapper a = Wrapper a

addDictWrapper :: Dict (f a) -> Dict (f (Wrapper a))
addDictWrapper = unsafeCoerce

you can then use it anytime you need the typeclass instance

intWrapperNum :: Dict (Num (Wrapper Int))
intWrapperNum = addDictWrapper Dict

two :: Wrapper Int
two = case intWrapperNum of
           Dict -> 1 + 1

this system of passing around explicit dictionaries is highly general, and has a pretty good (although experimental) library to support it called Data.Constraint

I'm afraid there is no direct way how to do that in GHC. But I think you could solve your problem using Template Haskell.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!