Skip to content

Instantly share code, notes, and snippets.

View dimitris-papadimitriou-chr's full-sized avatar
📖
Cloud Design Patterns

Dimitris Papadimitriou dimitris-papadimitriou-chr

📖
Cloud Design Patterns
View GitHub Profile
public abstract class Tree<T> { }
public class Node<T> : Tree<T>
{
public Tree<T> Left { get; }
public T Value { get; }
public Tree<T> Right { get; }
public Node(Tree<T> left, T value, Tree<T> right)
{
Left = left;
int? shape = null;
Shape shape = null;
Shape shape = new Rectangle
{
Width = 100,
Height = 100,
};
//this is valid for all the above
var t = shape.Map(x => x.ToString());
public static class FunctionalExt
{
public static T1 Map<T, T1>(this T @this, Func<T, T1> f) =>
@this switch
{
T value => f(value),
null => default,
};
}
public static class FunctionalExtensions
{
public static Maybe<T1> Bind<T, T1>(this Maybe<T> @this, Func<T, Maybe<T1>> f) =>
@this switch
{
None<T> { } => new None<T1>(),
Some<T> { Value: var v } => f(v),
};
}
public abstract class Maybe<T>
{
public Maybe<T1> Map<T1>(Func<T, T1> f) =>
this switch
{
None<T> { } => new None<T1>(),
Some<T> { Value: var v } => new Some<T1>(f(v)),
};
}
public class None<T> : Maybe<T>
public static Shape Scale(this Shape @this, Func<int, int> f) =>
@this switch
{
Rectangle { Height: var h, Width: var w } => new Rectangle { Height = f(h), Width = f(w) },
Circle { Radius: var r } => new Circle { Radius=f(r)},
};
using System;
using System.Reflection.Metadata.Ecma335;
namespace PracticalCSharp.Preliminaries.PatternMatch.Test
{
namespace Case1
{
abstract class Shape { }
class Rectangle : Shape
string GetShapeDescription1(Shape shape) =>
shape switch
{
Rectangle { Height: var h, Width: var w } => $"Found {h }x {w} rectangle",
Circle { Radius: var r } => $"found a circle with radius {r}",
};
string GetShapeDescription(Shape shape)
=> shape.MatchWith<string>(
rectangleCase: r => $"Found {r.Height}x {r.Width} rectangle",
circleCase: c => $"found a circle with radius {c.Radius}"
);
var description = GetShapeDescription(shape);
abstract class Shape
{
public abstract T MatchWith<T>(Func<Rectangle, T> rectangleCase, Func<Circle, T> circleCase);
}
class Rectangle : Shape
{
public int Width { get; set; }
public int Height { get; set; }
public override T MatchWith<T>(Func<Rectangle, T> rectangleCase, Func<Circle, T> circleCase)