문제

I am trying to convert Array2D optionArr with option int elements to Array2D arr with int elements:

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

However, Visual Studio 2013 underlines everything starting from Array2D.map ... until ... -> v) with red and says:

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

I have been trying to "fix" my code but I no idea what I am doing wrong nor what the above error message alludes to.

EDIT

I applied Reed Copsey's answer (which itself uses Marcin's approach), yet still got the above error message when I realised that the message clearly states that Array2D arr is of type int [,] option and not int option [,]. Applying the same logic my corrected code is as follows:

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

defaultArg seems to be quite useful for treating Option values as 'normal' ones.

도움이 되었습니까?

해결책

Marcin's approach works fine. This can also be done a bit more simply using defaultArg directly:

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

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

다른 팁

let arr optionArr =
    optionArr
    |> Array2D.map (fun x -> 
        match x with
        | Some(y) -> y
        | None -> -1)

usage

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

let result = arr getOptionArr
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top