Skip to content

Instantly share code, notes, and snippets.

@battermann
Last active August 29, 2015 14:22
Show Gist options
  • Save battermann/59af51dad9d798d7c9d8 to your computer and use it in GitHub Desktop.
Save battermann/59af51dad9d798d7c9d8 to your computer and use it in GitHub Desktop.
How to pass an argument to a F# function that takes ('a -> unit) from C#
using System;
using Microsoft.FSharp.Core;
namespace FSharpConverter
{
public static class ToFSharpFuncConverterExtensions
{
private static readonly Unit Unit = (Unit)Activator.CreateInstance(typeof(Unit), true);
public static Func<T, Unit> ToFunc<T>(this Action<T> action)
{
return x => { action(x); return Unit; };
}
public static FSharpFunc<T, Unit> ToFSharpFunc<T>(this Action<T> action)
{
return FSharpFunc<T, Unit>.FromConverter(new Converter<T, Unit>(action.ToFunc()));
}
}
}
Action<string> logger = Console.WriteLine;
var fsharpLogger = logger.ToFSharpFunc();
MyModule.doSomething(fsharpLogger);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment