Reputation: 29342
What would you name a function that takes a list and a function, and returns True if applying the function to all elements gives the same result?
def identical_results(l, func):
if len(l) <= 1: return True
result = func(l[0])
for el in l[1:]:
if func(el) != result:
return False
return True
Is there a nice generally accepted name for this thing? Bonus if you can implement in a less clunky fashion.
Upvotes: 2
Views: 328
Reputation: 2157
I posted this in a comment above, but the formatting got messed up, so here it is again for clarity:
def identical_results(l, func):
return reduce(lamdba x,y: x and y, map(func, l))
Upvotes: 0
Reputation: 49218
Havn't heard about a special name for this yet (somewhat similar to Forall
, but not exactly). IdenticalResults
seems okay so (Jon Seigel proposed SameForAll
, also quite nice)
Additionally: That's the way one could implement this in Haskell using the all
function (TrueForall
under .NET)
ident [] = True
ident (x:xs) = all (== x) xs
sameForAll f = ident . map f
And Python:
def idents(f, list):
if len(list) <= 1:
return True
else:
let fx0 = f(list[0])
return all(( f(x) == fx0 for x in list[1:] ))
Upvotes: 4
Reputation: 12401
In .NET, the closest is Array.TrueForAll
.
Maybe SameForAll
would be more appropriate for this function?
Upvotes: 5
Reputation: 50908
Can't think of a good name so far, but this one does the same:
def identical_results(l, func):
return len(set(map(func, l))) <= 1
Upvotes: 1