假设有一个type r = {A : int; B : string; C : int; D : string}和一些值:
let aOptional : int option = ...
let bOptional : string option = ...
let cOptional : int option = ...
let dOptional : string option = ...
Run Code Online (Sandbox Code Playgroud)
如何r optional从他们的eleganlty(没有嵌套的案件等)构建?
顺便说一下,这是如何在haskell中完成的Control.Applicative:
data R = R { a :: Integer, b :: String, c :: Integer, d :: String}
R <$> aOptional <*> bOptional <*> cOptional <*> dOptional :: Maybe R
Run Code Online (Sandbox Code Playgroud)
寻找fsharp中的等价物.
我知道的唯一方法(使用applicatives)是通过创建一个函数来构造记录:
let r a b c d = {A = a; B = b; C = c; D = d}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
> r </map/> aOptional <*> bOptional <*> cOptional <*> dOptional ;;
val it : R option
Run Code Online (Sandbox Code Playgroud)
您可以定义map与<*>自己,但如果你想有一个通用的实现尝试用代码F#+或者如果你想使用FsControl直接,你可以写代码是这样的:
#r "FsControl.Core.dll"
open FsControl.Operators
let (</) = (|>)
let (/>) f x y = f y x
// Sample code
type R = {A : int; B : string; C : int; D : string}
let r a b c d = {A = a; B = b; C = c; D = d}
let aOptional = Some 0
let bOptional = Some ""
let cOptional = Some 1
let dOptional = Some "some string"
r </map/> aOptional <*> bOptional <*> cOptional <*> dOptional
// val it : R option = Some {A = 0; B = ""; C = 1; D = "some string";}
Run Code Online (Sandbox Code Playgroud)
更新:Nuget包现已上市.
直截了当的方式是:
match aOptional, bOptional, cOptional, dOptional with
| Some a, Some b, Some c, Some d -> Some {A=a; B=b; C=c; D=d}
| _ -> None
Run Code Online (Sandbox Code Playgroud)
或者,有一个monad:
let rOptional =
maybe {
let! a = aOptional
let! b = bOptional
let! c = cOptional
let! d = dOptional
return {A=a; B=b; C=c; D=d}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |