Is there a standard name for this function?
-
20-09-2019 - |
Question
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.
Solution
In .NET, the closest is Array.TrueForAll
.
Maybe SameForAll
would be more appropriate for this function?
OTHER TIPS
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:] ))
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
identical_results sounds like a reasonable name to me.
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))