gpt4 book ai didi

haskell - 没有因使用 ‘show’ 而产生的实例(显示 a)

转载 作者:行者123 更新时间:2023-12-02 13:42:02 27 4
gpt4 key购买 nike

没有因使用“show”而产生(Show a)的实例在‘(++)’的第一个参数中,即‘show a’

data LTree a = Leaf a | Node (LTree a) (LTree a)
instance Show (LTree a) where
show (Leaf a) = "{" ++ show a ++ "}"
show (Node fe fd) = "<" ++ (show fe)++ "," ++(show fd)++ ">"
Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))

我应该得到:

<{1},<<{3},{4}>,<{8},{7}>>>

最佳答案

在你的行中:

    show (Leaf a) = "{" ++ <b>show a</b> ++ "}"

你调用show a,其中a是一个a类型的元素,但不是说的是该类型 aShow 的实例,因此您需要向 instance 声明添加约束:

instance <b>Show a =></b> Show (LTree a) where
show (Leaf a) = "{" ++ show a ++ "}"
show (Node fe fd) = "<" ++ (show fe)++ "," ++(show fd)++ ">"

所以这里我们说 LTree a 是 show given 的实例 aShow 的实例。对于您给定的样本数据,我们将获得:

Prelude> Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
<{1},<<{3},{4}>,<{8},{7}>>>

关于haskell - 没有因使用 ‘show’ 而产生的实例(显示 a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55918560/

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