【发布时间】:2013-03-14 02:58:54
【问题描述】:
我在 Haskell 中有一个冗长且略显古怪的函数。
(#==#) :: String -> String -> Bool
str1 #==# str2 = (sum[ 1 | index <- [0..(max (length str1) (length str2))], (str1!!index == str2!!index || str1!!index == '$')] == (max (length str1) (length str2)))
简而言之,这个函数检查两个字符串是否相同,如果它们有一个或多个'$'则认为它们相同 [长版:为了节省您解读它的时间,它需要两个字符串,列表理解中的一个索引变量从 0 到最长字符串的长度。然后将当前索引处的每个字符串的元素与彼此或美元符号进行比较。两者都可以。如果它们是其中之一,则将 1 添加到新列表中,如果此新列表的总和等于长度,则该单词是匹配的。
当我尝试运行它时,我得到了一个特殊的错误:
*Practice> let totals = (sum[ 1 | index <- [1..(max (length str1) (length str2))], (str1!!index == str2!!index || str1!!index == '$')] == (max (length str1) (length str2)))
*Practice> totals
*** Exception: Prelude.(!!): index too large
我一直在研究,但没有找到任何解决此特定错误的方法。如果有人对此有所了解,我将不胜感激。
(顺便说一句,错误中的“索引”与我在函数中使用的索引不一样)
【问题讨论】:
-
i去最长字符串的长度是吗?那么当您尝试在大索引处取消引用较短的索引时会发生什么? -
另外,最后一个有效索引是
length list - 1。 -
@Imray,用两个不同长度的字符串试试...
-
!!是将索引错误从其他语言移植到 Haskell 的有效方法。 (该代码看起来很像一个转换为列表理解的 for 循环。)
标签: function haskell runtime-error list-comprehension