【发布时间】:2012-06-28 19:24:10
【问题描述】:
我正在尝试构建一个本质上是二叉树的数据类型,其: 每个节点的左分支是一个函数,可以作用于每个节点的右分支中的变量。我是 Haskell 的新手,我不确定我是否以正确的方式进行操作,但我目前的问题是我无法弄清楚如何将我的类型添加到 Show 类型类中。这是我的尝试:
{-# LANGUAGE ExistentialQuantification #-}
-- file: TS.hs
data TypeSentence a = forall b. Apply (TypeSentence (b->a)) (TypeSentence b)
| Expr a
instance (Show a) => (Show (TypeSentence a)) where
show (Expr x) = show x
show (Apply x y) = (show x) ++ " " ++ (show y)
instance (Show (TypeSentence b->a)) where
show (Expr x) = show "hello"
x = Expr 1
f = Expr (+1)
s = Apply f x
但是,当我将其加载到 ghci 中时,出现以下错误:
TS.hs:9:24:
Could not deduce (Show (b -> a)) from the context ()
arising from a use of `show' at TS.hs:9:24-29
Possible fix:
add (Show (b -> a)) to the context of the constructor `Apply'
or add an instance declaration for (Show (b -> a))
In the first argument of `(++)', namely `(show x)'
In the expression: (show x) ++ " " ++ (show y)
In the definition of `show':
show (Apply x y) = (show x) ++ " " ++ (show y)
Failed, modules loaded: none.
任何想法如何添加 Show (b->a) 声明?
谢谢。
【问题讨论】:
-
没有办法为通用函数创建
Show实例,你认为它应该如何工作?我也不认为你真的想要这个。 — 无论如何,首先你的这棵树并没有按照你说的去做:b->a可以作用于b,但在另一个分支中有一个a。我相信你想把b放在那里? -
是的,你是对的。解决了这个问题。我想在一个通用函数上定义 Show ,这样如果函数有一个 Show 实例,它就会显示它,如果没有,它会在定义中递归,直到它在具有 show 实例的原始函数处触底。
-
你想写
instance Show (TypeSentence (b->a))吗?注意括号 -
import Text.Show.Functions为您提供Show函数实例 (show _ = "<function>")。 -
@Eyal:这是不可能的,因为它违反了参照透明性。有一些
f :: (a -> b) -> String这样f (+ 1) = "(+ 1)"和f $ \x -> x + 1 = "\\x -> x + 1"可以让我们区分两个相等的函数;并且函数相等是不可判定的,这使我们无法找到一些“规范形式”来显示。
标签: haskell