如果我有一个谓词函数数组,
rules = [is_cute, has_good_job, is_not_crazy, is_tall_enough ]
将所有这些应用于同一个变量的最佳做法是什么?
我提出的是
candidate= "joe pesci"
_.map(rules, function(rule){return rule.apply(candidate)} )
显然,目标是将其用于类似
的内容it_is_true_love = _.all( rules.map(...))
这是一件好事吗?我错过了什么吗?在函数式编程中有什么其他方法可以做到这一点?
答案 0 :(得分:2)
如果目的是检查每个或某些是否属实,那么您可以使用:
rules.every(function(rule){return rule.apply(candidate)})
rules.some(function(rule){return rule.apply(candidate)})
我不确定你写的是哪种Algol语言。看起来像JavaScript,所以我猜你需要在你的例子中使用return
才能使用它。
答案 1 :(得分:1)
与大多数“for-like”问题一样,您可以使用map with lambda。
用Elixir语言编写的示例(请注意,此处的点是函数应用程序):
bigger_than = fn x,y -> x>y end
bigger_1 = fn x -> bigger_than.(x,1) end
bigger_5 = fn x -> bigger_than.(x,5) end
bigger_10 = fn x -> bigger_than.(x,10) end
# list of predicates
l = [bigger_1,bigger_5,bigger_10]
# results in an interactive session:
iex(7)> x=1
iex(8)> Enum.map(l,fn f -> f.(x) end)
[false, false, false]
iex(9)> Enum.map(l,fn f -> f.(1) end)
[false, false, false]
iex(10)> Enum.map(l,fn f -> f.(3) end)
[true, false, false]
iex(11)> Enum.map(l,fn f -> f.(7) end)
[true, true, false]
iex(12)> Enum.map(l,fn f -> f.(11) end)
[true, true, true]
答案 2 :(得分:0)
到目前为止,我发现的最优雅的解决方案是Rambda.js:
var rules = [is_cute, has_good_job, is_not_crazy, is_tall_enough ]
var is_true_love = R.allPass(rules);
示例用法:
// is_true_love('joe pesci') => false //not that cute anymore
// is_true_love('elon musk') => false //he's probably crazy!
// is_true_love( the_real_one ) => true