Need help converting C# to F# - f#

I'd like to know how to convert this code line by line from C# to F#. I am not looking to use any kind of F#'s idioms or something of the like. I am trying to understand how to enumaration and reflcetion in F#.
using System.Linq;
namespace System.Collections.Generic
{
public static class EnumerableExtensions
{
private static readonly Random random;
static EnumerableExtensions()
{
random = new Random();
}
public static T Random<T>(this IEnumerable<T> input)
{
return input.ElementAt(random.Next(input.Count()));
}
}
}

You can define extensions as static methods in a type, but you have to mark those with the Extension attribute. A direct rewrite of your C# code would be:
open System.Runtime.CompilerServices
[<Extension>]
type EnumerableExtensions() =
static let rnd = System.Random()
[<Extension>]
static member Random(input:seq<_>) =
input |> Seq.item (rnd.Next(Seq.length input))
[1;2;3].Random()

Related

How can I hide some parameters from C DLL function on JNA Wrapper side?

I've successfully wrapped a C DLL library using JNA.
As I'm not the owner of the C development part, I would like to hide
some parameters of a C function that I've wrapped on java side.
To be more precise my java code is as follows :
public interface IJNALibrary extends Library {
// INIT FUNCTION
public int initFunction(int firstValue, int secondValue, int thirdValue);
}
On the C side I have in the *.h file :
extern "C" CSAMPLE_API int initFunction (
unsigned firstValue,
unsigned secondValue,
unsigned thirdValue);
My purpose is to directly set secondValue and thirdValue parameters to 1 and thus hide those parameters to the java API user.
I don't want the user to know that he could change the values of those parameters.
In fact I would like to have something like :
public interface IJNALibrary extends Library {
// INIT FUNCTION
public int initFunction(int firstValue);
}
and initFunction(int firstValue) calls initFunction(int firstValue, int secondValue, int thirdValue) from the C DLL part.
But this has to be done inside the java Wrapper and not from the code which calls the java Wrapper.
I'm afraid that It cannot be possible, is it?
Unless I create another C DLL (with public int initFunction(int firstValue) function) which calls the first C DLL(which embed initFunction(int firstValue, int secondValue, int thirdValue).But I would rather do it on the java side in order not to have manage 2 C DLLs.
See also below the Sample.java file which calls the mapped method defined in IJNALibrary interface.
public class Sample {
static IJNALibrary IJNAFunctions;
public static void main(String[] args) throws IOException {
System.setProperty("jna.library.path", "./librayPath");
// LOADING LIBRARY
IJNAFunctions = (IJNALibrary) Native.load("c", IJNALibrary.class);
int firstValue = 1;
int secondValue = 2;
int thirdValue = 3;
int initReturn = IJNAFunctions.initFunction(firstValue, secondValue, thirdValue);
}
}
Thanx for your help.
It depends on what you want to archive. If you want to make it easier for users to call the init, this is an option (demonstrated using gethostname from libc), which uses a Java 8 feature, which allows adding default methods to interfaces:
public class TestDefaultMethod {
public static interface LibC extends Library {
LibC INSTANCE = Native.load("c", LibC.class);
// Original binding of method
int gethostname(byte[] name, int len);
// Helper method to make it easier to call gethostname
default String gethostname() {
byte[] result = new byte[255];
LibC.INSTANCE.gethostname(result, result.length);
return Native.toString(result);
}
}
public static void main(String[] args) {
// Usage
System.out.println(LibC.INSTANCE.gethostname());
}
}
Java developers normally don't arrays to functions, which fill them and a java developer would never pass the length of the array in a separate parameter. These are artifacts of the C nature of the function. In the wrapped function an array is allocated, the native call done and the array then unwrapped. All the ugly C specialties are hidden in the default method.
If you don't want to expose the method on java at all (be warned, if your users can access the JNA library, they can circumvent your protections!), you can use a function pointer directly:
public class TestDefaultMethod {
public static interface LibC extends Library {
NativeLibrary libc = NativeLibrary.getInstance("c");
LibC INSTANCE = Native.load("c", LibC.class);
default String gethostname() {
byte[] result = new byte[255];
libc.getFunction("gethostname").invokeInt(new Object[] {result, result.length});
return Native.toString(result);
}
}
public static void main(String[] args) {
System.out.println(LibC.INSTANCE.gethostname());
}
}
Same idea as above, the default method will hide the ugly parts. In this case though the function is not accessed through the managed INSTANCE, but access through the function pointer directly.

why do we need Callable classes in dart

What is the use of callable classes in dart lang? Following is the example code available on official dart site.
class WannabeFunction {
call(String a, String b, String c) => '$a $b $c!';
}
main() {
var wf = new WannabeFunction();
var out = wf("Hi","there,","gang");
print('$out');
}
How useful is it add a call function and call it using a class instead of creating a function itself in class
This can be useful to make "named functions":
class _Foo {
const _Foo();
void call(int bar) {}
void named() {}
}
const foo = _Foo();
Which allows both:
foo(42);
and
foo.named();

Why does F# compiler prefer to generate closed implementations of FSharpFunc types?

For this code:
module Module =
let func x y z = 0
[<EntryPoint>]
let main args =
func 1
func 1 1
0
Decompilation yields:
[CompilationMapping(SourceConstructFlags.Module)]
public static class Main
{
[CompilationMapping(SourceConstructFlags.Module)]
public static class Module
{
[Serializable]
internal sealed class main#30 : OptimizedClosures.FSharpFunc<object, object, int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[CompilerGenerated]
[DebuggerNonUserCode]
public int x;
[CompilerGenerated]
[DebuggerNonUserCode]
internal main#30(int x)
{
this.x = x;
}
public override int Invoke(object y, object z)
{
return func(x, y, z);
}
}
[Serializable]
internal sealed class main#31-1 : FSharpFunc<object, int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[CompilerGenerated]
[DebuggerNonUserCode]
public int x;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[CompilerGenerated]
[DebuggerNonUserCode]
public int y;
[CompilerGenerated]
[DebuggerNonUserCode]
internal main#31-1(int x, int y)
{
this.x = x;
this.y = y;
}
public override int Invoke(object z)
{
return func(x, y, z);
}
}
[CompilationArgumentCounts(new int[]
{
1,
1,
1
})]
public static int func<a, b, c>(a x, b y, c z)
{
return 0;
}
[EntryPoint]
public static int main(string[] args)
{
int x = 1;
new main#30(x);
int x2 = 1;
int y = 1;
new main#31-1(x2, y);
return 0;
}
}
public static a Dump<a>(a arg00)
{
return arg00.Dump();
}
}
It generates a concrete type, that is generic parameters are provided at type definition. Why is not this done at the point of construction? I also noticed that types are generated in the module where call occurs, not where func is defined.
Having let func x y z = ... we need implementations of types to cover all possibilities:
FSharpFunc<T1,FSharpFunc<T2,T3,TReturn>>
FSharpFunc<T1,T2,FSharpFunc<T3,TReturn>>
FSharpFunc<T1,FSharpFunc<T2,FsharpFunc<T3,TReturn>>>
Compiler could generate all possible combinations in the same place, where function is defined, closing only for parameters with inferenced types.
You could argue that for the list of 7 args the set of types going to be quite large, but types like FSharpFunc<T1,T2,..,Tn, FSharpFunc<...>> are a mere optimazation. And FSharpFunc supports up to six generic types, then compiler has to switch to FSharpFun<T1,T2,T3,T4,T5,FSharp<...>>.
As pointed out by Fyodor it's not function creation that makes the compiler generating the hidden classes. The hidden classes are used to implement partial application.
In F# a partial application and lambdas are implemented as a compiler generated class that extends an abstract class. C# lambdas rely on delegates instead. IIRC Java and Scala use a similar technique to F# as JVM doesn't have delegates.
I suspect the F# compiler generates a class per partial application because it's simpler than collecting all partial applications and coalesce the identical ones.
It also helps the debuggability of F# programs as the name hints where the partial application was done: main#31-1 => In the main function at row 31. This name if included in logs or performance runs can help identifying what partial application is causing problems.
This comes at the cost of increasing the size of the F# assembly file as noted in a comment by Pavel.

