Haskell中的showS技巧是什么? [英] What is the showS trick in Haskell?

查看:113
本文介绍了Haskell中的showS技巧是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到引用 showS 技巧来构建字符串(例如,在 this discussion ),但我从来没有见过这么好的描述。

I have seen references to the showS trick to build strings (e.g., in this discussion), but I have never seen a good description of it.

什么是the showS trick?

What is the showS trick?

推荐答案

在标准库中,定义了 ShowS as:

In the standard library, ShowS is defined as:

type ShowS = String -> String

这是 差异列表
诀窍是一个字符串 xs 被函数表示为 ShowS 其他列表:(xs ++)。这允许有效的级联,避免了嵌套左关联级联(即((as ++ bs)++ cs)++ ds )的问题。例如:

This is a difference list. The trick is that a string xs is represented as a ShowS by the function that prepends it to any other list: (xs ++). This allows efficient concatenation, avoiding the problems of nested left-associative concatenation (i.e. ((as ++ bs) ++ cs) ++ ds). For example:

hello = ("hello" ++)
world = ("world" ++)

-- We can "concatenate" ShowS values simply by composing them:
helloworld = hello . world

-- and turn them into Strings by passing them an empty list:
helloworld' = helloworld ""

它被称为 ShowS ,因为它用于执行标准 Show > typeclass允许高效的 show 大型深度嵌套结构;以及 show ,您可以实现 showsPrec ,其类型为:

It's called ShowS because it's used in the implementation of the standard Show typeclass to allow efficient showing of large, deeply-nested structures; as well as show, you can implement showsPrec, which has the type:

showsPrec :: (Show a) => Int -> a -> ShowS

这允许处理运算符优先级,并返回一个 ShowS 值。标准实例实现这个而不是 show 来提高效率; show a 然后用它来定义,如 showsPrec 0 a。 (这个默认定义在 Show typeclass本身中,所以你可以为一个完整的实例实现 showsPrec

This allows handling of operator precedence, and returns a ShowS value. The standard instances implement this instead of show for efficiency; show a is then defined in terms of it, as showsPrec 0 a "". (This default definition is in the Show typeclass itself, so you can just implement showsPrec for a complete instance.)

这篇关于Haskell中的showS技巧是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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