What is a predicate?

前端 未结 12 1751
无人及你
无人及你 2020-12-04 12:16

Being a hobbyist coder, I\'m lacking some fundamental knowledge. For the last couple days I\'ve been reading some stuff and the word \"predicate\" keeps reappearing. I\'d ve

12条回答
  •  臣服心动
    2020-12-04 12:46

    A statement which is either true or false. In programming it is typically a function which return a boolean for some input.

    Most commonly (I guess) used in the context of higher-order function. E.g. filter is a function in many languages which takes a predicate and a list as arguments, and returns the items in the list for which the predicate is true.

    Example in javascript:

    lessThanTen = function(x) { return x < 10; }
    [1,7,15,22].filter(lessThanTen) --> [1,7]
    

    the function lessThanTen is the predicate here, which is applied to each item in the list. Of course a boolean expression could be used as predicate in place of a function, e.g filter(true) will return the full list, filter(false) an empty list.

提交回复
热议问题