I need a function that returns a List < List < T>>.
The value i j should be 1.0 or 2.0 or nothing..depending on certain conditions (condition_1_is_true …).
I’ve written the following :
type T =
{
value : float32
}
let level_1_docked_balls : List<List<T>>=
[ for i in 0 .. LineNumber - 1->
[ for j in 0 .. BallsPerLine - 1 ->
if (condition_1_is_true) then
{
value = 1.0f
}
elif (condition_2_is_true) then
{
value = 2.0f
}
else
//HERE I don't know how to return nothing
]
]
The problem is that in certain cases (else branch), I need to return nothing, but I don’t know how to do it.
NOTE: I know that there are eventually better ways to initialize a List but I would like to understand how to make the above example work.
You probably want something like:
There is no way to say that there is nothing at a specified index in the list. A list is simply a list of values and if you didn’t return a value, then the list would be shorter. If you want to represent
floator nothing, then you can use F#optiontype – the valueSome 1.0fspecifies that there is a value 1.0f and the valueNonespecifies that there is no number at that position.I also changed the type from
floattofloat32in the type annotation. The typefloat32corresponds toSystem.Singleand the literals are written as1.0f. The other option is double (floatwith literals1.0).As a side-note, if you’re representing some 2D matrix and especially if you need to access value at a specified index, then it is probably better to use 2D array. Although they are mutable, you can use them in an immutable way using higher-order functions like
Array2D.map. To create a 2D array similar to your list, you could write:EDIT There are two options to represent something like balls in a map of a game. Either use dense representation where you have some value for each (i, j) – that’s what I described earlier. Another option is to use sparse representation where you only keep a list of balls, together with the (i, j) index where the ball is located. Then you could write something like:
When you use
doin theforloop, then you can writeyieldto generate an element, but you don’t have to return a value in each case — there is noelsebranch. However, you need to know the index where the value belongs.