3 people like it.
Like the snippet!
Initialization of 2D array that may fail
A function to initialize 2D array that supports failures - if the initializer fails to produce value for any of the array locations, the construction is stopped and the function returns 'None'
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
|
/// Attempts to initialize a 2D array using the specified base offsets and lengths.
/// The provided function can return 'None' to indicate a failure - if the initializer
/// fails for any of the location inside the array, the construction is stopped and
/// the function returns 'None'.
let tryInitBased base1 base2 length1 length2 f =
let arr = Array2D.createBased base1 base2 length1 length2 (Unchecked.defaultof<_>)
/// Recursive function that fills a specified 'x' line
/// (returns false as soon as any call to 'f' fails, or true)
let rec fillY x y =
if y < (base2+length2) then
match f x y with
| Some v ->
arr.[x, y] <- v
fillY x (y + 1)
| _ -> false
else true
/// Recursive function that iterates over all 'x' positions
/// and calls 'fillY' to fill individual lines
let rec fillX x =
if x < (base1+length1) then
if fillY x base2 then fillX (x + 1)
else false
else true
if fillX base1 then Some arr else None
|
val tryInitBased : base1:int -> base2:int -> length1:int -> length2:int -> f:(int -> int -> 'a option) -> 'a [,] option
Full name: Script.tryInitBased
Attempts to initialize a 2D array using the specified base offsets and lengths.
The provided function can return 'None' to indicate a failure - if the initializer
fails for any of the location inside the array, the construction is stopped and
the function returns 'None'.
val base1 : int
val base2 : int
val length1 : int
val length2 : int
val f : (int -> int -> 'a option)
val arr : 'a [,]
module Array2D
from Microsoft.FSharp.Collections
val createBased : base1:int -> base2:int -> length1:int -> length2:int -> initial:'T -> 'T [,]
Full name: Microsoft.FSharp.Collections.Array2D.createBased
module Unchecked
from Microsoft.FSharp.Core.Operators
val defaultof<'T> : 'T
Full name: Microsoft.FSharp.Core.Operators.Unchecked.defaultof
val fillY : (int -> int -> bool)
Recursive function that fills a specified 'x' line
(returns false as soon as any call to 'f' fails, or true)
val x : int
val y : int
union case Option.Some: Value: 'T -> Option<'T>
val v : 'a
val fillX : (int -> bool)
Recursive function that iterates over all 'x' positions
and calls 'fillY' to fill individual lines
union case Option.None: Option<'T>
More information