首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单的GHC.Generics示例

简单的GHC.Generics示例
EN

Stack Overflow用户
提问于 2013-07-15 21:57:01
回答 1查看 364关注 0票数 4

通过遵循wiki article,我正在尝试创建如何使用GHC.Generics的最小工作示例。这就是我所拥有的:

代码语言:javascript
复制
{-# 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)

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

代码语言:javascript
复制
λ> main
[I]
[O     -- the program hangs here

我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-16 00:37:21

您需要一个合适的Int实例。这是一个内置类型,你不能期望在这里有魔力。为Int提供一个空实例将导致循环(这可能是一个糟糕的设计决策,但它目前就是这样的)。

下面是一个有效的方法(但绝不是高效的):

代码语言:javascript
复制
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]

如果你真的想要一个最小的例子,那么不要使用Int,而应该使用Tree ()Tree Bool

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17656018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档