[英]Constructing a record with a power of Applicative in F#
假設有一個type r = {A : int; B : string; C : int; D : string}
type r = {A : int; B : string; C : int; D : string}
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等)?
順便說一句,這是如何在haskell中使用Control.Applicative
:
data R = R { a :: Integer, b :: String, c :: Integer, d :: String}
R <$> aOptional <*> bOptional <*> cOptional <*> dOptional :: Maybe R
尋找fsharp中的等價物。
我知道的唯一方法(使用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包現已上市。
直截了當的方式是:
match aOptional, bOptional, cOptional, dOptional with
| Some a, Some b, Some c, Some d -> Some {A=a; B=b; C=c; D=d}
| _ -> None
或者,有一個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}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.