// @brief Swaps the values of two state effect handlers. // Given two state effect…
- User
// @brief Swaps the values of two state effect handlers. // Given two state effect handlers, this function swaps their values. func swap in (lhs: ref, rhs: ref): unit { let tmp = lhs.get(); lhs.set(rhs.get()); rhs.set(tmp); () }
// @brief Swaps the values of two pointers. // Given two pointers, this function swaps their values. // May abort using the raise effect handler. func swap_ptr(lhs: ptr, rhs: ptr) in (raise: abort): unit { let lhs_brw = ptr2brw(lhs, raise); let rhs_brw = ptr2brw(rhs, raise); swap_brw(lhs_brw, rhs_brw) }
// @brief Swaps the values of two borrowed references. // Given two borrowed references, this function swaps their values. func swap_brw(lhs: brw, rhs: brw): unit { use lhs_ref = brw2ref(lhs); use rhs_ref = brw2ref(rhs); swap(lhs_ref, rhs_ref) }
// @brief Converts a borrowed reference to a state effect handling function. // Can be used with "use" keyword for ergonomics. func brw2ref<a, b>(brw_: brw) in (action: fn(ref_: ref) -> b): b { try { action(ref_) } catch ref_: ref { set(value): resume => brw_.set(value); resume(()), get: resume => resume(brw_.get()), } }
- Assistant
The
swapfunction swaps the values of two state effect handlers. It takes tworef<a>(reference to a value of typea) as input and swaps their values.The
swap_ptrfunction swaps the values of two pointers. It takes twoptr<a>(pointer to a value of typea) as input and swaps their values. It may abort using theraiseeffect handler if an error occurs.The
swap_brwfunction swaps the values of two borrowed references. It takes twobrw<a>(borrowed reference to a value of typea) as input and swaps their values.The
brw2reffunction converts a borrowed reference to a state effect handling function. It can be used with theusekeyword for ergonomics. It takes abrw<a>as input and a functionactionthat operates on aref<a>, and converts the borrowed reference to the state effect handling functionssetandget. - User
ref IS NOT a reference, it is the type of a state effect handler.
- Assistant
Apologies for the confusion. You are correct.
In this context,
ref<a>refers to the type of a state effect handler, not a reference.A state effect handler is an abstraction that allows reading and writing values in an effectful manner. It provides two operations:
get()to read the current value, andset(value)to update the value.The
swapfunction takes two state effect handlers of typeref<a>and swaps their values by performing a temporary assignment.The
swap_ptrandswap_brwfunctions are then provided as utility functions to swap the values of pointers and borrowed references, respectively, by using theswapfunction internally.Apologies again for the incorrect usage of the term "reference" in my previous response.