【问题标题】:Haskell: deriving Show for Fix typesHaskell:为 Fix 类型派生 Show
【发布时间】:2017-08-13 14:48:28
【问题描述】:

我正在尝试使用recursion-schemes 实现递归数据类型。我希望能够打印出来。

import Data.Functor.Foldable

data T1F a = Foo deriving Show
type T1 = Fix T1F
data T2 = Bar T1 deriving Show -- error here

错误信息:

No instance for (Data.Functor.Classes.Show1 T1F)
  arising from the first field of ‘Bar’ (type ‘T1’)
Possible fix:
  use a standalone 'deriving instance' declaration,
    so you can specify the instance context yourself
When deriving the instance for (Show T2)

如何让T1 派生Show?

【问题讨论】:

  • 错误信息告诉你问题所在。对于T1F,您需要一个Show1 的实例。手动编写Show1 的实例可能非常乏味。幸运的是deriving-compat 包has got your back。
  • @BenjaminHodgson 有手动派生的例子吗?
  • @CMCDragonkai 最简单的方法是为您的数据类型派生Show,通过-ddump-deriv 编译查看生成的代码,然后粘贴并调整它。不过,这并不是一项有趣的任务 - 在 pkg 中使用 TH 助手要容易得多!
  • 我明白了。我仍然不明白为什么需要这样做。

标签: haskell typeclass deriving fixpoint-combinators


【解决方案1】:

使用包deriving-compat:

{-# LANGUAGE TemplateHaskell #-}
import Data.Functor.Foldable
import Text.Show.Deriving

data T1F a = Foo deriving Show
$(deriveShow1 ''T1F)
type T1 = Fix T1F
data T2 = Bar T1 deriving Show

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多