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

前端 未结 9 1066
清酒与你
清酒与你 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:43

    I think I might just be implementing find and redoing this. I think it's instructive, though, to see the innards of it. (Note how the solution depends on equality being transitive, though note also how the problem requires equality to be transitive to be coherent.)

    sameElement x:y:xs = if x /= y then Nothing else sameElement y:xs
    sameElement [x] = Just x
    allEqual [] = True
    allEqual xs = isJust $ sameElement xs
    

    I like how sameElement peeks at the first O(1) elements of the list, then either returns a result or recurses on some suffix of the list, in particular the tail. I don't have anything smart to say about that structure, I just like it :-)

    I think I do the same comparisons as this. If instead I had recursed with sameElement x:xs, I would compare the head of the input list to each element like in solution 0.

    Tangent: one could, if one wanted, report the two mismatching elements by replacing Nothing with Left (x, y) and Just x with Right x and isJust with either (const False) (const True).

提交回复
热议问题