Question

I'm trying to write a simple wrapper class in F# that takes a function that returns a string, and returns a function that takes the same parameters and returns the string from the input 'wrapped'.

The following code works for functions that take a single variable (so test works fine):

open System

let myFunc anotherFunc =
    fun x -> "boo" + anotherFunc x + "unboo"

let Func2 toDouble =
    (toDouble * 2).ToString ()

let test = myFunc Func2

let Func3 numOne numTwo =
    (numOne * numTwo).ToString ()

let test2 = myFunc Func3

do
    Console.WriteLine(test 10)
    Console.WriteLine(test2 5 10)

But because fun x -> specifies a single parameter, test2 is not valid code. Is there a piece of syntax that would allow for this construct?

Was it helpful?

Solution

Your function works. The problem is in your last line when you do

let test2 = myFunc Func3

should be

let test2 x = myFunc (Func3 x)

UPDATE:

I'm assuming you don't want to change Func3. Otherwise the solution from Tomas could be what you need.

OTHER TIPS

The easiest solution is to write Func3 as a function that takes a tuple. This way, the function will take just a single parameter, but you can pass it both of the numbers:

// Function takeing a single argument, which is a tuple
let Func3 (numOne, numTwo) = 
  (numOne * numTwo).ToString () 

let test2 = myFunc Func3      

// The created function takes a tuple as well
Console.WriteLine(test2(5, 10))

In general, there is no good way to write a higher-order function that takes a function accepting any number of parameters. This kind of genericity cannot be easily encoded in F#. You could use Reflection to build something like that (but that would be inefficient and unsafe), or you could write some more complex encoding of parameters, but I think that tuple is the best option.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top