jna: pass a string from C# to Java

I am using Unamanged dependencies (RGiesecke.DllExport.DllExport) and jna in a small C# function that should return a string consumed within another now java function.
Following the jna suggestions for mapping i crafted the code below:
My C# code:
[RGiesecke.DllExport.DllExport]
public static unsafe char* Test(string id)
{
unsafe
{
fixed (char *s = "test passed")
{
return s;
}
}
}
Java side:
public interface ITest extends Library{
public String Test(String id);
}
public static void main(String[] args) {
ITest nativeExample= (ITest)Native.loadLibrary("C:/native/JavaLib.dll", ITest.class);
String s = nativeExample.Test("id");
System.out.println(s);
}
So, all that is printed, is 't', because I bet all is being transmitted is the address to s[0].
Has anyone had luck mapping strings from C# to java through jna?
Plain strings in the C# code throws errors.
Have you tried returning a string instead of char? or changing char *s to char s[]

Can the free_function be a static class method?

This is a follow-up question to How to write void pointer typedefs in vapi files?
I now have four almost identical [Compact] classes that represent handles allocated with unixODBCs SQLAllocHandle function.
The first one (for the ENV type handle) looks like this:
[CCode (cname = "void", free_function = "EnvironmentHandle.free")]
[Compact]
public class EnvironmentHandle {
[CCode (cname = "SQLAllocHandle")]
private static Return allocate_internal (HandleType type, void* nothing, out EnvironmentHandle output_handle);
public static Return allocate (out EnvironmentHandle output_handle) {
return allocate_internal (HandleType.ENV, null, out output_handle);
}
[CCode (cname = "SQLFreeHandle")]
private static Return free_internal (HandleType type, EnvironmentHandle handle);
public static Return free (EnvironmentHandle handle) {
return free_internal (HandleType.ENV, handle);
}
}
This doesn't compile.
Is it possible to use a static class method as the free_function?
If not, is there at least a way to write a custom free_function in the vapi file?
I need a custom function because the SQLFreeHandle function takes the handle type and the handle as an argument.
From the vapi users perspective all that is really important is:
[CCode (cname = "void")]
[Compact]
public class EnvironmentHandle {
public static Return allocate (out EnvironmentHandle output_handle);
}
The only other solution would be to use a [SimpleType] struct as suggested by apmasell in the original question. That would hide the fact that a SQLHANLDE is really a reference type.
The full code of my current implementation is available online:
https://github.com/antiochus/unixodbc-vala/tree/0486f54dc3f86d9c8bf31071980e4f171aca9591
No. The free_function is a C function, not a Vala function and it cannot take any context. You have two options:
Write a C macro in an extra header file to do what you want and bind the macro as the free function.
Bind the free function as a static method that takes an owned instance of the object:
[CCode (cname = "SQLFreeHandle")]
public static Return free(HandleType type, owned EnvironmentHandle handle);
EnvrionmentHandle foo = ...;
EnvironmentHandle.free(HandleType.ENV, (owned) foo);

Resources