簡體   English   中英

顯示多態類型的功能

[英]Show function for polymorphic type

我正在嘗試為多態Tree類型定義Show函數。 有人可以幫我嗎?

import Char

data Tree t =
    NilT |
    Node t (Tree t) (Tree t)

class Mar t where
    maior :: t -> String

instance Mar Tree where
    maior (NilT) = "a" 
    maior (Node t a b) = "b"

instance Show Tree where
    show = maior

非常感謝!


解決方案(由ivanm提供):

import Char

data Tree t =
    NilT |
    Node t (Tree t) (Tree t)

class Mar t where
    maior :: t -> String

instance Mar (Tree t) where
    maior (NilT) = "a" 
    maior (Node t a b) = "b"

instance Show (Tree t) where
    show = maior

您沒有使用deriving Show任何特殊原因嗎? ShowRead類旨在提供真正的基本序列化/反序列化,(通常)生成有效的Haskell代碼。

但是對於您想要的,我認為錯誤可以追溯到您的Mar班。 按照定義,該實例的種類為* -> * (例如MaybeMaybe Int相對)。 您可能的意思是讓instance Mar (Tree t) where ...位於instance Mar (Tree t) where ...

data Tree t =
    NilT |
    Node t (Tree t) (Tree t)
    deriving Show

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM