如何将带有int元素的Array2D转换为带有int元素的Array2D

时间:2014-02-21 18:42:22

标签: arrays f# option

我试图将带有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),但当我意识到该消息明确指出Array2D arr属于类型时,仍会收到上述错误消息int [,] option而非int option [,]。应用相同的逻辑我的更正代码如下:

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

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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
相关问题