Search code examples
listhaskellreduce

Comparing lists in Haskell


I have to define a function called zeros which takes input of two lists and returns a boolean which returns True if the number 0 appears the same amount of times in each list and false otherwise.

This is the last question in my homework and and I have managed to solve the question get it to work but I wondered if anybody can spot ways in which to reduce the amount of code. Any ideas are appreciated.
My code so far is as follows:

x :: Int
x = 0 
instances::[Int]->Int
instances [] = 0
instances (y:ys)
    | x==y = 1+(instances ys)
    | otherwise = instances ys



zeros :: [Int] -> [Int] -> Bool
zeros [] [] = False
zeros x y
       | ((instances x) == (instances y)) = True
       | otherwise = False

Solution

  • Without giving too much away, since this is homework, here are a few hints.

    Do you know about list comprehensions yet? They would be useful in this case. For example, you could combine them with an if expression to do something like this:

    *Main> let starS s = [if c == 's' then '*' else ' ' | c <- s]
    *Main> starS "schooners"
    "*       *"
    

    You can even use them to do filtering. For example:

    *Main> let findFives xs = [x | x <- xs, x == 5]
    *Main> findFives [3,7,5,6,3,4,5,7,5,5]
    [5,5,5,5]
    

    Neither of these is a complete answer, but it shouldn't be hard to see how to adapt these structures to your situation.

    You should also think about whether you actually need a guard here! For example, here's a function written with a guard in the same style as yours:

    lensMatch [] [] = True
    lensMatch xs ys
                 | ((length xs) == (length ys)) = True
                 | otherwise = False
    

    Here's a function that does the same thing!

    lensMatch' xs ys = length xs == length ys
    

    You can see that they are the same; testing the first:

    *Main> lensMatch [1..4] [1..4]
    True
    *Main> lensMatch [1..4] [1..5]
    False
    *Main> lensMatch [] [1..5]
    False
    *Main> lensMatch [] []
    True
    

    And testing the second:

    *Main> lensMatch' [1..4] [1..4]
    True
    *Main> lensMatch' [1..4] [1..5]
    False
    *Main> lensMatch' [] [1..5]
    False
    *Main> lensMatch' [] []
    True
    

    Finally, I agree very strongly with sblom's comment above; zeros [] [] should be True! Think about the following statement: "For each item x in set s, x > 0". If set s is empty, then the statement is true! It's true because there are no items in s at all. This seems to me like a similar situation.