【问题标题】:Recursively calling in a show function递归调用 show 函数
【发布时间】:2018-02-21 21:29:53
【问题描述】:

我正在接受一个数据类型 MyList,它有一个带有列表的尾部和一个头部。需要把它变成像haskell数据类型列表那样的反转字符串。

showList :: MyList a -> String
showlist (MyList h t) =  show(showlist(t) ++ show( h : [] ))

我正在为 showList [1,2,3] 摆脱这种疯狂

"\"[3][2]\"[1]"

【问题讨论】:

  • showList [1,2,3] 看起来甚至不是很好的类型(除非您使用的是-XOverloadedLists)。请始终在有关错误或意外输出的问题中添加minimal reproducible example,以便我们真正知道您在做什么。
  • show 在给定字符串时不等于 id

标签: haskell recursion show


【解决方案1】:

你基本上是调用show 两次:你不需要那个,一旦你得到一个字符串,这就是实现show 所需的全部内容。所以不要这样:

Prelude> show [1,2,3]
"[1,2,3]"

你得到:

Prelude> show $ show [1,2,3]
"\"[1,2,3]\""

那是因为为了打印",Haskell 需要用\ 转义那些。

让我们回到你的定义,你试图定义一个MyList a -> String类型的函数,所以基本上我们只需要在a类型的元素上调用show(我假设@987654330 @ 是a 类型,而这个类型是Show 的一个实例):

showList :: (Show a) => MyList a -> String
showList Nil = ""
showlist (MyList h t) =  showlist(t) ++ show(h : [])

我假设您的列表类型类似于:

data MyList a = Nil | MyList a (MyList a)

所以你会得到(我不知道你为什么在显示时反转列表):

Prelude> showList (MyList 1 (MyList 2 Nil))
"[2][1]"

如果你愿意,你可以使用,来稍微改进你的显示功能:

showList :: (Show a) => MyList a -> String
showList Nil = ""
showlist (MyList h t) =  show h ++ "," ++ showlist t

因此,你会得到:

Prelude> showList (MyList 1 (MyList 2 Nil))
"1,2,"

我留给你一个练习如何正确放置,[] 以同样打印:

"[1,2]"

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2016-08-20
    • 2013-08-29
    相关资源
    最近更新 更多