简体   繁体   English

为什么要采取全面的功能

[英]Why is take a total function

take (-1) [] is [] . take (-1) [][]

What are the reasons to prefer this over a partial function, that is, an error? 在部分功能上更喜欢这个的原因是什么,即错误?

Are there use cases where this property is exploited? 是否存在利用此属性的用例?

take and drop are similar to the left-substring and right-substring functions, and it's proven in practice to be convenient for those not raise an error for negative or invalid lengths. takedrop类似于left-substring和right-substring函数,并且在实践中证明它对于那些没有为负数或无效长度引发错误的人来说很方便。

For example - a padding function: 例如 - 填充功能:

pad :: Int -> String -> String
pad n str = (repeat (n - length str) ' ') ++ str

and here is a variant to pad with another string: 这是一个用另一个字符串填充的变体:

padWith :: String -> Int -> String -> String
padWith field n str = (take (n - length str) field) ++ str

Splitting a list in chunks of (at most) n pieces requires take to be total: 在大块(最多)拆分列表n片需要take以总:

chunks n [] = []
chunks n xs = take n xs : chunks n (drop n xs)

Also, the current definition ensures 此外,当前的定义确保

take n xs ++ drop n xs == xs

for any n and xs . 对于任何nxs

Arguably, we should have both takeAtMost and takeAtLeast , the latter being the partial variant (or instead returning Maybe ). 可以说,我们应该同时具有takeAtMosttakeAtLeast ,后者是部分变体(或者返回Maybe )。

A similar concern arises from zip , which is total as well, even when applied to lists of unequal length. zip也出现了类似的问题,即使应用于长度不等的列表也是如此。 Still, that is frequently exploited in the idiom zip [1..] xs which pairs every element of the list with its own index. 尽管如此,这经常在成语zip [1..] xs被利用,它将列表中的每个元素与其自己的索引配对。

Keep however in mind that I am not arguing that a total function is always the preferred one. 但请记住,我并不是说总功能始终是首选功能。 On many, many programming tasks obtaining a bug-revealing exception is a bliss compared with obtaining the wrong result and having no idea about where the bug is. 在许多情况下,获取错误揭示异常的许多编程任务与获取错误结果并且不知道错误位置相比是一种幸福。 Or even worse, getting a wrong yet plausible result, and not even discovering there is a bug. 或者更糟糕的是,得到一个错误但看似合理的结果,甚至没有发现有一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM