Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 哈斯克尔的表演技巧是什么?_Haskell - Fatal编程技术网

Haskell 哈斯克尔的表演技巧是什么?

Haskell 哈斯克尔的表演技巧是什么?,haskell,Haskell,我见过对showS构建字符串技巧的引用(例如,in),但我从未见过对它的良好描述 什么是showS技巧?在标准库中,showS定义为: type ShowS = String -> String 这是一个很好的例子。 诀窍在于,字符串xs通过将其添加到任何其他列表的函数表示为显示:(xs++)。这允许有效的连接,避免了嵌套左关联连接(即((as++bs)+cs)+ds)的问题。例如: hello = ("hello" ++) world = ("world" ++) -- We can

我见过对
showS
构建字符串技巧的引用(例如,in),但我从未见过对它的良好描述


什么是showS技巧?

在标准库中,
showS
定义为:

type ShowS = String -> String
这是一个很好的例子。 诀窍在于,字符串
xs
通过将其添加到任何其他列表的函数表示为
显示
(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 ""
它被称为
Show
,因为它用于标准
Show
typeclass的实现中,以允许高效地
Show
ing大型嵌套结构;除了
show
,您还可以实现
showsPrec
,其类型为:

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

这允许处理运算符优先级,并返回
显示的值。为了提高效率,标准实例实现了这一点,而不是
show
<代码>显示a
然后根据它定义为
showsPrec 0 a”“
。(此默认定义在
Show
typeclass本身中,因此您可以只为完整实例实现
showsPrec

showS
使用差异列表方法有效地连接显示值的各个组件。该函数获取要显示的值和要附加到结果的字符串。追加的字符串一直向下传递到最右边的子值,直到它到达一个叶,在那里它实际上被追加


这里有一个差异列表的描述(包括
showS

看看这里的答案,一个简明的总结可能是:“
showS
诀窍”是将一个低效(
O(n^2)
)左关联字符串串联转换成一个高效(
O(n)
)通过将字符串转换为(前置)连续体,然后组合连续体,右关联字符串连接。链接:ShowS位于基本包的Text.Show模块中