The pattern discriminator is not defined

Viewed 2303

I'm new in F#, can you help me with this error: 'The pattern discriminator is not defined'

let findColorIndex colorArray, color =
    let mutable index=0
    for i in 0..colorArray.Length-1 do
                 if Color.FromName(colorArray.[i]).R.Equals(color.R) then 
                    if Color.FromName(colorArray.[i]).G.Equals(color.G) then 
                        if Color.FromName(colorArray.[i]).B.Equals(color.B)
                            then index<-i
    index
2 Answers

The error message is difficult to read. It is the initial comma that the compiler does not like. You probably mean either

let findColorIndex colorArray color =

or

let findColorIndex (colorArray, color) =

Stylistically, your code looks like a straight translation of C# code. It works but it doesn't look very nice. I rewrote it as follows:

// A little helper function to get all color values at once
let getRGB (color : Color) = (color.R, color.G, color.B)

let findColorIndex colorArray color =
    let rec findIdx i =
        // If no matching color is found, return -1
        // Could use options instead...
        if i >= colorArray.Length then -1
        elif getRGB (Color.FromName colorArray.[i]) = getRGB color then i
        else findIdx (i + 1)
    findIdx 0

Alternatively you could use Array.tryFindIndex:

let findColorIndex colorArray color =
    // Returns None if no matching index is found,
    // otherwise Some index
    colorArray |> Array.tryFindIndex (fun c ->
        getRGB (Color.FromName c) = getRGB color)
Related