I have been working on allowing function chaining. I have created a class called continuationmonad which takes a value, and a function from a => b. This allows me to use fmap and bind to chain these together. I have also used lazy to allowed calls to be defered where possible.
Is this class really the continuation monad or is it something else. I am finding it hard to find good literature which is not is Haskell.
Also any comments on how to improve / correct this.
using NUnit.Framework;
using System;
namespace Monads
{
public class Continuation<Input, Output>{
public Continuation(Input value, Func<Input,Output> function){
this.value = new Lazy<Input>( () => value);
this.function = function;
}
public Continuation(Lazy<Input> value, Func<Input,Output> function){
this.value = value;
this.function = function;
}
public Continuation<Output, Result> FMap<Result>(Func<Output, Result> map){
return new Continuation<Output, Result>(new Lazy<Output>( () => Run() ), x => map(x));
}
public Continuation<Output,Result> Bind<Result>(Func<Output, Continuation<Output, Result>> f){
return f(Run());
}
public Output Run(){
return function(value.Value);
}
private Func<Input, Output> function;
private Lazy<Input> value;
}
public static class ContinuationExtension{
public static Continuation<A,B> Unit<A,B>(this Func<A,B> f, A value){
return new Continuation<A, B>(value,f);
}
public static Continuation<A,B> Unit<A,B>(this A value,Func<A,B> f){
return new Continuation<A, B>(value,f);
}
}
[TestFixture]
public class MonadTests
{
public Continuation<int,int> Wrapped(int value){
return new Continuation<int,int>(value, x => x * 10);
}
[Test]
public void ContinuationMonadTests()
{
var number = 42;
var result = number.Unit(x => x + 8).FMap(x => x * 2).Bind(Wrapped).Run();
Console.WriteLine(result);
}
}
}
This is not the continuation monad. You are much closer to the Haskell Monad instance for functions.
You aren't getting anything that you couldn't get just from using Lazy<>. Since you have provided the input when you build an instance of your class, you aren't building functions, you are building values that are determined by a computation that hasn't been evaluated yet. Lazy<> delays the evaluation of computation until the value is needed.
Let's put together something like the Haskell Monad instance for functions in c#. LINQ syntax has established the convention for Monads in c#. They should have:
a Select extension method analogous to a Haskell Functor's fmap
a SelectMany extension method analogous to Haskell's Monad's >>=
an additional SelectMany that LINQ syntax uses. This takes an additional function that combines the value from two steps together.
Unfortunately, there's no convention for what the analog of a Monad's return should be called; we'll call ours Constant. Unfortunately, Constant won't be very convenient because c#'s type inference won't be able to figure out the types.
public static class Function
{
public static Func<TIn, TOut> Constant<TIn, TOut>(TOut result)
{
return x => result;
}
public static Func<TIn, TOut> Select<TIn, TMid, TOut>(
this Func<TIn, TMid> func,
Func<TMid, TOut> proj)
{
return x => proj(func(x));
}
public static Func<TIn, TOut> SelectMany<TIn, TMid, TOut>(
this Func<TIn, TMid> func,
Func<TMid, Func<TIn, TOut>> proj)
{
return x => proj(func(x))(x);
}
public static Func<TIn, TOut> SelectMany<TIn, TMid1, TMid2, TOut>(
this Func<TIn, TMid1> func,
Func<TMid1, Func<TIn, TMid2>> proj1,
Func<TMid1, TMid2, TOut> proj2)
{
return x => {
var mid1 = func(x);
var mid2 = proj1(mid1)(x);
return proj2(mid1, mid2);
};
}
}
Note that defining these extension methods only lets you interact with something like it's a Monad, it doesn't let you write code that's generic over the specific Monad being used. There's a sketch of how to do that in the second half of this answer.
This might be a bit opinion based but I'll try to give you my 5ct anyway.
Let's have a look at your class and their instances:
It includes a value and a function where you (tried) to make it all a lazy.
From a theoretical view I can see no difference to Lazy<T> on first glance:
You can surely convert one of your Continuation<Input,Output> to just a Lazy<Output>.
The same is true for the reverse: given some lazy value a you can make a instance with just
new Continuation(a, x => x)
So to me it seems that you just reinvented Lazy (which is an monad, in Haskell you would call it Identity.
The Cont monad is not really easy to crasp but it's really more related to .net-Events or .net-Observables. The datastructure itself would be like
Func<Func<Input,Output>, Output>
Where you pass in a continuation Func<Input,Output> to some internal calculation and then the struture than will call it when it has calculated an input Input to get the final result.
This might be a bit cryptic but one .net application are the Async workflows F# uses and which stood model for C#s async/await behaviour in some sense.
I have some material I used for a talk on a simpified version of this monad in C# on github maybe you'll find it interesting.
I have created a very comprehensive introduction to the Continuation monad that you can Find Here Discovering the Continuation Monad in C#
Also you can find a.Net Fiddle here
I Repeat it in summary here
Starting from an initial Function
int Square(int x ){return (x * x);}
Use Callback and remove return type
public static void Square(int x, Action<int> callback)
{
callback(x * x);
}
Curry the Callback
public static Action<Action<int>> Square(int x)
{
return (callback) => { callback(x * x); };
}
Generalize the returned Continuation
public static Func<Func<int,T>,T> Square<T>(int x)
{
return (callback) => { callback(x * x); };
}
Extract the Continuation Structure Also Known As the Return Method of the monad. That is Give me a value and i will give you a Monad for this value
//((U→ T) → T)
delegate T Cont<U, T>(Func<U, T> f);
public static Cont<U, T> ToContinuation<U, T>(this U x)
{
return (callback) => callback(x);
}
square.ToContinuation<Func<int, int>, int>()
Add The bind Monadic method and thus Complete the Monad.That is Give me a Two Monads and i will combine them to a new monad
((A→ T) → T)→( A→((B→ T) → T))→ ((B→ T) → T)
public static Cont<V, Answer> Bind<T, U, V, Answer>(
this Cont<T, Answer> m,
Func<T, Cont<U, Answer>> k,
Func<T, U, V> selector)
{
return (Func<V, Answer> c) =>
m(t => k(t)(y => c(selector(t, y))));
}
Related
I have a class with a member Predicate which I would like to use in a Linq expression:
using System.Linq;
class MyClass
{
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(m_filterExpression);
}
private IEnumerable<Instrument> m_instrumentList;
private Predicate<Instrument> m_filterExpression;
}
As I read that "Predicate<T> is [...] completely equivalent to Func<T, bool>" (see here), I would expect this to work, since All takes in as argument: Func<Instrument, bool> predicate.
However, I get the error:
Argument 2: cannot convert from 'System.Predicate<MyNamespace.Instrument>' to 'System.Type'
Is there a way to convert the predicate to an argument that this function will swallow?
The two types represent the same logical signature, but that doesn't mean they're just interchangable. A straight assignment won't work, for example - but you can create a new Func<T, bool> from the Predicate<T, bool>. Sample code:
Predicate<string> pred = x => x.Length > 10;
// Func<string, bool> func = pred; // Error
Func<string, bool> func = new Func<string, bool>(pred); // Okay
This is a bit like having two enum types with the same values - you can convert between them, but you have to do so explicitly. They're still separate types.
In your case, this means you could write:
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(new Func<T, bool>(m_filterExpression));
}
The lambda expression approach suggested by other answers will work too, of course.
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(i => m_filterExpression(i));
}
You can convert a predicate to a method by calling Invoke. All delegates have this member. Delegates don't have structural identity, but methods can be converted to matching delegates. This fix has a minor performance cost, as it adds an extra layer of indirection. However, most solutions to this problem have that problem. Eric Lippert discusses this in more detail at https://web.archive.org/web/20140625132124/http://blog.coverity.com/2014/06/18/delegates-structural-identity/ .
In your specific case, replace return m_instrumentList.All(m_filterExpression); with return m_instrumentList.All(m_filterExpression.Invoke);
Sample code demonstrating the actual problem.
void Main()
{
Predicate<int> t1 = Foo;
Func<int,bool> t2 = Foo;
Predicate<int> t3 = t2.Invoke; //Legal
Func<int,bool> t4 = t1.Invoke; //Legal
Predicate<int> t5 = t2; //Illegal
Func<int,bool> t6 = t1; //Illegal
}
bool Foo(int x)
{
return x > 20;
}
return m_instrumentList.All(i => m_filterExpression(i));
Since there are a lot of answers i will add one more just for fun.
If you want your code to compile you can use extention methods
//Original Code
class MyClass4
{
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(m_filterExpression);
}
private IEnumerable<Instrument> m_instrumentList;
private Predicate<Instrument> m_filterExpression;
}
Add this class in the same namespace
public static class MyExtentions
{
public static bool All(this IEnumerable<Instrument> enumer, Predicate<Instrument> pred)
{
return enumer.All(e => pred(e));
}
}
As Brian said, you can convert a predicate to a method via Invoke:
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(m_filterExpression.Invoke);
}
I have a method in which I send two arguments of the same type and I need to fold them. For example, if these are numbers, then return only the sum, and if the lines are the concatenation of these lines. How can I do it? And if I pass a type that cannot be folded, then I need to throw an exception.
public class Calcul<T>
{
public static T Add(T c1, T c2)
{
}
}
Servy said in a comment:
Don't make the method generic if it's not actually generic, and don't say the method can accept any type if it can't in fact accept any type. As you've already been told, if you want to handle a finite number of specific types, have overloads for each of those types.
to which you replied:
Alas, I showed the teacher, but he said that it was not that. He said that it should be something like an abstract calculator where for each type T you can define the operation N
You can have your method with that signature and no if blocks at all, but the Add method can't be static. You have to pass in a Func<T1, T2, TResult> where T1, T2, and TResult are the same (T):
public class Calculator<T>
{
private readonly Func<T, T, T> _func;
public Calculator(Func<T, T, T> func)
{
_func = func;
}
public T Add(T a, T b)
{
return _func(a, b);
}
}
You'd use it like this:
Func<int, int, int> intAddition = (a, b) => a + b;
var intCalculator = new Calculator<int>(intAddition);
Console.WriteLine(intCalculator.Add(1, 2)); // writes 3
Func<string, string, string> stringAddition = (a, b) => a + b;
var stringCalculator = new Calculator<string>(stringAddition);
Console.WriteLine(stringCalculator.Add("Hello ", "world")); // writes "Hello world"
Online example: https://dotnetfiddle.net/8NOBsv
This way you get to specify the logic of the Add method, and you don't have loads of overloaded methods (or awful type-checking logic inside the method like if ( typeof(T) == typeof(string) ), etc.
You can typeof(T) to get the type information always. Using that, you can use conditional statements to work your way through the logic
Example:
var type = typeof(T);
if (type == int)
{ do something ;}
Generics are used for cases like : 2 different types following the same operations but taking different input types and output types. The underlying usage is that they have the same processes. If you are using type specific processes much, then its better to overload your functions to suit your need.
Reading more into your use case:
Try overloading methods.
private static int doSomething(int n1, int n2)
{
return (n1) + (n2);
}
private static float doSomething(float n1, float n2)
{
return (n1) - (n2);
}
Here's a generic way that works as long as T supports the + operator. However, it uses runtime checking. As far as I can tell there is no way to use type constraints to check this at compile time.
Adapted from: https://stackoverflow.com/a/5997156/6713871
public class Calcul<T>
{
public static T Add(T c1, T c2)
{
return (dynamic)c1 + (dynamic)c2;
}
}
As others have said you should probably use overloads. However it's possible to do something like this
static class Calc<T>
{
public static T Add(T a, T b)
{
if (typeof(T) == typeof(int))
{
return (T)(object)((int)(object)a + (int)(object)b);
}
if (typeof(T) == typeof(uint))
{
return (T)(object)((uint)(object)a + (uint)(object)b);
}
throw new ArgumentOutOfRangeException($"Type {typeof(T).Name} is not supported.");
}
}
And call it with:
Calc<int>.Add(1 , 2); // returns 3
Calc<double>.Add(2d, 3d).Dump(); // throws exception
Are there built in methods for converting between the various types of Func delegates? That is, suppose you need a Func, but you have a Func (and you have the value that should be passed in for the T parameter). For example:
static TREsult Foo<TResult>(Func<TResult> f)
{
// ...
TResult result = f();
// ...
return result;
}
static int MyFunc(int i)
{
return i;
}
void CallFoo()
{
Func<int> func = ConvertFunc(MyFunc, 1); // Does this family of methods exist?
int j = Foo(func);
}
I've written my own, like this:
static Func<TResult> ConvertFunc<T, TResult>(Func<T, TResult> f1, T t)
{
return () => f1(t);
}
static Func<TResult> ConvertFunc<T1, T2, TResult>(Func<T1, T2, TResult> f2, T1 t1, T2 t2)
{
return () => f2(t1, t2);
}
// etc.
But I'm wondering if a family of methods like this exists (or even if there's a better way to do this).
Essentially, I'm doing this for a case where there is some boiler plate code in a method followed by a function call (where the number and types in the function will vary, but the return type is the same), followed by more boiler plate code.
All opinions welcome! Thanks.
static Func<TResult> ConvertFunc<T, TResult>(Func<T, TResult> f1, T t)
{
return () => f1(t);
}
This kind of code to me looks a bit dangerous - not that by itself is anything wrong but need to be careful. You are using closure to embed an input variable in the function. But this could lead to difficult bugs since if the variable changes between converting Func and running it, the result would be different.
I am just curious what would be the benefit. Are you trying to hide away input parameter from the consumer of the function? As long as the variable is a local one passed to it, would be fine.
In terms of a solution, there would not be one since .NET has created 16 different generic Func<> exactly for the same reason.
You can perhaps use reflection to implement a solution but you would be paying a penalty for calling the functions. MethodInfo.GetGenericArguments() would give you the types and you then can use MethodInfo.MakeGenericMethod() to create new ones.
Update
Just to illustrate my point:
static int Double(int number)
{
return number * 2;
}
static void Main(string[] args)
{
int i = 2;
Func<int> f = () => Double(i);
i = 3;
Console.WriteLine(f()); // prints 6 and not 4
}
Is there any way that I can generalise the type definitions here?
Ideally, I'd like to be able to change the type of 'testInput' and have test correctly infer the type at compile time.
public static void Run()
{
var testInput = 3;
var test = ((Func<int, int>) Identity).Compose<int,int,int>(n => n)(testInput);
Console.WriteLine(test);
}
public static Func<T, V> Compose<T, U, V>(this Func<U, V> f, Func<T, U> g)
{
return x => f(g(x));
}
public static T Identity<T> (this T value)
{
return value;
}
Update:
I can specify the type of the function passed into Compose but this still specifies the type in the line.
public static void Run()
{
var testInput = 3;
var identity = (Func<int, int>) Identity;
var test = identity.Compose((int n) => n)(testInput);
Console.WriteLine(test);
}
A little context; I'm working through Wes Dyer's The Marvel of Monads
Well seeing as I'm on a roll for spewing out text tonight I'll have my own stab at it. I should note that I am no expert on the C# compiler, I haven't read the specification (any of them... for anything), and although that article you linked was really interesting, I'd be lying if I said I was any sort of expert on that either (or even understood it all 100%).
Caveats aside, my take on your question is this:
Is there any way that I can generalise
the type definitions here?
I think the short answer is no. With the information provided, there is simply not enough information for the type inference part of C#'s compiler to infer enough information from the usage of the various variables.
As the other answers here demonstrate, it can be simplified. You can use #Lee's IdentityFunc to allow for type inference with var identity. However, even with this addition, it is still not possible with your sample code to infer all the type variables of Compose.
Imagine the following situation:
public static Func<T, V> Compose<T, U, V>(this Func<U, V> f, Func<T, U> g)
{
return x => f(g(x));
}
public static T Identity<T> (this T value)
{
return value;
}
public static Func<T, T> IdentityFunc<T>(this T value)
{
return (Func<T, T>)Identity;
}
and
public static void Run()
{
var a = 3; // a is int
var i = a.IdentityFunc(); // i is Func<int, int>;
var test = i.Compose(n => n)(a) // test is expected to be int
}
Initially this might appear as if test should easily be inferred to int. However, the return type of i.Compose can only be inferred after the fact, from its usage. The C# compiler obviously won't allow this.
public static void Run()
{
var a = 3; // a is int
var i = a.IdentityFunc(); // i is Func<int, int>;
var c = i.Compose(n => n) // c is Func<T, int> - T cannot be resolved without knowledge of n
var test = c(a); // ideally have type inference infer c (Func<T, int>) as Func<int, int>
}
In that example, upon usage of c with a the compiler would have to retrospectively infer the return type of the call to i.Compose<T, U, V>(n => n) to be Func<int, int>. This is obviously not possible in the C# compiler. Take away the call c(a) and the compiler would have no knowledge of the usage of c, which would remove any possibility of inferring T (not that it can anyway). It is possible a more advanced type inference system would be able to do this sort of inferring based on the usage of a generic return (possibly F# - another topic I'm no expert on).
As Wes Dyer doesn't provide specific usage of that particular example, it's unknown whether there is some other magic he uses to allow for the degree of type inference you're trying to achieve.
More qualified people like Eric Lippert would be able to provide you with a much greater level of detail (and technical accuracy / acuity). I read a great response he wrote on here to a question on type inference, but I can't find it. His blog has lots of great information. You could try contacting him if you're interested. Also, his answer to this question here discusses monads (and ultimately links back to Wes Dyer's article) buy you might be interested in reading it: Monad in plain English? (For the OOP programmer with no FP background)
You could write an extension method to return the Identity function for a type:
public static Func<T, T> IdentityFunc<T>(this T value)
{
return (Func<T, T>)Identity;
}
(or just return v => value;)
Your test then becomes
var testInput = 3;
var identity = testInput.IdentityFunc();
test = identity.Compose((int n) => n)(testInput);
The closest I can get is to explicitly type the parameter for the n => n lambda:
var test = ((Func<int, int>)Identity).Compose((int n) => n)(testInput);
I don't think you can achieve your ideal; C# type inference does not work like that.
You might enjoy F#.
Just a little niggle about LINQ syntax. I'm flattening an IEnumerable<IEnumerable<T>> with SelectMany(x => x).
My problem is with the lambda expression x => x. It looks a bit ugly. Is there some static 'identity function' object that I can use instead of x => x? Something like SelectMany(IdentityFunction)?
Unless I misunderstand the question, the following seems to work fine for me in C# 4:
public static class Defines
{
public static T Identity<T>(T pValue)
{
return pValue;
}
...
You can then do the following in your example:
var result =
enumerableOfEnumerables
.SelectMany(Defines.Identity);
As well as use Defines.Identity anywhere you would use a lambda that looks like x => x.
Note: this answer was correct for C# 3, but at some point (C# 4? C# 5?) type inference improved so that the IdentityFunction method shown below can be used easily.
No, there isn't. It would have to be generic, to start with:
public static Func<T, T> IdentityFunction<T>()
{
return x => x;
}
But then type inference wouldn't work, so you'd have to do:
SelectMany(Helpers.IdentityFunction<Foo>())
which is a lot uglier than x => x.
Another possibility is that you wrap this in an extension method:
public static IEnumerable<T> Flatten<T>
(this IEnumerable<IEnumerable<T>> source)
{
return source.SelectMany(x => x);
}
Unfortunately with generic variance the way it is, that may well fall foul of various cases in C# 3... it wouldn't be applicable to List<List<string>> for example. You could make it more generic:
public static IEnumerable<TElement> Flatten<TElement, TWrapper>
(this IEnumerable<TWrapper> source) where TWrapper : IEnumerable<TElement>
{
return source.SelectMany(x => x);
}
But again, you've then got type inference problems, I suspect...
EDIT: To respond to the comments... yes, C# 4 makes this easier. Or rather, it makes the first Flatten method more useful than it is in C# 3. Here's an example which works in C# 4, but doesn't work in C# 3 because the compiler can't convert from List<List<string>> to IEnumerable<IEnumerable<string>>:
using System;
using System.Collections.Generic;
using System.Linq;
public static class Extensions
{
public static IEnumerable<T> Flatten<T>
(this IEnumerable<IEnumerable<T>> source)
{
return source.SelectMany(x => x);
}
}
class Test
{
static void Main()
{
List<List<string>> strings = new List<List<string>>
{
new List<string> { "x", "y", "z" },
new List<string> { "0", "1", "2" }
};
foreach (string x in strings.Flatten())
{
Console.WriteLine(x);
}
}
}
With C# 6.0 and if you reference FSharp.Core you can do:
using static Microsoft.FSharp.Core.Operators
And then you're free to do:
SelectMany(Identity)
With C# 6.0 things are getting better. We can define the identity function in the way suggested by #Sahuagin:
static class Functions
{
public static T It<T>(T item) => item;
}
And then use it in SelectMany the using static constructor:
using Functions;
...
var result = enumerableOfEnumerables.SelectMany(It);
I think it looks very laconic in the such way. I also find the identity function useful when building dictionaries:
class P
{
P(int id, string name) // Sad. We are not getting primary constructors in C# 6.0
{
ID = id;
Name = id;
}
int ID { get; }
int Name { get; }
static void Main(string[] args)
{
var items = new[] { new P(1, "Jack"), new P(2, "Jill"), new P(3, "Peter") };
var dict = items.ToDictionary(x => x.ID, It);
}
}
This may work in the way you want. I realize Jon posted a version of this solution, but he has a second type parameter which is only necessary if the resulting sequence type is different from the source sequence type.
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source)
where T : IEnumerable<T>
{
return source.SelectMany(item => item);
}
You can get close to what you need. Instead of a regular static function, consider an extension method for your IEnumerable<T>, as if the identity function is of the collection, not the type (a collection can generate the identity function of its items):
public static Func<T, T> IdentityFunction<T>(this IEnumerable<T> enumerable)
{
return x => x;
}
with this, you don't have to specify the type again, and write:
IEnumerable<IEnumerable<T>> deepList = ... ;
var flat = deepList.SelectMany(deepList.IdentityFunction());
This does feel a bit abusive though, and I'd probably go with x=>x. Also, you cannot use it fluently (in chaining), so it will not always be useful.
I'd go with a simple class with a single static property and add as many as required down the line
internal class IdentityFunction<TSource>
{
public static Func<TSource, TSource> Instance
{
get { return x => x; }
}
}
SelectMany(IdentityFunction<Foo>.Instance)