Hide this comment

Here you can use the following code:

match A with

| 1 when B < 10 && B > 1 -> "good"

| 2 when B > 11 && B < 20 -> "bad"

By on 2/12/2009 10:15 PM ()Reply
Hide this comment

Hi, you can also use active patterns and write something like this:

1
2
3
4
5
6
7
// pattern to check whether the number 'x' is in the specified range
let (|Between|_|) (nfrom, nto) x = 
  if x < nfrom && x > nto then Some(x) else None

match A, B with
| 1, Between(1, 10) _ -> "good"    // note: the underscore ignores the value returned from the pattern
| 2, Between(11, 20) _ -> "good"   // (which is the original number in this example)

I believe this makes the code a bit more readable :-).
T.

By on 2/13/2009 3:29 AM ()Reply
Hide this comment

You can rid of the underscores by returning Some () instead of Some(x) from the active patternThen it's even more readable [;)]

By on 2/13/2009 4:13 AM ()Reply
Hide this comment

That doesn't seem to work unfortunatelly - the active pattern returns a unit value that you still have to consume somehow, so if I write Some() I still have to write something, either underscore or this:

1
2
3
4
 
match 0, 0 with
| 1, Between(1, 10) () -> "good"
| 2, Between(11, 20) () -> "good"

Perhaps active patterns should be able to return just true/false in this case...

T.

By on 2/13/2009 4:25 AM ()Reply
Hide this comment

Hmm, it doesn't work indeed. The problem apparently isn't the return value, but the fact that active patterns do not behave like curried functions. This for instance works fine:

1
2
3
4
5
6
let (|Between_1_and_10|_|) x =
  if x>=1 && x<=10 then Some() else None
  
match 0 with
| Between_1_and_10 -> "good"
| _ -> "bad"
By on 2/13/2009 5:27 AM ()Reply
Hide this comment

Unless you are going out of your way to be recondite, the obvious way to write this is to use a simple if..then:

1
2
3
4
let a = 1
let b = 10
if (a = 1 && 1<=b && b<=10) then printfn "good"
if (a = 2 && 11<=b && b<=20) then printfn "bad"
By on 2/13/2009 5:21 AM ()Reply
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

Logging in...