How to convert an Array2D with option int elements to Array2D with int elements

StackOverflow https://stackoverflow.com/questions/21942636

  •  14-10-2022
  •  | 
  •  

سؤال

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