efficiently checking that all the elements of a (big) list are the same

前端 未结 9 1085
清酒与你
清酒与你 2020-12-14 16:01

Problem

Let us suppose that we have a list xs (possibly a very big one), and we want to check that all its elements are the same.

I came up wi

9条回答
  •  长情又很酷
    2020-12-14 16:44

    This implementation is superior.

    allSame [ ] = True
    allSame (h:t) = aux h t
    
    aux x1 [ ]                 = True
    aux x1 (x2:xs) | x1==x2    = aux x2 xs 
                   | otherwise = False
    

    Given the transitivity of the (==) operator, assuming the instance of Eq is well implemented if you wish to assure the equality of a chain of expressions, eg a = b = c = d, you will only need to assure that a=b, b=c, c=d, and that d=a, Instead of the provided techniques above, eg a=b, a=c, a=d, b=c , b=d, c=d.

    The solution I proposed grows linearly with the number of elements you wish to test were's the latter is quadratic even if you introduce constant factors in hopes of improving its efficiency.

    It's also superior to the solution using group since you don't have to use length in the end.

    You can also write it nicely in pointwise fashion but I won't bore you with such trivial details.

提交回复
热议问题