Alex_P
Alex_P

Reputation: 2952

How can I use a predicate function parameter in the function body?

I am trying to solve the 'strain' exercise on exercism. The function is supposed to accept a predicate function as a parameter.

let keep pred xs =
  function body

When the code is:

[1;2;3;4] |> Seq.keep (fun x -> x % 2 = 0)

How can I use the predicate in the body?

Upvotes: 0

Views: 271

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243051

To answer the specific question - how to use the predicate in the body - let's say that we want to do something much simpler. We want to write a function that takes a predicate pred and a value v and it just returns "OK" if the predicate holds for the given value and "Nope" if it does not.

To do this, you would write:

let okIfHolds pred v = 
  if pred v then "OK" else "Nope"

To call the predicate, you just need to say pred v. This is the same F# function application syntax that you see when calling built-in functions like sqrt 2.0 or List.sum [1;2;3] - just specify the function and its argument(s).

Upvotes: 1

Related Questions