Constructing a record with a power of Applicative in F#

风流意气都作罢 提交于 2019-12-10 22:35:37

问题


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.


回答1:


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.




回答2:


The straightforward way is:

match aOptional, bOptional, cOptional, dOptional with
| Some a, Some b, Some c, Some d -> Some {A=a; B=b; C=c; D=d}
| _ -> None

or, with a maybe 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}
  }


来源:https://stackoverflow.com/questions/19104114/constructing-a-record-with-a-power-of-applicative-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!