For some function f , which is of type:
f: 'a -> bool
you want to be able to generate another function to wrap it in order to negate the result. Let's look at the type of this new function, call it negated (I do not use not , since this is the name of the built-in):
negated: ('a -> bool) -> 'a -> bool
Why is this type? Why not 'a -> bool ? Remember well, we want this new function to use an existing function and return a new function with the same type that does something else. To make this clearer, you can think like this: ('a -> bool) -> ('a -> bool) , which is equivalent.
So now, given these limitations, how can we write a negated function?
let negated f = ??
Well, first you need to consider that you need to return a function to this function:
let negated f = (fun x -> ??)
What's next? Well, we know that the new function we create must call our wrapped function an argument and negate it. Let this be done, call the function with the argument: fx and cancel it: not (fx) . This gives us the final definition of the function:
let negated f = (fun x -> not (fx))
Look at him in action:
# let fx = x < 5;; val f : int -> bool = <fun> # f 2;; - : bool = true # f 8;; - : bool = false # let negated f = (fun x -> not (fx));; val negated : ('a -> bool) -> 'a -> bool = <fun> # let g = negated(f);; val g : int -> bool = <fun> # g 2;; - : bool = false # g 8;; - : bool = true
Jeff mercado
source share