是否有此功能的标准名称?
-
20-09-2019 - |
题
你会怎样命名一个函数,它接受一个列表和功能,并返回true,如果应用功能,所有的元素给出了同样的结果?
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
有没有这个东西不错普遍接受的名字吗?奖金,如果你能在一个不太笨重的方式实现。
解决方案
在.NET,最接近是Array.TrueForAll
。
也许SameForAll
会更适合于这样的功能?
其他提示
还没看听说过这个特殊的名字了(有点类似Forall
,但不完全)。 IdenticalResults
似乎好了,所以(乔恩·赛格尔提出SameForAll
,也相当不错)
此外:这是使用all
函数(下.NET TrueForall
)的方式人们可以在Haskell实现此
ident [] = True
ident (x:xs) = all (== x) xs
sameForAll f = ident . map f
和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:] ))
无法想到一个好名字,到目前为止,但是这一次不一样的:
def identical_results(l, func):
return len(set(map(func, l))) <= 1
identical_results听起来像一个合理名称给我。
我在上面所发布注释本,但格式弄乱,所以这里又是为了清晰:
def identical_results(l, func):
return reduce(lamdba x,y: x and y, map(func, l))
不隶属于 StackOverflow