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
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)
.