Is there a standard name for this function?

What would you call a function that takes a list and a function and returns True if the function is applied to all the elements and produces 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 common name for this thing? Bonus if you can implement a less smart way.

+2


source to share


5 answers


In .NET, the closest is Array.TrueForAll

.



Maybe it SameForAll

would be more appropriate for this feature?

+5


source


Haven't heard of a special name for this yet (somewhat similar to Forall

but not specific). IdenticalResults

Seems okay, so (John Seigel suggested SameForAll

, also pretty nice)

Optional: This is a way to implement this in Haskell with a function all

( TrueForall

in .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:] ))

      

+4


source


Don't know a good name yet, but it does the same:

def identical_results(l, func):
    return len(set(map(func, l))) <= 1

      

+1


source


same_results sounds like a sane name to me.

0


source


I posted this in the comment above, but the formatting got messed up, so here again for clarity:

def identical_results(l, func):
    return reduce(lamdba x,y: x and y, map(func, l))

      

0


source







All Articles