如何定义泛型类型是“可打印的” [英] How to define that a generic type is "printable"

查看:100
本文介绍了如何定义泛型类型是“可打印的”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须预先打印多态树类型。我遇到了一些麻烦,因为我的泛型类型t可能不是可打印的。有谁知道如何出售这个?无论如何告诉haskell只接受可打印类型? (在控制台上打印,所以它应该像显示)



以下是代码:

  import char 

数据树t =
NilT |
Node t(Tree t)(Tree t)

实例Show(Tree t)其中
show = func

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

谢谢!

解决方案

您可以要求 t Show 的一个实例,无论是在实例声明还是以下类型声明中:

  instance显示t => Show(Tree t)
func :: Show t =>树t - >字符串

要使用它,您的预订遍历需要调用 show

  func(节点标签)= show t ++ func a ++ func b 


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")

Here is the code:

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)

Thanks!

解决方案

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

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

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

这篇关于如何定义泛型类型是“可打印的”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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