Iterating through a List<List<>> looking for a value in F#

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)

The code above is wrong.

Could anyone suggest me how to achieve that result?


This is a direct translation of your C# code:

   let contains value (ls: _ list list) = 
       let mutable found = false
       for row in ls do
           if not found then
               for el in row do
                    if not found && el = value then
                        found <- true

To modify value of a variable in F#, you should use mutable or ref keywords. However, in F# doing the functional way:

let contains value ls  = 
     ls |> List.exists (List.exists ((=) value))

Different from for .. in ... do, which is a syntactic sugar, the higher-order function List.exists will 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:

let contains value (ls: _ list list) = 
     ls |> List.concat |> Set.ofList |> Set.contains value

Another, slightly different, way to do it

let contains value items =
  |> Seq.concat
  |> Seq.exists ((=) value)

or, more concisely

let contains value = 
  Seq.concat >> Seq.exists ((=) value)

Need Your Help

JSONP Ajax Call with JQuery causes memory leak

ajax performance jquery memory-leaks

I already searched a complete day and cannot find the issue why I get such big memory leaks in my phonegap application, which uses a lot of ajax-jsonp requests to the server.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.