itsadok
itsadok

Reputation: 29342

Is there a standard name for this function?

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

Answers (5)

Lee B
Lee B

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

Dario
Dario

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

Jon Seigel
Jon Seigel

Reputation: 12401

In .NET, the closest is Array.TrueForAll.

Maybe SameForAll would be more appropriate for this function?

Upvotes: 5

balpha
balpha

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

b.roth
b.roth

Reputation: 9542

identical_results sounds like a reasonable name to me.

Upvotes: 0

Related Questions