【问题标题】:Sharing functions across different types跨不同类型共享功能
【发布时间】:2019-04-08 11:29:32
【问题描述】:

如果 f# 编写了一个 etl 进程,它将在关系数据库中排序数据并将其转换为星型模式,为第 3 方平台做好准备。因为我们正在对数据进行非规范化,所以我们(几乎)拥有重复的对象、类型和属性,这些对象、类型和属性散布在我们的系统中。到目前为止,我对此感到满意,因为对象的不同足以保证不同的功能,或者我们已经能够将公共/共享属性分组到子记录中。

但是,我们现在添加的对象需要挑选系统的不同部分,并且不属于现有的通用分组。 在尝试了几种不同的风格后,我开始使用界面,但使用它们感觉有些不对劲。有没有人遇到过这个问题并想出不同的方法?

module rec MyModels =
    type AccountType1 =
        { Id : int
          Error : string option 
          Name : string option }
        // PROBLEM: this get very bulky as more properties are shared
        interface Props.Error<AccountType1> with member x.Optic = (fun _ -> x.Error), (fun v -> { x with Error = v })
        interface Props.AccountId<AccountType1> with member x.Optic = (fun _ -> x.Id), (fun v -> { x with Id = v })
        interface Props.AccountName<AccountType1> with member x.Optic = (fun _ -> x.Name), (fun v -> { x with Name = v })

    type AccountType2 =
        { Id : int
          Error : string option 
          AccountId : int
          AccountName : string option
          OtherValue : string }
        interface Props.Error<AccountType2> with member x.Optic = (fun _ -> x.Error), (fun v -> { x with Error = v })
        interface Props.AccountId<AccountType2> with member x.Optic = (fun _ -> x.AccountId), (fun v -> { x with AccountId = v })
        interface Props.AccountName<AccountType2> with member x.Optic = (fun _ -> x.AccountName), (fun v -> { x with AccountName = v })
        interface Props.OtherValue<AccountType2> with member x.Optic = (fun _ -> x.OtherValue), (fun v -> { x with OtherValue = v })

    module Props =
        type OpticProp<'a,'b> = (unit -> 'a) * ('a -> 'b)    

        // Common properties my models can share
        // (I know they should start with an I)

        type Error<'a> = abstract member Optic : OpticProp<string option, 'a>
        let Error (h : Error<_>) = h.Optic

        type AccountId<'a> = abstract member Optic : OpticProp<int, 'a>
        let AccountId (h : AccountId<_>) = h.Optic

        type AccountName<'a> = abstract member Optic : OpticProp<string option, 'a>
        let AccountName (h : AccountName<_>) = h.Optic

        type OtherValue<'a> = abstract member Optic : OpticProp<string, 'a>
        let OtherValue (h : OtherValue<_>) = h.Optic

[<RequireQualifiedAccess>]
module Optics =
    // Based on Aether
    module Operators =
        let inline (^.) o optic = (optic o |> fst) ()
        let inline (^=) value optic = fun o ->  (optic o |> snd) value

    let inline get optic o =
        let get, _ = optic o
        get ()

    let inline set optic v (o : 'a) : 'a = 
        let _, set = optic o
        set v

open MyModels
open Optics.Operators

// Common functions that change the models

let error msg item =
    item
    |> (Some msg)^=Props.Error
    |> Error

let accountName item = 
    match item^.Props.AccountId with
    | 1 -> 
        item
        |> (Some "Account 1")^=Props.AccountName
        |> Ok
    | 2 -> 
        item
        |> (Some "Account 2")^=Props.AccountName
        |> Ok
    | _ ->
        item
        |> error "Can't find account"

let correctAccount item =
    match item^.Props.AccountName with
    | Some "Account 1" -> Ok item
    | _ ->
        item
        |> error "This is not Account 1"

let otherValue lookup item =
    let value = lookup ()

    item
    |> value^=Props.OtherValue
    |> Ok

// Build the transform pipeline

let inline (>=>) a b =
    fun value ->
    match a value with
    | Ok result -> b result
    | Error error -> Error error


let account1TransformPipeline lookups = // Lookups can be passed around is needed
    accountName
    >=> correctAccount

let account2TransformPipeline lookups =
    accountName
    >=> correctAccount
    >=> otherValue lookups

// Try out the pipelines

let account1 = 
    ({ Id = 1; Error = None; Name = None } : AccountType1)
    |> account1TransformPipeline ()

let account2 = 
    ({ Id = 1; Error = None; AccountId = 1; AccountName = None; OtherValue = "foo" } : AccountType2)
    |> account2TransformPipeline (fun () -> "bar")

我尝试过的其他方法:

  • Aether Optics – 除非我遗漏了什么,否则这只是为了编辑 复杂对象的子类型不具有公共属性
  • 鸭子打字——我很喜欢这个,但问题是你也必须内联 多种功能

【问题讨论】:

  • 你可以看看F# Crates
  • 我认为你的界面很好。 SRTP(鸭子打字)会使情况变得更糟恕我直言。
  • 其实我做了一些非常相似的事情......但是我自动生成了大部分代码

标签: types f# record


【解决方案1】:

我不确定如何使您的解决方案更简单 - 我认为您的方法中对类型的非常花哨的使用使代码变得相当复杂。可能有其他方法可以简化这一点,同时保持某种类型的输入。同样,我认为在某些情况下,您需要实现的逻辑是相当动态的,然后可能值得使用一些更动态的技术,即使在 F# 中也是如此。

举个例子,这里是一个使用Deedle data frame library的例子。这使您可以将数据表示为数据框(列名称为字符串)。

在数据帧上编写您需要的两个清理操作相对容易 - 该库针对基于列的操作进行了优化,因此代码结构与您的有点不同(我们计算新列,然后将其替换为所有数据框中的行):

let correctAccount idCol nameCol df = 
  let newNames = df |> Frame.getCol idCol |> Series.map (fun _ id ->
    match id with
      | 1 -> "Account 1" 
      | 2 -> "Account 2" 
      | _ -> failwith "Cannot find account")
  df |> Frame.replaceCol nameCol newNames

let otherValue newValue df = 
  let newOther = df |> Frame.getCol "OtherValue" |> Series.mapAll (fun _ _ -> Some newValue)
  df |> Frame.replaceCol "OtherValue" newOther

然后您的管道可以获取记录,将它们转换为数据帧并进行所有处理:

[ { Id = 1; Error = None; Name = None } ]
|> Frame.ofRecords
|> correctAccount "Id" "Name"

[ { Id = 1; Error = None; AccountId = 1; AccountName = None; OtherValue = "foo" } ]
|> Frame.ofRecords
|> correctAccount "Id" "AccountName"
|> otherValue "bar"

这在类型安全方面不如您的方法,但我相信人们实际上可以阅读代码并很好地了解它的作用,这可能值得权衡。

【讨论】:

  • 我同意,lens' 只是让代码难以阅读,这不是一个部分困难的问题,只是现在看起来它与所有的光学元件......
  • deedle 是否类似于 ado.net 数据集或数据表或 Apache spark 数据框?
  • Deedle 的灵感来自 Python 的 pandas 库和 R 数据帧。 ADO.NET 数据集可能不是那么接近(因为它没有很多您可以对其进行的操作)。我不太了解 Spark 数据帧,但我猜它们是相关的(但 Deedle 不适用于大数据)。
  • 感谢 Tomas 提供反馈并花时间制作示例。您生成的代码非常适合对我的问题中的数据进行建模,因此这是一个很好的答案。但是,在我们的生产系统中,我认为我不能安全地丢失类型并添加魔法刺,因为它可能导致运行时失败。我不认为我们的系统在宏观上属于“大数据”,但我们将其视为大数据。
  • @davidtme 我确实写了答案只是为了展示一个更动态的替代方案可能是什么样子 - 当然还有其他方法可以做到这一点,也许还有更好和类型安全的方法。如果我面临您的问题所说明的问题,我可能会选择动态选项 - 因为在这种情况下强制执行安全性对我来说具有太高的可读性成本。 (也许,我需要更多测试以确保处理正确,但这可能是值得付出的代价。)
猜你喜欢
  • 1970-01-01
  • 2014-06-19
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多