f# - 获取元组选项类型变量的值?

标签 f# f#-3.0

我有以下 F# 代码。函数 getARow 返回 (string * string * string) 选项。在主函数中,我需要提取列值并将它们分别分配给a、b、c。如何实现? (新手问题)

如果没有找到行,该函数可能会返回 null? getARow返回null如何处理?

open System
open System.Data
open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Microsoft.FSharp.Linq
open System.Net
open System.IO
open FSharp.Data

type dbSchema = SqlDataConnection<"Data Source=Svr;Initial Catalog=DB;Integrated Security=SSPI;"> 
//, LocalSchemaFile = "Schema.dbml", ForceUpdate = false > 

let getARow =
    let db = dbSchema.GetDataContext()
    db.DataContext.Log <- System.Console.Out
    let query = query { 
        for row in db.Table1 do 
        where (row.SiteID = 1) 
        select (Some(row.Col1, row.Col2, row.Col2)) // All Colx are strings
        headOrDefault // May return null
        }
    query 

[<EntryPoint>]
let main argv = 
    let aRow = getARow
    printfn "%A" aRow 

    let a,b,c = match aRow with
    | ........ // How to let a = Col1, b = Col2 and c = Col3?
    | None -> failwith "Cannot find a row" // Null?
    0

最佳答案

要从选项类型中提取值(无论它包含什么),您需要使用 Some <...>模式在哪里 <...>是一个嵌套模式,可以为值命名(如果你想要一个包含元组的单个变量)或进一步分解它(如果你想要三个单独的变量):

let a,b,c = 
  match aRow with
  | Some(a, b, c) -> a, b, c
  | None -> failwith "Cannot find a row"

或者,您可以只使用内置的 Option.get功能:

let a,b,c = Option.get aRow

您的代码依赖于一个技巧 - 即 headOrDefault返回 null如果没有行 - 这将起作用,因为 nullNone 的内部表示.但你也可以使用 an extension that adds headOrNone 使代码更漂亮。

关于f# - 获取元组选项类型变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920342/

相关文章:

f# - 将 OCaml 代码转换为 F#

list - 从列表 F# 中删除每第 3 个元素

F# - 如果更改则设置属性

f# - F# 代码片段在 MONO 下不起作用

oop - 我应该在类型定义中使用 this、self 还是其他东西作为 self 标识符?

.net - F#/.NET : add an element to an array of List<T>

f# - 如何在 VS 2015 中使用 FSharp.Data?

f# - 只读与自动(只读)属性

f# - 有没有一种方法可以在没有Visual Studio的情况下安装F#3.0?

.net - F# 3.1 是否需要安装特定的运行时?