简体   繁体   中英

Not Function And Function Composition in F#

Is it possible it F# to have function composition between Operators.Not and some standard .NET function, for instance String.IsNullOrEmpty ?

In other words, why is the following lambda expression unacceptable:

(fun x -> not >> String.IsNullOrEmpty)

The >> function composition works the other way round - it passes the result of the function on the left to the function on the right - so your snippet is passing bool to IsNullOrEmpty , which is a type error. The following works:

(fun x -> String.IsNullOrEmpty >> not)

Or you can use reversed function composition (but I think >> is generally preferred in F#):

(fun x -> not << String.IsNullOrEmpty)

Aside, this snippet is creating a function of type 'a -> string -> bool , because it is ignoring the argument x . So I suppose you might actually want just:

(String.IsNullOrEmpty >> not)

If you want to use argument x , you can use pipe operator |> instead of function composition operators ( << or >> ).

fun x -> x |> String.IsNullOrEmpty |> not

But point-free style with function composition is generally preferred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM