Aaaaarrrrrghhhh. Silly me.

Thank you all for help.

How long did you guys needed to learn all those tiny little details?

By on 1/5/2009 9:14 AM ()

Hi zendar,

In your second code example you are not matching buffer.[0..1] with the let bound c1. In fact you are redefining c1 within the match expression to contain whatever value you pass to the match:

1
2
3
4
5
6
let c1 = 1
match [| 1; 2 |] with c1 -> c1


val it : int array = [|1; 2|]

This is because in the cases of the match there is a decomposition then a binding (together these are called the pattern match.) In the case above [| 1; 2|] is not decomposed (as c1 has no structure,) so is simply bound to c1.

Perhaps you are looking for pattern matching with guards so:

1
2
3
4
5
6
7
8
9
10
11
let c1 = [| 1; 1 |]
let c2 = [| 1; 2 |]

match [| 1; 2 |] with 
| x             when x = c1             -> 1uy
| x             when x = c2             -> 2uy
| [| x1; x2 |]  when x1 = 1 && x2 = 3   -> 3uy
| _                                     -> 4uy


val it : byte = 2uy

regards,

Danny

P.S: Beaten to the draw!

By on 1/5/2009 9:08 AM ()

Hello,

in short, you may not use variables in patterns, but you may use they in guards (after "when"), so your code will looks like:

1
2
3
4
5
6
7
let FindMessageType (buffer : byte[]) =
    let c1 = [| 0x24uy; 0x6Cuy |]
    let c2 = [| 0x24uy; 0x43uy |]
    match buffer.[0..1] with
      | c when c = c1  -> 1uy
      | c when c = c2 -> 2uy
      | _ -> 0uy
By on 1/5/2009 9:03 AM ()

In the second pattern, c1 refers to any incoming value and not to the value that you defined above. You could write a pattern like this:

let FindMessageType (buffer : byte[]) =
let c1 = [| 0x24uy; 0x6Cuy |]
let c2 = [| 0x24uy; 0x43uy |]
match buffer.[0..1] with
| c3 when c3 = c1 -> 1uy
| c4 when c4 = c2 -> 2uy
| _ -> 0uy

Otherwise, you'll have to use the byte array literals as you are in the first example.

By on 1/5/2009 8:58 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper