Alex Rivera | Logout

What is a predicate?

Asked 2009-08-27T22:09:59.537
85

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 very much appreciate an explanation on the subject.

Edit
Report

2 Answers

50

In programming, a predicate is a function which returns either true or false 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:

function lessThanTen(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.

answered 2009-08-27T22:12:20.390
2

A function that returns a boolean. Predicates are used a lot in functional and OO programming to select subsets of values from data structures, especially lists and other collections. You'll find plenty of examples in the standard libraries for Haskell and Smalltalk.

answered 2009-08-27T22:35:37.007

Your Answer