gpt4 book ai didi

generics - 简单的 GHC.Generics 示例

转载 作者:行者123 更新时间:2023-12-03 07:53:57 28 4
gpt4 key购买 nike

我正在尝试通过遵循 wiki article 创建如何使用 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)

但是,当我尝试运行它时,程序挂起:
λ> main
[I]
[O -- the program hangs here

我究竟做错了什么?

最佳答案

您需要一个合适的实例 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]

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

关于generics - 简单的 GHC.Generics 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17656018/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com