I have a List<List<int>> in F#. I need to iterate through it looking for a given value val.
In C# I would do something like:
public bool contains(List<List<int>> list, int value)
foreach (l in list ){
foreach(val in l){
if (val == value)
return true; //found value
}
}
return false;
}
I’m looking for the equivalent in F#. I tried the following but I’m doing something wrong, because I’m not still used to F# syntax:
type foo =
{
l : List<List<float>>
}
let contains (value: float) : bool =
for row in foo.l do
for val in row do
if (val == value)
true
false
The code above is wrong.
Could anyone suggest me how to achieve that result?
This is a direct translation of your C# code:
To modify value of a variable in F#, you should use
mutableorrefkeywords. However, in F# doing the functional way:Different from
for .. in ... do, which is a syntactic sugar, the higher-order functionList.existswill stop immediately when it finds the answer.This version does not scale well if your lists are big. You can convert list to set to be able to find the element faster: