F# Define function to act as delegate to .net Action
Asked Answered
S

1

12

in System.Activities.WorkflowApplication there is a delegate property:

        public Action<WorkflowApplicationCompletedEventArgs> Completed { get; set; }

In my program so far, I have a variable that is an instance of this class

I want to define an F# function to set that:

let f (e: WorkflowApplicationCompletedEventArgs) = 
    // body
myInst.Completed <- f

but this produces the error:

Error 102 This expression was expected to have type Action but here has type 'a -> unit

how do I complete function "f" to satisfy the compiler?

Sidoney answered 16/3, 2017 at 18:23 Comment(2)
let f = System.Action<WorkflowApplicationCompletedEventArgs>(fun e -> (*body to unit*))Catechu
Works like a charm!!Sidoney
P
18

If you pass an anonymous function fun a -> ... to a method or a constructor that expects a System.Action<...> or a System.Func<...>, then it is automatically converted; in any other case, you need to convert it explicitly like @Funk indicated.

let f = System.Action<WorkflowApplicationCompletedEventArgs>(fun e ->
    // body
)
myInst.Completed <- f

// Another solution:

let f (e: WorkflowApplicationCompletedEventArgs) = 
    // body
myInst.Completed <- System.Action<_>(f)
Pokeberry answered 17/3, 2017 at 1:48 Comment(2)
that last one is a new form to me. What does the underscore represent here?Sidoney
It lets the type inference system guess the type. Based on the type of f, it can deduce what type the Action's parameter is. I could just as well have written Action<WorkflowApplicationCompletedEventArgs>, but this is shorter and just as clear.Pokeberry

© 2022 - 2024 — McMap. All rights reserved.