程序上的Haskell错误

程序上的Haskell错误,haskell,Haskell,只是在解决一个问题,它总是给我这个错误: 例外:Prelude.tail:空列表 以下是我目前的代码: lxP :: Eq a => [[a]] -> [a] lxP [] = [] lxP xss | any null xss = [] | otherwise = loop xss [] where loop ::Eq b => [[b]] -> [b] -> [b] loop xss acc =

只是在解决一个问题,它总是给我这个错误: 例外:Prelude.tail:空列表

以下是我目前的代码:

lxP :: Eq a => [[a]] -> [a]
lxP []   = []
lxP xss 
   | any null xss = []
   | otherwise    = loop xss []
   where loop ::Eq b => [[b]] -> [b] -> [b] 
         loop xss acc =        
               let xs = concatMap (take 1) xss
               in if any (\x -> x /= head xs) (tail xs)       
                     then reverse acc
                     else loop (map tail xss) (head xs : acc)
你知道我的缩进是问题还是代码有问题吗?
附:我怎样才能提高效率?

我不太清楚您的功能应该做什么。这对我来说是不合理的。以下是它在我看来的样子:

您获取一些列表列表(假设它现在是一个矩阵,因为我将要讨论列),并且希望返回第一行的最长前缀,这样每个元素都在一个常量列中

因此,让我们试着用更惯用的方式来写这篇文章

现在我们想在列中寻找恒常性,但是如果行的长度不同,我们该怎么办?我将决定忽略它们,想象一下将所有元素向上推,这样就没有间隙。让我们将行转换为列:

transpose :: [[a]] -> [[a]]
transpose xss = t xss where
  n = maximum (map length xss)
  t [] = repeat n []
  t (xs:xss) = join xs (t xss)
  join [] yss = yss
  join (x:xs) (ys:yss) = (x:ys) : join xs yss
现在我们可以编写函数了

myWeirdFunction xss
  | any null xss = []
  | otherwise = map head $ takeWhile constant $ transpose xss where
    constant (x:xs) = c x xs
    c x (y:ys) | y == x = c x ys
               | True   = False
    c x [] = True

错误消息非常简单,您使用空列表调用tail。仔细检查一下你的算法,想想是什么导致了这种情况。我试过了,但我没有发现问题,你能告诉我我需要更改什么吗?我猜在某个时候,
xs
变为空,触发了错误。这就是为什么应该避免头、尾。当然,您确实会在开始时检查
任何空xss
,以防止出现这种情况,但此属性不一定在每次递归调用时都保留。(顺便问一下,您的代码是否尝试执行类似于
concat.transpose
)顺便说一句,您可以尝试使用GHCi调试器查看发生了什么。尝试
映射头。takeWhile((==1.length)。地图组。转置