在F#中构建具有Applicative功能的记录

时间:2013-09-30 21:22:39

标签: haskell f#

假设有一个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 = ...

如何从他们的eleganlty构建r optional(没有嵌套的case-stuff等)?


顺便说一句,以下是使用Control.Applicative在haskell中完成的方法:

data R = R { a :: Integer, b :: String, c :: Integer, d :: String}

R <$> aOptional <*> bOptional <*> cOptional <*> dOptional :: Maybe R

在fsharp中寻找相同的东西。

2 个答案:

答案 0 :(得分:5)

我知道的唯一方法(使用applicatives)是通过创建一个函数来构建记录:

let r a b c d = {A = a; B = b; C = c; D = d}

然后你可以这样做:

> r </map/> aOptional <*> bOptional <*> cOptional <*> dOptional ;;

val it : R option

您可以自己定义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";}

更新Nuget packages现已上市。

答案 1 :(得分:5)

直截了当的方式是:

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

或使用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}
  }