简体   繁体   中英

f# function that returns a generic function

I would like to do the following :

module private repo =
    let SaveEvts<'T> (conn:IConnection) mydata =  
        async {
            let! result = conn.SaveAsync(mydata)
        }

let SaveAsync (conn:IConnection) = repo.SaveEvts conn

so that I could open a single connection to my db and then have in closure my connection whenever I want to save some type T data. eg :

type Foo = { idPhoto : Guid }
type Bar = { reason : string }

let myConnection = new Connection(connectionString)
let save = SaveAsync myConnection
let doProgram =
    save<Foo>({idPhoto = 212313})
    save<Bar>({idPhoto = 212313})

This is fantasy writing, I do not know if it compiles: My issues here are

  1. Is there a way to do what I want to achieve , ie a normal function that returns a generic function.
  2. if it is doable, is it advisable?

I would like to avoid writing :

let saveFoo = SaveEvts<Foo> (conn:IConnection) 
let saveBar = SaveEvts<Bar> (conn:IConnection) 

but maybe there is no other way...

You cannot write a function that returns a generic function in F#. There are two ways to solve this:

  • You can write a function that returns a simple object with a generic method and then use this object to do all the work
  • You can define a new generic function that captures an existing connection

So, the code in your second snippet would not work, but you can do:

let myConnection = new Connection(connectionString)
let save arg = SaveAsync myConnection arg

save {FooProperty = 212313}
save {BarProperty = 212313}

Here, save is defined as a function and so it can be generic, but it can still capture the existing opened connection myConnection and use it for all the different arguments that you give it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM