【问题标题】:Haskell: No instance for (Show Exp) arising from a use of 'print'Haskell:没有因使用“打印”而产生的(Show Exp)实例
【发布时间】:2020-10-20 01:19:44
【问题描述】:

我收到以下错误:

没有因使用“打印”而产生 (Show Exp) 的实例

在表达式中:打印 ti1

在“it”的等式中:it = print ti1


当我

ghci>ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
ghci>print ti1

我的整个代码是:

data Exp = Lit Int
    | Neg Exp
    | Add Exp Exp
    
view:: Exp -> String
view (Lit n) = show n
view (Neg e) = "(-" ++ view e ++ ")"
view (Add e1 e2) = "(" ++ view e1 ++ " + " ++ view e2 ++ ")"

如何打印这个字符串?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    如何打印这个字符串?

    你应该先调用view函数,所以:

    ghci> ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
    ghci> print (view ti1)
    "(8 + (-(1 + 2)))"

    但是调用view就足够了,因为它会自动在ghci中打印结果:

    ghci> ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
    ghci> view ti1
    "(8 + (-(1 + 2)))"

    您还可以将view 函数设为show 函数Exp

    instance Show Exp where
        show = view

    那么只需查询t1print t1 就足够了:

    ghci> print ti1
    (8 + (-(1 + 2)))
    ghci> ti1
    (8 + (-(1 + 2)))
    

    【讨论】:

    • 感谢您对一个非常新的haskell用户的回答:)
    【解决方案2】:

    您需要让您的数据声明派生Show 实例。因此,将您的数据声明更改为:

    data Exp = Lit Int
        | Neg Exp
        | Add Exp Exp deriving (Show)
    

    【讨论】:

    • 非常感谢您的回答,但我会选择其他答案,因为它不需要更改我的代码
    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多