简体   繁体   中英

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

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

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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