Home > front end >  How to check if length of a list is not equal to length of a list within a list in haskell
How to check if length of a list is not equal to length of a list within a list in haskell

Time:10-13

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!

CodePudding user response:

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.

CodePudding user response:

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) -> f a -> Bool:

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