Your Positive is a partial pattern, as indicated by the |_| when declaring it. Which means that it can either succeed (when the function returns Some) or fail (when it returns None).

What would you expect the let line to do? As you can see on the line with +5, p is an int, not an int option. The active pattern either returns the value passed to Some, or signals a match failure by returning None.

Note that when you declare g, you have a fallback pattern (the "| _ -> "-"" line). This line is reached when the AP signals a match failure, ie when it returns None. If you remove this line, you will see the same behavior as with let.

If you want to retrieve the int option returned by the matching function, you can actually directly call this function like so:

1
2
let p = (|Positive|_|) +5     // val p : int option = Some 5
let p = (|Positive|_|) -3     // val p : int option = None

Note that this is not a pattern matching; it's a simple function call, where the function happens to have a weird name with parentheses and pipes in it.

By on 12/4/2012 9:13 AM ()

Thank you for answering.
I know about this pattern matching syntax

1
let (Positive p) = +5 

but I never saw an obvoius function call like

1
let p = (|Positive|_|) +5

For the following I expected a Some 5 and not a 5, as the signature shows a int option.
For me it was not clear why the Option goes away.
So the option is eaten by the let-pattern-match.

1
let (Positive p) = +5   // val p : int = 5 
By on 12/4/2012 11:17 AM ()
1
let (Positive p) = 5

is equivalent to

1
2
3
4
let p =
  match 5 with
  | Positive p -> p
  | _ -> raise MatchFailureException

which is in turn equivalent to

1
2
3
4
5
let p =
  match (|Positive|_|) 5 with
  | Some p -> p
  | None -> raise MatchFailureException
                  (* | None ->, can also be replaced with | _ -> *)
By on 12/5/2012 2:28 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