我有一个函数类型
Reader<_, string option>
,我想在 ReaderT<_, unit option>
中使用它,这样我就可以使用 option
一直钻取到 let!
中的值,请问我该怎么做?
let fun1: Reader<_, string option> = // some implementation
let fun2: ReaderT< _, unit option> = monad {
let! valueFun1 = // how do I drill through option and reader monad to get the value inside? lift and hoist?
return ()
}
一个可行的解决方案是将
fun1
弯曲为 ReaderT< _ , string option>
类型,这样我就可以在 fun2
中无缝地使用它,但我不需要 ReaderT
中 fun1
的额外功能,我想保持最优雅
您只需打开
Reader
并将其包裹成ReaderT
:
#r "nuget: FSharpPlus"
open FSharpPlus
open FSharpPlus.Data
let fun1: Reader<int, string option> = Unchecked.defaultof<_> // some implementation
let fun2: ReaderT<int, unit option> = monad {
let! valueFun1 = ReaderT (Reader.run fun1)
return () }
话虽如此,首先有一个
Reader<'R, string option>
的目的是什么?
除非您要绑定整个
string option
类型,我的意思是在不期望选项短路效果的情况下,我会跳过 Reader
包装器。
要么将其保留为裸函数,要么将其直接包装到 ReaderT
(如果您知道稍后会绑定短路效果)。