Hi,
matching character agains a list or a range isn't directly supported, but you can write active patterns to allow this. Active patterns are a way for implementing your own "tests" for pattern matching:

1
2
3
4
5
6
7
 
// tests whether the character 'c' is in the range 'cfrom' .. 'cto'
let (|CharRange|_|) (cfrom, cto) c = 
  if c >= cfrom && c <= cto then Some(c) else None
//  tests whtether the character 'c' is in the specified list 'clist'
let (|CharList|_|) clist c =
  if List.exists (fun e -> e = c) clist then Some(c) else None

Now you can write the pattern match using these patterns like this (note that the list of characters or a specified range is input argument for the active pattern - the 'c' value is the result of the pattern and this is the value returned from the pattern if it returns 'Some(c)' ):

1
2
3
4
5
 
match 'a' with
| CharRange('1','8') c -> int c - 48
| CharList ['p'; 'b'; 'n' ] c -> 1
| _ -> 99

Hope this helps!
T.

By on 11/4/2008 3:26 AM ()

Thanks! Works perfectly. Better than nothing. :)

By on 11/5/2008 11:17 AM ()

Hi,

Note that the CharRange function given by Tomas is generic: you can use it with any type that supports comparison (basically, anything but functions). So I suggest you to rename the function. :)

For your letters, you don't have to use a list here:

1
2
match 'a' with
| 'p' | 'b' | 'n' -> 1

Laurent.

By on 11/5/2008 11:48 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