Search code examples
f#active-pattern

Resuse F# Active Pattern result


In the following code I have to reuse the Active Pattern result three times for each iteration. i.e.

match tree.Parent, postion with

I found out that I could save the Active Pattern result. i.e.

let pos = ((|Root|Nil|Single|First|Inner|Last|Unknown|) (tree.Parent, position)) 

What I could not figure out was if the Active Pattern result can be used in a match statement. i.e.

match pos with
| ??? -> printf "("

The question is can the saved active pattern result be used in a match statement?

If so, how? If not, need to explain it so that it logicaly makes sense.

Examples of possibly why not. i.e. Language Specification, syntactic sugar, should not have allowed active pattern result to be bound, ExprItems vs. PatItems

I looked in the The F# 2.0 Language Specification (April 2010) http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc270597500

But I didn't recognize anything that would confirm an answer.

EDIT

If I change the code to

    let pos = (|Root|Nil|Single|First|Inner|Last|Unknown|) (tree.Parent, position)  
    match pos with                                                                
    | Choice1Of7 (tree.Parent, position) -> printf "("                                                          
    | _    -> ()

I get the following error for (tree.Parent, position) after Choice1Of7:

This expression was expected to have type unit but here has type 'a * 'b

As Brian suggested it should be

    match pos with                                                                
    | Choice1Of7 () -> printf "("                                                          
    | _    -> ()    

End EDIT

Note: The code I tried this in follows, but I did find a better algorithm for what it sovles.

// An F# function to print a CommonTree as an s-expression
// 
// Note: Because the CommonTree data structure was created allowing null values,
// the null value has to be handled.
// 
let commonTreeToSExpression100 (tree : BaseTree) =
    // Define Active Pattern to create new view of node, i.e. BaseTree
    // for position in list instead of content.
    // Note: The name of the active pattern function    is "|Root|Nil|Single|First|Inner|Last|Unknown|"
    let (|Root|Nil|Single|First|Inner|Last|Unknown|) (tree : ITree , position) =
        let parent = tree :?> BaseTree
        match parent with
        | null -> Root
        | _ ->
            let list = parent.Children
            match obj.ReferenceEquals(list,null) with
            | true -> Nil  // This should never happen.
            | false ->
                let count = list.Count
                // TODO: Handle count = 0
                if (count = 1) then Single
                elif (count > 1) && (position = 0) then First
                elif (count > 1) && (position = count - 1) then Last 
                elif (count > 1) && (0 < position) && (position < count - 1) then Inner
                else Unknown  // This should never happen.

    // Define walk/print function
    let rec printTree (tree : BaseTree) (position) =

        // Start an s-expression
        match tree.Parent, position with
        | Root | Single | First -> printf "("
        | _                     -> ()

        // Note: Can save the result of an active pattern which is type Choice<uint,uint,uint,uint,uint,uint,uint>. 
        // The question is can the saved active pattern result be used in a match statement? 
        // If so, how? If not, need to explain it so that it logicaly makes sense. 
        // Give examples of possibly why not. i.e. Language Specification, syntactic sugar,
        // should not have allowed result to be bound, not in symbol table but other table.
        //let pos = ((|Root|Nil|Single|First|Inner|Last|Unknown|) (tree.Parent, position))  // This works / is allowed
        //    match pos with                                                                
        //    | ???  -> printf "("                                                          // Can this work? What should ??? be?
        //    | _    -> ()

        // Visit the node
        printf "%s" tree.Text    

        // Space out the values
        match tree.Parent, position with
        | Root | First | Inner -> printf " " 
        | _                    -> ()

        // Process the children
        // Note: BaseTree holds the ChildIndex, if this property was not available
        // then the use of Seq.iter whould have to be changed for a mechanism that
        // would allow the calculation of the child index as the list is processed.
        match tree.Children with
        | null -> ()
        | _    -> 
            tree.Children |> Seq.iter (fun x -> printTree (x :?> BaseTree) x.ChildIndex)
            printf " "

        // End an s-expression
        match tree.Parent, position with
        | Root | Single | Last -> printf ")" 
        | _                    -> ()

    // Call the walk/print function
    printTree tree 0

    // Since s-experssions print as single line, 
    // print a newline so that what is printed after this
    // is not on the same line as this s-expression.
    printfn ""

Solution

  • It is not particularly elegant, but you can use the underlying discriminated union that is used to represent active patterns. The result of active pattern with N options is represented using a type Choice<'T1, .., 'Tn> which has members Choice1OfN .. ChoiceNOfN.

    Here is a simpler example with just three cases:

    let (|Pos|Neg|Zero|) n = 
      if n < 0 then Neg (-n)
      elif n = 0 then Zero
      else Pos n
    
    let res = (|Pos|Neg|Zero|) 10
    
    match res with
    | Choice1Of3 n -> sprintf "pos %d" n
    | Choice2Of3 n -> sprintf "neg %d" n
    | Choice3Of3 () -> "zero"
    

    In practice, I probably wouldn't use this approach, but I'd define a custom discriminated union instead:

    type Number = Pos of int | Neg of int | Zero
    
    let convertNumber n = 
      if n < 0 then Neg (-n)
      elif n = 0 then Zero
      else Pos n
    
    let res = convertNumber 10
    
    match res with
    | Pos n -> sprintf "pos %d" n
    | Neg n -> sprintf "neg %d" n
    | Zero -> "zero"
    

    This requires explicit definition of a discriminated union, but it makes the code more readable.