简体   繁体   English

如何在haskell中检查列表的长度是否不等于列表中的列表的长度

[英]How to check if length of a list is not equal to length of a list within a list in haskell

Hi Guys I am trying to check whether the length of a list is not equal to length of a list within a list using haskells length function and pattern matching嗨,伙计们,我正在尝试使用 haskells 长度函数和模式匹配来检查列表的长度是否不等于列表中列表的长度

This is the function i have and its type:这是我拥有的功能及其类型:

func :: [String] -> [[String]] -> String 

where the return string is either "Error different lengths found" OR "Lengths are the same"其中返回字符串是“发现错误长度不同”或“长度相同”

This is what i would input and the expected output see below:这是我要输入的内容,预期输出如下:

["Planet", "City"] [["Jupiter", "Earth"], ["Berlin", "Madrid", "Krakow"] ] [“行星”、“城市”] [[“木星”、“地球”]、[“柏林”、“马德里”、“克拉科夫”]]

Output should be "Error different lengths found" due to ["Berlin", "Madrid", "Krakow"] being of size 3 where as ["Planet", "City"] is of size 2由于["Berlin", "Madrid", "Krakow"]的大小为 3,而["Planet", "City"]的大小为 2 ["Planet", "City"]输出应为"Error different lengths found"

bit unsure how to do this and would appreciate any help!有点不确定如何做到这一点,并希望得到任何帮助!

Something like this would check it in linear time.像这样的事情会在线性时间内检查它。

compLength :: [String] -> [[String]] -> String
compLength s = go (length s)
  
  where go _ []   = "All Good! Hurray!"
        go n (y:ys)
          | n /= length y = "Error different lengths found" ++ " [" ++ unwords y ++ "]"
          | otherwise      = go n ys

I think this gives you the base and the necessary information to tailor the output to your exact needs.我认为这为您提供了根据您的确切需求定制输出的基础和必要信息。

You can write a helper function to check if two lists have the same length, so you can implement a function:您可以编写一个辅助函数来检查两个列表是否具有相同的长度,因此您可以实现一个函数:

sameLength :: [a] -> [a] -> Bool
sameLength … = …

When you have implemented such function, it is only a matter to check if all sublists have the same length.当您实现了这样的功能时,只需检查所有子列表是否具有相同的长度。 We can do this with all :: Foldable f => (a -> Bool) -> fa -> Bool :我们可以用all :: Foldable f => (a -> Bool) -> fa -> Bool来做到这一点:

func :: [a] -> [[a]] -> Bool
func xs yss
    | all (sameLength xs) yss = "Lengths are the same"
    | otherwise = "Error different lengths found"

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

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