如何定义通用类型为& quot;可打印&". [英] How to define that a generic type is "printable"

查看:55
本文介绍了如何定义通用类型为& quot;可打印&".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须预先订购多态的Tree类型.我遇到了一些麻烦,因为我的通用类型t可能不是可打印的".有谁知道怎么卖这个?无论如何,有没有告诉Haskell只接受可打印"类型?(在控制台上打印,所以应该类似​​显示")

I have to print on pre-order a polymorphic Tree type. I'm having some trouble because my generic type t may not be "printable". Does anyone knows how to sold this? Is there anyway to tell haskell to only accept "printable" types? (print on the console, soo it should be something like "Show")

这是代码:

import Char

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

instance Show (Tree t) where
    show = func

func :: (Tree t) -> String
func (NilT) = "" 
func (Node t a b) = t ++ (func a) ++ (func b)

谢谢!

推荐答案

在实例声明和以下示例中,您都可以要求 t Show 的实例类型声明:

Your can demand that t be an instance of Show, both in the instance declaration and the following type declaration:

instance Show t => Show (Tree t)
func :: Show t => Tree t -> String

要使用此功能,您的预订遍历将需要调用 show .

To use this, your pre-order traversal will need to call show.

func (Node t a b) = show t ++ func a ++ func b

这篇关于如何定义通用类型为& quot;可打印&".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