I'm looking into chessie library. I often times see Trial.lift and Trial.bind functions being used. If I understand it right, Trial.lift takes in a function parameter and executes and returns that function if the piped in result is a success. If that is true, doesn't Trial.bind do the same thing?
These functions are subtly different: under bind
, the function f
must return a Result<_>
, while lift
takes any ordinary function.
Think of it like this: bind
"attaches" another maybe-failed computation to a previous chain of computations:
let isOdd x = if x % 2 = 0 then ok x else fail "Even!"
let x = ok 5
let oddX = x |> bind isOdd
while lift
"transports" a given function from the world of "ordinary" functions into the world of Result<_>
functions:
let plus5 x = x + 5 // plus5 : int -> int
let liftedPlus5 = lift plus5 // lisftedPlus5 : Result<int,_> -> Result<int,_>
let seven = liftedPlus5 (ok 2)
There is a very nice article by the venerable Scott Wlaschin that talks about these things in a very nice and understandable way: Elevated World. One of my favorite articles ever.
(and here is one about bind
)
P.S. Sorry if you find small mistakes in above examples - I don't have a working F# environment to test right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With