简单的GHC.Generics示例

mhw*_*bat 4 generics haskell

我正在尝试通过关注wiki文章创建如何使用GHC.Generics的最小工作示例.这就是我所拥有的:

{-# LANGUAGE DefaultSignatures, DeriveGeneric, TypeOperators, FlexibleContexts #-}

import GHC.Generics

data Bit = O | I deriving Show

class Serialize a where
  put :: a -> [Bit]

  default put :: (Generic a, GSerialize (Rep a)) => a -> [Bit]
  put a = gput (from a)

class GSerialize f where
  gput :: f a -> [Bit]

instance GSerialize U1 where
  gput U1 = []

instance (GSerialize a, GSerialize b) => GSerialize (a :*: b) where
  gput (a :*: b) = gput a ++ gput b

instance (GSerialize a, GSerialize b) => GSerialize (a :+: b) where
  gput (L1 x) = O : gput x
  gput (R1 x) = I : gput x

instance (GSerialize a) => GSerialize (M1 i c a) where
  gput (M1 x) = gput x

instance (Serialize a) => GSerialize (K1 i a) where
  gput (K1 x) = put x


--
-- Try it out...
--

data UserTree a = Node a (UserTree a) (UserTree a) | Leaf
  deriving Generic

instance (Serialize a) => Serialize (UserTree a)

instance Serialize Int


main = do
  print . put $ (Leaf :: UserTree Int)
  print . put $ (Node 7 Leaf Leaf :: UserTree Int)
  print . put $ (3 :: Int)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行它时,程序挂起:

?> main
[I]
[O     -- the program hangs here
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

kos*_*kus 5

你需要一个适当的实例Int.这是一种内置类型,你不能指望魔法.给出一个空实例Int将导致循环(这可能是一个糟糕的设计决定,但这就是目前的情况).

这是一个有效的(但没有效率):

import Data.Bits

boolToBit :: Bool -> Bit
boolToBit False = O
boolToBit True  = I

instance Serialize Int where
  put x = map (boolToBit . testBit x) [0 .. bitSize x - 1]
Run Code Online (Sandbox Code Playgroud)

如果你真的想要一个最小的例子,那就不要使用Int,使用Tree ()Tree Bool代替.