Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Exercise 1: Functional programming using delegates and generics
- ===============================================================
- Exercise 1.3 (mandatory) Construct a generic method Compose that takes two functions and composes them.
- For example, if f has type Func<int, int> then Compose(f,f) should also be of type Func<int,
- int> and should actually be the same as Twice(f) known from the slides. But we should be able to compose
- any pair of functions if only the return type of the first matches the input type of the second.
- Suppose now, U is a subclass of T and f has type Func<T,T> and g has type Func<U,U>. Which of the
- expressions Compose(g,f) and Compose(f,g) is welltyped? Justify your answer.
- Hint. Recall that the interface Func is declared Func<in T, out U>.
- */
- using System;
- using System.Collections.Generic;
- namespace exercise_5
- {
- public class Exercise_5_1_3
- {
- // from slides
- public static Func<int,int> Twice(Func<int,int> f) {
- return x => f(f(x));
- }
- //public static Func<T, U> Compose<T, U>(Func<T, U> f, Func<T, U> g) {
- // raised:
- // /Users/pelle/itu/programming_language_concepts/programming_language_exercises/exercise_5/Exercise_5_1_3.cs(37,37): Error CS1594: Delegate `System.Func<T,U>' has some invalid arguments (CS1594) (exercise_5)
- public static Func<T, T> Compose<T>(Func<T, T> f, Func<T, T> g) {
- // f is calculated first the used and calculated by g
- return x => g(f(x));
- }
- public static void Main() {
- Console.WriteLine("Exercise_5_1_3");
- Console.WriteLine("show and try out the Twice() from slides:");
- var fun1 = Twice(x => 3*x);
- Console.WriteLine(fun1(1)); // expected 9 based upon 3*1 = 3 -> 3*3 = 9
- var t = fun1(2);
- Console.WriteLine(t); // expected 18 based upon 3*2 = 6 -> 3*6 = 18
- Console.WriteLine("show and try out the Compose() that takes two lambda functions:");
- Func<int, int> a = x => 3*x;
- Func<int, int> b = x => 3+x;
- Func<int, int> compose1 = Compose(a, b);
- Console.WriteLine(compose1(3)); // expected 9 based upon 3*3 = 9 -> 3+9 = 12
- // try out with mixed types int bool
- // but raises:
- // /Users/pelle/itu/programming_language_concepts/programming_language_exercises/exercise_5/Exercise_5_1_3.cs(52,52): Error CS0411: The type arguments for method `exercise_5.Exercise_5_1_3.Compose<T>(System.Func<T,T>, System.Func<T,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly (CS0411) (exercise_5)
- // try out 2:
- //
- // Func<int, bool> c = x => x % 2 == 0;
- // Func<bool, bool> d = x => x & true;
- //
- //
- // Func<int, bool> compose2 = Compose(c, d);
- //
- // try out 2:
- //
- // Func<int, int> c = x => 3*x;
- // Func<int, bool> d = x => x % 2 == 0;
- //
- // Func<int, bool> compose2 = Compose(c, d);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment