在F#中构建一个应用程序的强大记录 [英] Constructing a record with a power of Applicative in F#
问题描述
类型r = {A:int; B:字符串; C:int; D:string}
和一些值: $ b
let aOptional: int option = ...
let bOptional:string option = ...
let cOptional:int option = ...
let dOptional:string option = ...
如何 r可选
可以由他们构建eleganty(不嵌套这些是如何在haskell中完成的 Control.Applicative
:
$ b
data R = R {a :: Integer,b :: String, c :: Integer,d :: String}
R $ $> a可选的* b可选的* c可选的* dOptional ::也许R
在fsharp中寻找等价的东西。
<我知道的唯一方法(使用applicatives)是通过创建一个函数来构造记录:
<$ p $ p>
let rabcd = {A = a; B = b; C = c; D = d}
然后你可以这样做:
> r< / map /> a可选的* b可选的* c可选的*可选;;
val it:R选项
您可以定义 map
和< *>
,但是如果您想要一个通用实现,请使用 F#+ ,或者如果您想使用 FsControl 直接你可以这样编写代码:
#rFsControl.Core.dll
open FsControl.Operators
let(< /)=(|>)
let(/>)fxy = fyx
/ /示例代码
type R = {A:int; B:字符串; 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 = Somesome string
r< / map /> a可选的* b可选的* c可选的* d可选
// val it:R选项=一些{A = 0; B =; C = 1; D =some string;}
$ b 更新: Nuget软件包现已发布。
Suppose there is a type r = {A : int; B : string; C : int; D : string}
and a some values:
let aOptional : int option = ...
let bOptional : string option = ...
let cOptional : int option = ...
let dOptional : string option = ...
How can r optional
could be constructed from them eleganlty (without nested case-stuff, etc.)?
Btw, here is how it could be done in haskell with Control.Applicative
:
data R = R { a :: Integer, b :: String, c :: Integer, d :: String}
R <$> aOptional <*> bOptional <*> cOptional <*> dOptional :: Maybe R
Looking for something equivalent in fsharp.
The only way I know (using applicatives) is by creating a function to construct the record:
let r a b c d = {A = a; B = b; C = c; D = d}
Then you can do:
> r </map/> aOptional <*> bOptional <*> cOptional <*> dOptional ;;
val it : R option
You can define map
and <*>
yourself, but if you want a generic implementation try that code with F#+ or if you want to use FsControl directly you can write the code this way:
#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";}
UPDATE: Nuget packages are available now.
这篇关于在F#中构建一个应用程序的强大记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!