Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Trial.lift and Trial.bind in chessie error handling?

Tags:

f#

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?

like image 266
user3587180 Avatar asked Jul 13 '17 00:07

user3587180


1 Answers

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.

like image 179
Fyodor Soikin Avatar answered Nov 01 '22 21:11

Fyodor Soikin