locked
How to count number of elements in tuple RRS feed

  • Question

  • How to count number of elements in tuple

    For counting number of columns , numofcols, it should be 3 for first row (0,1,0)

    let matrix1 = [(0,1,0)] :: [(1,0,1)] :: [(0,1,0)] :: []
        Guess1(matrix1)
    let Guess1(g2 : list<'a>) =
        let numofrows = g2.Length
        let firstrow = g2.Item(0)
        let numofcols = Seq.length firstrow


    Friday, February 28, 2014 4:07 AM

Answers

  • This is quite easy using reflection:

    open Microsoft.FSharp.Reflection
    
    let tupleLen (t:'a) =
        if FSharpType.IsTuple typeof<'a> then
            Some (FSharpType.GetTupleElements typeof<'a>).Length
        else None

    Function tupleLen returning int option when applied to a tuple will return Some (tuple length), otherwise None.

    VisualF# alert

    • Proposed as answer by Mr. Tines Friday, February 28, 2014 7:44 AM
    • Marked as answer by Map to new space Monday, March 3, 2014 3:38 AM
    Friday, February 28, 2014 5:06 AM