【问题标题】:How to convert an Array2D with option int elements to Array2D with int elements如何将带有选项 int 元素的 Array2D 转换为带有 int 元素的 Array2D
【发布时间】:2014-03-23 10:50:51
【问题描述】:

我正在尝试将带有选项 int 元素的 Array2D optionArr 转换为带有 int 元素的 Array2D arr:

let arr =
    optionArr
    |> Array2D.map (fun x -> 
        match Option.toArray x with
        | [| |] -> -1
        | [| v |] -> v)

然而,Visual Studio 2013 用红色强调了从 Array2D.map ... 到 ... -> v) 的所有内容,并表示:

Type mismatch. Expecting a  
    int [,] option -> 'a
but given a  
    'b [,] -> 'c [,]  
The type 'int [,] option' does not match the type ''a [,]'

我一直在尝试“修复”我的代码,但我不知道我做错了什么,也不知道上述错误消息暗示了什么。

编辑

我申请了Reed Copsey's answer(它本身使用Marcin's approach),但当我意识到该消息明确指出Array2Darr 的类型为int [,] option 而不是int option [,] 时,仍然收到上述错误消息.应用相同的逻辑,我更正的代码如下:

let arr = defaultArg optionArr (Array2D.zeroCreate 0 0)

defaultArg 似乎对于将 Option 值视为“正常”值非常有用。

【问题讨论】:

  • 如何声明optionArr?真的是二维数组还是锯齿数组?
  • 不是锯齿状数组,而是二维数组。有关声明,请参阅 Tomas Petricek 对 stackoverflow.com/questions/21919785/… 的回答。

标签: arrays f# option


【解决方案1】:

Marcin's approach 工作正常。这也可以更简单地直接使用defaultArg:

// Create our array
let optionArr = Array2D.create 10 10 (Some(1))

let noneToMinusOne x = defaultArg x -1
let result = optionArr |> Array2D.map noneToMinusOne

【讨论】:

    【解决方案2】:
    let arr optionArr =
        optionArr
        |> Array2D.map (fun x -> 
            match x with
            | Some(y) -> y
            | None -> -1)
    

    用法

    let getOptionArr =
        Array2D.create 10 10 (Some(1))
    
    let result = arr getOptionArr
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 2020-01-05
    • 2020-03-17
    • 2020-11-19
    • 2018-09-29
    • 2014-09-12
    • 2018-04-18
    • 2020-03-12
    相关资源
    最近更新 更多