Call a higher order F# function from C# - c#

Given the F# higher order function (taking a function in parameter):
let ApplyOn2 (f:int->int) = f(2)
and the C# function
public static int Increment(int a) { return a++; }
How do I call ApplyOn2 with Increment as parameter (from C#)?
Note that ApplyOn2 is exported as Microsoft.FSharp.Core.FSharpFunc<int,int> which do not match with Increment's signature.

To get an FSharpFunc from the equivalent C# function use:
Func<int,int> cs_func = (i) => ++i;
var fsharp_func = Microsoft.FSharp.Core.FSharpFunc<int,int>.FromConverter(
new Converter<int,int>(cs_func));
To get a C# function from the equivalent FSharpFunc, use
var cs_func = Microsoft.FSharp.Core.FSharpFunc<int,int>.ToConverter(fsharp_func);
int i = cs_func(2);
So, this particular case, your code might look like:
Func<int, int> cs_func = (int i) => ++i;
int result = ApplyOn22(Microsoft.FSharp.Core.FSharpFunc<int, int>.FromConverter(
new Converter<int, int>(cs_func)));

If you would like to provide a more friendly interop experience, consider using the System.Func delegate type directly in F#:
let ApplyOn2 (f : System.Func<int, int>) = f.Invoke(2)
You would be able to call your F# function very easily in C# like this:
MyFSharpModule.ApplyOn2(Increment); // 3
There is an issue with the Increment function as you have written it, however. You need the prefix form of the increment operator in order for your function to return the correct result:
public static int Increment(int a) { return ++a; }

Just create reference to your assembly:
#r #"Path\To\Your\Library.dll"
let ApplyOn2 (f:int->int) = f(2)
ApplyOn2 Library.Class.Increment

Related

What is the use of lambda in the last function here?

I'm trying to understand Lambda expressions;
I've got a basic function Sq1 which is squaring the number i
I can rewrite this with a lambda to oneline it, Sq2
I can also write it like Sq4 with a Func<>, but I'm not sure why I'd want to
and furthermore, with Sq3 I was trying to write the long-hand version of Sq4 because writing Sq1 helped me understand what Sq2 was actually doing
public int Sq1(int i)
{
return i * i;
}
public int Sq2(int i) => i * i;
public Func<int, int> Sq3(int i)
{
// Not sure what goes here, I don't want to return a function?
}
public Func<int, int> Sq4 = x => x * x;
Can anybody help me understand why I'd write the function as per Sq4 and what this is actually shorthand for?
Sq1 and Sq2 are identical functions, not lambdas. Sq2 uses the expression body syntax that allows simplifying simple methods. Sq2 is essentially:
public int Sq2(int i) {
return i * i;
}
You can use Sharplab.io to see the generated code in both cases. You'll see that the body of both methods is the same
You can't make the Sq3 function behave like Sq4, because Sq4 on the other hand is a Func-typed field that holds the x => x * x delegate. Sq3 on the other hand is a function that returns a Func, a common idiom in functional programming.
You can use Sq4 as if it were a function, eg :
var result=Sq4(2);
As for Sq3, what you do depends on what you want to do. If you only want to execute the function, use the same syntax as Sq1 or Sq2. If you really want to return a Func<> you could use something like this :
public Func<int,int> Sq3F()
{
return (int i)=>i*i;
}
And use it like this:
var fun=Sq3F();
var result=fun(4);
Why a Func<>?
That doesn't look like much until you realize you can pass functions as parameters and construct complex transformations dynamically, eg :
public Func<int,double> LogF(Func<int,int> fun)
{
return (int i)=>Math.Log(fun(i));
}
...
var func=LogF(Sq3F());
var result=func(4);
Another common technique is partial application - take a function with multiple arguments and produce another one where some of the arguments are fixed. Let's say you want to create a single-argument Log method that works for a specific base, which means you can't just use `Math.Log(double,double). You could do this :
public Func<double,double> LogN(double N)
{
return (double d)=>Math.Log(d,N);
}
...
var log5F=LogN(5);
var result=log5F(5);
You would use the lambda expression for the sake of simplicity, to avoid having to write a full function for a simple operation.
And it would translate to the following normal function:
public int Sq4(int x):
{
return x * x;
}
Also you have used an arrow function that is different of a lambda.
An arrow function is a way to simplify the body of a function but it has the same structure
(string param1, int param2) => {
// To do here
}

How to use F# to process lists from C#

I'm trying to figure out how to use an F# library from a C# assembly, I have used C# quite a bit, but have never used F#.
Here is the F# Class..
namespace FLib
type Class1() =
member this.square(x)=x*x
member this.doit(x, op) = List.map op (Seq.toList(x))|>List.toSeq
member this.squareAllDirect(x) = List.map this.square (Seq.toList(x))|>List.toSeq
member this.squareAllIndirect(x) = this.doit x, this.square
Here is the C# using it
class Program
{
static void Main(string[] args)
{
FLib.Class1 f = new FLib.Class1();
List<int> l=new List<int>(){1,2,3,4,5};
var q =f.squareAllDirect(l);
var r = f.squareIndirect(l);
foreach (int i in r)
Console.Write("{0},",i);
Console.ReadKey();
}
}
The squareAllDirect function works as expected... but the squareAllIndirect call from c# has an exception:
The Type argument for method 'FLib.Class1.squareAllIndirect (System.Tuple,Microsoft.FSharp.Core.FSharpFunc'2>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
It looks you are expecting your squareAllIndirect function to take and returns a int seq
However if you mouse over it you will see it takes and returns a int seq * (int -> int)
Tuple is lower precedence than function call so x is passed as both arguments to doit.
You need to surround the parameters of your function call in ().
member this.squareAllIndirect(x) = this.doit(x, this.square)
That will ensure you take and return what you expect.

how to execute a method based on a string which contains its name

I have an Object which contains several methods and outside of it I have a list of strings where each of the strings value is the name of the Method. I would like to Execute the the method based on the name. From expirience, in python it is deadly simple. In c# I assume that it should be done with delegates I suposse. Or with methodInvoking?
I wanted to ignore reflection on this one.
i python you can store methods as objects, because it is an object.
def a():
return 1
def b():
return 2
def c():
return 3
l= [a,b,c]
for i in l:
print i()
The output would be:
>>> 1
>>> 2
>>> 3
If you want to ignore reflection, you can create a delegate for each method call and store in a Dictionary.
Heres how you do it:
var methods = new Dictionary<string, Action >() {
{"Foo", () => Foo()},
{"Moo", () => Moo()},
{"Boo", () => Boo()}
};
methods["Foo"].Invoke();
Note that in your Python example, you are not "[executing] a method based on a string which contains its name" but rather adding the method to a collection.
You can do basically the same thing as you are doing in Python in C#. Take a look at the Func delegate.
class FuncExample
{
static void Main(string[] args)
{
var funcs = new List<Func<int>> { a, b, c };
foreach (var f in funcs)
{
Console.WriteLine(f());
}
}
private static int a()
{
return 1;
}
private static int b()
{
return 2;
}
private static int c()
{
return 3;
}
}
and the output is
1
2
3
If you need to execute a function based on its name as a string, Uri-Abramson's answer to this very question is a good place to start, though you may want to reconsider not using reflection.

Closures and java anonymous inner classes

Would anyone be so kind to post the equivalent Java code for a closure like this one (obtained using C#) with anonymous inner classes?
public static Func<int, int> IncrementByN()
{
int n = 0; // n is local to the method
Func<int, int> increment = delegate(int x)
{
n++;
return x + n;
};
return increment;
}
static void Main(string[] args)
{
var v = IncrementByN();
Console.WriteLine(v(5)); // output 6
Console.WriteLine(v(6)); // output 8
}
Furthermore, can anyone explain how partial applications can be obtained if lexical closures are available and viceversa? For this second question, C# would be appreciated but it's your choice.
Thanks so much.
There is no closure yet in Java. Lambda expressions are coming in java 8. However, the only issue with what you're trying to translate is that it has state, which not something that lamba expressions will support i don't think. Keep in mind, it's really just a shorthand so that you can easily implement single method interfaces. You can however still simulate this I believe:
final AtomicInteger n = new AtomicInteger(0);
IncrementByN v = (int x) -> x + n.incrementAndGet();
System.out.println(v.increment(5));
System.out.println(v.increment(6));
I have not tested this code though, it's just meant as an example of what might possibly work in java 8.
Think of the collections api. Let's say they have this interface:
public interface CollectionMapper<S,T> {
public T map(S source);
}
And a method on java.util.Collection:
public interface Collection<K> {
public <T> Collection<T> map(CollectionMapper<K,T> mapper);
}
Now, let's see that without closures:
Collection<Long> mapped = coll.map(new CollectionMapper<Foo,Long>() {
public Long map(Foo foo) {
return foo.getLong();
}
}
Why not just write this:
Collection<Long> mapped = ...;
for (Foo foo : coll) {
mapped.add(foo.getLong());
}
Much more concise right?
Now introduce lambdas:
Collection<Long> mapped = coll.map( (Foo foo) -> foo.getLong() );
See how much nicer the syntax is? And you can chain it too (we'll assume there's an interface to do filtering which which returns boolean values to determine whether to filter out a value or not):
Collection<Long> mappedAndFiltered =
coll.map( (Foo foo) -> foo.getLong() )
.filter( (Long val) -> val.longValue() < 1000L );
This code is equivalent I believe (at least it produces the desired output):
public class Test {
static interface IncrementByN {
int increment(int x);
}
public static void main(String[] args) throws InterruptedException {
IncrementByN v = new IncrementByN() { //anonymous class
int n = 0;
#Override
public int increment(int x) {
n++;
return x + n;
}
};
System.out.println(v.increment(5)); // output 6
System.out.println(v.increment(6)); // output 8
}
}
Assuming we have a generic function interface:
public interface Func<A, B> {
B call A();
}
Then we can write it like this:
public class IncrementByN {
public static Func<Integer, Integer> IncrementByN()
{
final int n_outer = 0; // n is local to the method
Func<Integer, Integer> increment = new Func<Integer, Integer>() {
int n = n_outer; // capture it into a non-final instance variable
// we can really just write int n = 0; here
public Integer call(Integer x) {
n++;
return x + n;
}
};
return increment;
}
public static void main(String[] args) {
Func<Integer, Integer> v = IncrementByN();
System.out.println(v.call(5)); // output 6
System.out.println(v.call(6)); // output 8
}
}
Some notes:
In your program, you capture the variable n by reference from the enclosing scope, and can modify that variable from the closure. In Java, you can only capture final variables (thus capture is only by value).
What I did here is capture the final variable from the outside, and then assign it into a non-final instance variable inside the anonymous class. This allows "passing info" into the closure and at the same time having it be assignable inside the closure. However, this information flow only works "one way" -- changes to n inside the closure is not reflected in the enclosing scope. This is appropriate for this example because that local variable in the method is not used again after being captured by the closure.
If, instead, you want to be able to pass information "both ways", i.e. have the closure also be able to change things in the enclosing scope, and vice versa, you will need to instead capture a mutable data structure, like an array, and then make changes to elements inside that. That is uglier, and is rarer to need to do.

Generic Factorial function in C#

I want to write a generic function to calculate factorial in C# ... like:
static T Factorial<T>(T n)
{
if (n <= 1)
return 1;
return Factorial<T>(n - 1);
}
but obviously having restriction that we can't perform operations on type 'T'. any alternative?
The problem is that generics don't support operators because they are static methods, and not part of an interface. However, you could probably use Generic Operators, which is available in the Miscellaneous Utility Library.
You would need to add a delegate parameter which performs the multiplication. Something like this
delegate T Multiply<T>(T a, T b);
So then your function would be defined like this:
static T Factorial<T>(T n, Multiply func)
{
... your code here
}
So when your factorial function is called, the caller would pass in the multiplication function:
int x = Factorial<int>(5, (a,b) => a * b);
There is no easy way to do this. I have seen some solutions that work around the problem, but they are fairly complicated. That said, if you really want to do this here are a few ideas:
If you can use .Net 4, you can cast n to dynamic and then perform the addition. You lose safety, of course - you could get an exception at runtime
You could always manually check the type from within your factorial function: If n is a short, cast to short, if n is a double, cast to double... etc. That is complicated and defeats part of the value of generics, but the outside API at least looks simple.
When's the last time you took the factorial of a string, or a character?
Why do you ever need a factorial of type T????
Besides this has been said numerous (prolly 1 million times now).
When you need to use a generic you need to tell the compiler the type.
For instance what if I had a generic stack class?
C# needs to know the elements type when I create my stack.
Otherwise it makes no sense for:
Stack<T> s = new Stack<T>();
s.Push(????); //how do I add items to the stack if we don't know what T is?
Instead you need to specify:
Stack<int> s = new Stack<int>();
s.Push(5);
s.Push(7);
This isn't specifically addressing your question about making the method generic, but your method as it stands will never return anything other than 1.
Supposing you were only working with integers, it should look like this:
static int Factorial(int n)
{
if (n <= 1)
return 1;
// note the multiplication in this step
return n * Factorial(n - 1);
}
public T Factorial<T>(T a, T b, Multiply<T> delegateMutliply, Difference<T> diffDelegate, BaseCondition<T> baseDelegate)
{
if (!baseDelegate(a, b))
return b;
return delegateMutliply(a, Factorial<T>(diffDelegate(a), b, delegateMutliply, diffDelegate, baseDelegate));
}
int y = p.Factorial(3, 1, (a, b) => a * b, (a) => --a, (a, b) => (a <= b) ? false : true);
Super old question but I'd like to add my 2 cents.
Factorial functions require f* = i
A quick function for the example above is:
class FindFactorial
{
static void Main()
{
Console.WriteLine("Please enter your number: ");
int n = int.Parse(Console.ReadLine());
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine(factorial);
}
}

Categories