如何在谓词数组上映射单个值

how to map a single value over an array of predicates?

本文关键字:映射 单个值 数组 谓词      更新时间:2023-09-26

如果我有一个谓词函数数组,

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(...))

这是一件好事吗?我错过什么了吗?在函数式编程中还有其他的方法吗?

如果目的是检查是否所有或某些为真,则可以使用:

rules.every(function(rule){return rule.apply(candidate)})
rules.some(function(rule){return rule.apply(candidate)})

我不确定你在用哪一种Algol语言写作。看起来像JavaScript,所以我猜你需要使用return在你的例子,它的工作

与大多数"for-like"问题一样,您可以将map与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]

目前为止我发现的最优雅的解决方案是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