gpt4 book ai didi

Haskell Labeled AST : No instance for (Show1 (Label a)), 如何构建实例?

转载 作者:行者123 更新时间:2023-12-01 03:20:06 27 4
gpt4 key购买 nike

我想要一个带注释的 AST,所以我定义了那些递归数据结构
使用 Fix :

data Term a 
= Abstraction Name a
| Application a a
| Variable Name
deriving (Read,Show,Eq,Functor,Foldable,Traversable)

data Label a b
= Label a (Term b)
deriving (Read,Show,Eq,Functor,Foldable,Traversable)

newtype Labeled a
= Labeled (Fix (Label a))
deriving (Show)

我希望能够 show Labeled a ,但编译器不高兴:

No instance for (Show1 (Label a))  
arising from the first field of `Labeled' (type `Fix (Label a)')


什么是类(class) Show1以及如何定义适当的实例以显示 Labeled a ?

最佳答案

Show1 是您可能称之为“高阶可展示”的类:类型构造函数,只要它们的参数是可展示的,就可以展示。出于快速和宽松推理的目的,您可以考虑 Show1大致像这样声明(另见 showsPrec1 ):

class Show1 f where
show1 :: Show a => f a -> String

这是另一种不准确但有用的思考方式 Show1 .我正在使用 the constraints library"entailment" operator声明 f a应该是 Show 的一个实例每当 a是。这个模型有点简单,但可能不太实用。
class Show1 f where
show1 :: Show a :- Show (f a)

不管怎样, Fix :: (* -> *) -> *如果它的参数是一个高阶可展示的,则它是可展示的。来自 the source code :
instance Show1 f => Show (Fix f) where
showsPrec d (Fix a) =
showParen (d >= 11)
$ showString "Fix "
. showsPrec1 11 a
recursion-schemes的作者本来可以用 StandaloneDeriving写他们的 Show实例...
deriving instance Show (f (Fix f)) => Show (Fix f)

...但此上下文需要 UndecidableInstances .

写一个 Show1 的最简单方法给定仿函数的实例是使用 the deriving-compat libraryTemplate Haskell helper .
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# LANGUAGE TemplateHaskell #-}

import Text.Show.Deriving
import Data.Functor.Foldable


type Name = String
data Term a
= Abstraction Name a
| Application a a
| Variable Name
deriving (Read, Show, Eq, Functor, Foldable, Traversable)

deriveShow1 ''Term

data Label a b = Label a (Term b)
deriving (Read, Show, Eq, Functor, Foldable, Traversable)

deriveShow1 ''Label

newtype Labeled a = Labeled (Fix (Label a)) deriving (Show)

这将生成以下实例,
instance Show1 Term
instance Show a => Show1 (Label a)

给你你想要的 Labeled的派生实例:
instance Show a => Show (Labeled a)

(PS。您是否考虑过使用像 bound 这样的库来管理您的术语语言中的名称和活页夹?)

关于Haskell Labeled AST : No instance for (Show1 (Label a)), 如何构建实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117489/

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