gpt4 book ai didi

haskell - Haskell 中的 showS 技巧是什么?

转载 作者:行者123 更新时间:2023-12-03 04:39:20 25 4
gpt4 key购买 nike

我已经看到了对构建字符串的 showS 技巧的引用(例如,在 this discussion 中),但我从未见过对其的良好描述。

表演技巧是什么?

最佳答案

在标准库中,ShowS定义为:

type ShowS = String -> String

这是一个difference list 。诀窍在于,字符串 xs 通过将其添加到任何其他列表的函数来表示为 ShowS:(xs++)。这允许高效的串联,避免嵌套左关联串联的问题(即 ((as++ bs)++ cs)++ ds)。例如:

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类型类的实现,以允许高效显示大型、深度嵌套的结构;除了 show 之外,您还可以实现 showsPrec,其类型为:

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

这允许处理运算符优先级,并返回一个 ShowS 值。标准实例实现此方法而不是 show 以提高效率;然后根据它定义 show a,如 showsPrec 0 a ""。 (此默认定义位于 Show 类型类本身中,因此您只需为完整实例实现 showsPrec 即可。)

关于haskell - Haskell 中的 showS 技巧是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9197913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com