【问题标题】:Return Data From Function F#从函数 F# 返回数据
【发布时间】:2019-04-26 14:14:07
【问题描述】:

我是 F# 的新手。我有一个执行一些数据库操作的函数。我正在努力返回结果。

let funcA () = 
 let funcB () = 
    // do some database operation and returns seq of records
 let funcC () = 
    // do some other database operation returns nothing
 let result = funcB ()
 funcC ()

如何从funcA 返回result?我需要在funcC之前执行funcB

【问题讨论】:

    标签: f#


    【解决方案1】:

    函数的最后一行应该是你的返回值。在您的情况下,您不一定需要在此处嵌套函数,但我们可以保持原样。此外,重要的是要注意 F# 默认情况下是一种热切求值的语言,因此如果您在没有任何参数的情况下定义函数,它们实际上会被预先求值(并且不会随着未来的执行而改变)。如果您的函数实际上不需要任何参数,请提供 unit 值作为参数。

    let funcA () = // Function defintion

    而不是

    let funcA = // Function definition

    let funcA () = 
     let funcB () = 
         // Perform database operation
     let funcC () = 
         // Perform some side-effect, returns ()
    
     let result = funcB ()
     funcC ()
    
     result // This will be your return value
    
    let a = funcA () // Example usage
    

    【讨论】:

    • 执行funcC后有没有办法返回result
    • 看我的编辑,关键是最后一行是你的返回值。因此,只需将 result 放在末尾,它就会被返回,而不是 funcC () 的结果
    【解决方案2】:

    接受的答案工作正常,但不是很fsharp-y

    如果你的 funcC 只能在 funcB 之后执行,这可以通过使用 funcB 的结果类型作为 funcC 的输入来更明确。或者更好的是,使用铁路模式:

    let funcA () =
      let funcB () : Result<Seq<Foo>, string> =
        // perform database operation, return Ok <| sequence of Foo if successful
        // otherwise Error <| "sql failed"
    
      let funcC x =
        // perforn some side effect
        x //return input
      funcB ()
      |> Result.map funcC
    

    (See Scott Wlaschins excellent posts about railway oriented programming)

    【讨论】:

      猜你喜欢
      • 2012-06-21
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 2019-06-02
      相关资源
      最近更新 更多