简体   繁体   中英

How can I encapsulate the idea of 'all parameters' in F#?

In F#, I need to do something like this:

let price k s t r v =
  let d1 = d1 k s t r v
... and so on

I'm getting really tired of listing all the parameters when they are passed into a function. Apart from turning the parameters into a parameter object (something I cannot do), is there any way to group the parameters? I'm thinking of something like

let price (k s t r v as foo) =
  let d1 = d1 foo

Any ideas? Thanks.

You can effectively batch together your arguments (call them w, x, y, z ) via a higher-order function like so

let batchedArgs f = f w x y z

Now batchedArgs is a closure over the original function arguments. You just pass it another function which takes the same number/type of arguments, and they will be applied.

// other functions which you wish to pass the args to
let sub1 w x y z = 42
let sub2 w x y z = true

// main routine
let doStuff w x y z =
    // one-time declaration of batching function is
    // the only time you need to list out the arguments
    let batchedArgs f = f w x y z

    // from then on, invoke like this
    batchedArgs sub1
    // or like this, which looks more like a traditional function call
    sub2 |> batchedArgs 

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